Python subprocess.call seems to ignore parameters

◇◆丶佛笑我妖孽 提交于 2019-12-13 02:27:26

问题


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.


回答1:


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)




回答2:


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)


来源:https://stackoverflow.com/questions/14600294/python-subprocess-call-seems-to-ignore-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!