Forums

sqlite db backup using python script and subprocess

Trying to backup the sqlite db using a python script using subprocess. I get the following error message: File Not Found: 'sqlite3 /home/<myusername>/<djangoapp>/db.sqlite3 ".backup \'/home/<myusername>/<djangoapp>/db_backup_20231205\'"'

The following Python statement works in Python on Windows, but fails per the noted error message in Python Anywhere when the .py file is run.

process_output = subprocess.run('sqlite3 /home/<myusername>/<djangoapp>/db.sqlite3' + '".backup \'/home/<myusername>/<djangoapp>/sqlite3_backup/db_backup_20231205\'"')

The following (one line) command works in Python Anywhere from the bash console: sqlite3 /home/<myusername>/<djangoapp>/db.sqlite3 ".backup '/home/<myusername>/<djangoapp>/sqlite3_backup/db_backup_20231205'"

Guessing the problem has something to do with the string escape character "\" processing problem

You need to use the full path to the sqlite executable. You can find it by running which sqlite3

Thanks for the answer. The error changed a little bit with "[Errno 2]" added. FileNotFoundError: [Errno 2] No such file or directory: '/usr/bin/sqlite3 /home/<myusername>/<djangoapp>/db.sqlite3".backup \'/home/<myusername>/<djangoapp>/sqlite3_backup/db_backup_20231205\'"'

Any other suggestions?

Fixed the problem by submitting the command and parameters as an array instead of a long string.

process_output = subprocess.run( [ '/usr/bin/sqlite3', '/home/<myusername>/<djangoapp>/db.sqlite3', ".backup /home/<myusername>/<djangoapp>/sqlite3_backup/db_backup_20231205'" ] )

Glad to hear you got it working! An alternative solution would have been to add the kwarg shell=True to the end -- then you could still use a long string instead of needing a list of strings.