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, i.e. delete the backup-12-11-2019.sql only after backup-13-11-2019 was created successfully
Delete existing file after successful write
82 views Asked by zamponotyropita At
2
There are 2 answers
0
On
you can use try:...except:...esle: as the following code.
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
Best regard
From DBA StackExchange
And SO: Get return value
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.