【问题标题】:Delete existing file after successful write写入成功后删除现有文件
【发布时间】:2019-11-13 15:25:53
【问题描述】:

我在 python 脚本中执行每日数据库转储,我正在寻找最有效的 python 方法来删​​除当前文件,仅在最近的文件成功写入后,即删除 backup-12-11-2019.sql仅在成功创建 backup-13-11-2019 之后

【问题讨论】:

  • 你是怎么写备份文件的?你能附上一些代码吗?
  • 尝试:pg_dumpall('-h', DB_HOST, '-U', DB_USERNAME, '-p', DB_PORT, _out=BACKUP_FOLDER + 'backup-' + str(now.day) + ' -' + str(now.month) + '-' + str(now.year) +'.sql') 例外为 e: print(e)

标签: python pg-dumpall


【解决方案1】:

您可以使用try:...except:...esle:作为以下代码。

import datetime
import os
now = datetime.datetime.utcnow()
try:
    pg_dumpall('-h', DB_HOST, '-U', DB_USERNAME, '-p', DB_PORT, _out=BACKUP_FOLDER + 'backup-' + str(now.day) + '-' + str(now.month) + '-' + str(now.year) + '.sql')
except Exception as e:
    print(e)
else:
    previous_day = now - datetime.timedelta(days=1)
    os.remove(BACKUP_FOLDER + 'backup-' + str(now.day - 1) + '-' + str(now.month) + '-' + str(now.year) + '.sql')

如果pg_dumpall 没有出现,Exception 会删除之前的备份文件

最好的尊重

【讨论】:

    【解决方案2】:

    来自DBA StackExchange

        pg_dumpall -U pg_user > /tmp/tmp.txt
        DUMP_STATUS=$?
        echo "Dump status: $DUMP_STATUS" > /tmp/status.txt
    

    还有SO: Get return value

        subprocess.check_output([SCRIPT, "-d", date], shell=True).
    

    我们能够想出一些东西来运行你想要运行的命令,同时检查它的返回值。

        output = subprocess.check_output(['pg_dumpall', '-h', DB_HOST, '-U', DB_USERNAME, '-p', DB_PORT], stdout=outfile)
        if output == 0:
            print("Success")
            os.remove(oldfile)
        else:
            print("Failure")
    

    【讨论】:

      猜你喜欢
      • 2013-10-01
      • 2019-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-07
      • 2020-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多