I want to call a subprocess to backup mysql database.
A command line which ran fine in the terminal (and created a file named mydatabase.sql) is:
mysqldump -uroot -ppassword --add-drop-database --database mydatabase > mydatabase.sql
Now the code to be ran by python to call a subprocess:
args = shlex.split('mysqldump -uroot -ppassword --add-drop-database --database mydatabase > mydatabase.sql')
subprocess.check_call(args)
The exeption is raised (no file created):
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
subprocess.check_call(args)
File "/usr/lib/python3.2/subprocess.py", line 485, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['mysqldump', >'-uroot', '-ppassword', '--add-drop-database', '--database', >'mydatabase', '>', 'mydatabase.sql']' returned non-zero exit status 2
I have tried different ways, but they still don’t work:
args = shlex.split('/opt/lampp/bin/mysqldump -uroot -ppassword --add-drop-database --database mydatabase > mydatabase.sql')
subprocess.check_call(args)
or
args = shlex.split('/opt/lampp/bin/mysqldump -uroot -ppassword --add-drop-database --database mydatabase > mydatabase.sql')
subprocess.Popen(args)
I also tried with shell=True or or shell=False. In both cases, they still don’t work.
I have read the docs, google for the answer for my problem, but I haven’t got a clue how to show my problem. stackoverflow is probably my last hope.
the problem here is the way you’re redirecting the output.
">"will always be interpreted as a literal>, no matter if you useshell=Trueorshell=Falseshell=True.the best way do do what you want would be to redirect the output to a file directly from python: