I have written two small functions in Python to call mysqldump and mysql from console, so I am able to create a database backup and then restore it:
# Makes a backup current database status
def backupDatabase():
if(os.path.exists('myDatabaseBackup.sql')):
os.remove('myDatabaseBackup.sql')
call(['mysqldump', '-u myUsername myDatabase > myDatabaseBackup.sql'])
# Restores database
def restoreDatabase():
call(['mysql', '-u myUsername myDatabase < myDatabaseBackup.sql'])
Nevertheless, they are not working. I have read that call gets two values: the executable and the parameters, but it looks that parameters are being ignored, since the output after calling backupDatabase is:
Usage: mysqldump [OPTIONS] database [tables] OR … For more options,
se mysqldump –help
What’s wrong? I know I could use Pipes (I don’t know how at the moment, just know they exist and are an alternative), but since this looks like a pretty simple task I guess subprocess.call should be enough. So, is it possible to fix this with subprocess.call? (If not, please provide some help for Pipes or any other solution).
Also, I’m using MySQLdb package for other purposes, so if it is possible to backup and restore somehow using this package, it would be great.
First of all,
subprocess.callexpects you to pass each command line parameter separately, like this:Second, to redirect the output, you pass additional
stdoutargument, which, among other things, can be an open file object:(For the second redirection you naturally use
stdin. More details are in FAQ)