I wonder how to execute a complicated external command from within python?
It works well in linux bash command line:
$ mysqldump --single-transaction -u myusername -pmypassword mydb mytable > mytable.sql
But it doesn't work from within python code:
subprocess.call(['mysqldump' '--single-transaction' '-u myusername' '-pmypasword' 'mydb' 'mytable' '>' 'mytable.sql'])
What's wrong with my python code?
Or I have to use os.system() ??
Please tell me how it can work from within python code, thanks in advance.
The problem is that >
isn't a command-line argument to the program. >
, in this context, is actually a shell output redirection operator. It gets processed by the shell itself, not by the mysqldump
program.
Python's subprocess
knows nothing about the shell, so it can't understand shell operators such as >
. It just tries to give >
and mytable.sql
to mysqldump
as arguments, which mysqldump
also does not understand, causing an error.
What you need to do is set up your subprocess to redirect its output. The way to do that in Python is:
with open('mytable.sql', 'w') as f:
subprocess.call(['mysqldump',
'--single-transaction',
'-u',
'myusername',
'-pmypasword',
'mydb',
'mytable'], stdout=f)
The stdout
argument to subprocess.call
allows you to direct your subprocess's output wherever you like, just as the >
shell operator does.