简体   繁体   English

写入成功后删除现有文件

[英]Delete existing file after successful write

I am performing a daily database dump in a python script and I am looking for the most python efficient way to delete the current file only after the recent one was written successfully, ie delete the backup-12-11-2019.sql only after backup-13-11-2019 was created successfully我在 python 脚本中执行每日数据库转储,我正在寻找最有效的 python 方法,仅在最近的文件写入成功后才删除当前文件,即仅在备份后删除备份 12-11-2019.ZAC5C74B64B4B8352EF2F18 -13-11-2019 创建成功

you can use try:...except:...esle: as the following code.您可以使用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')

If the pg_dumpall does not raise and Exception it will delete the previous backup file如果pg_dumpall没有引发Exception ,它将删除以前的备份文件

Best regard最良好的问候

From DBA StackExchange来自DBA StackExchange

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

And SO: Get return value SO:获取返回值

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

We're able to come up with something that will run the command you want to run, and check its return value at the same time.我们能够想出一些东西来运行你想要运行的命令,同时检查它的返回值。

    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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM