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
Asked
Active
Viewed 62 times
0
-
How are you writing the backup file? Can you attach some code? – shashwat Nov 13 '19 at 15:29
-
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) – zamponotyropita Nov 13 '19 at 15:30
2 Answers
1
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

TOTO
- 307
- 1
- 6
0
From DBA StackExchange
pg_dumpall -U pg_user > /tmp/tmp.txt
DUMP_STATUS=$?
echo "Dump status: $DUMP_STATUS" > /tmp/status.txt
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")

shashwat
- 992
- 1
- 13
- 27