Roman Rdgz
Roman Rdgz

Reputation: 13254

Python subprocess.call seems to ignore parameters

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.

Upvotes: 1

Views: 1328

Answers (2)

bereal
bereal

Reputation: 34272

First of all, subprocess.call expects you to pass each command line parameter separately, like this:

subprocess.call(['mysqldump', '-u', 'myUsername'])

Second, to redirect the output, you pass additional stdout argument, which, among other things, can be an open file object:

with open('myDatabaseBackup.sql', 'w') as fout:
    subprocess.call(['mysqldump', '-u', 'myUsername'], stdout=fout)

(For the second redirection you naturally use stdin. More details are in FAQ)

Upvotes: 2

NPE
NPE

Reputation: 500257

Redirection operators < and > are processed by the shell. If there's no shell, they won't work.

Try passing shell=True to call():

call(['mysqldump', '-u myUsername myDatabase > myDatabaseBackup.sql'], shell=True)
call(['mysql', '-u myUsername myDatabase < myDatabaseBackup.sql'], shell=True)

Upvotes: 1

Related Questions