Python subprocess.call似乎忽略了参数 [英] Python subprocess.call seems to ignore parameters

查看:278
本文介绍了Python subprocess.call似乎忽略了参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用Python编写了两个小函数来从控制台调用mysqldumpmysql,因此我能够创建数据库备份,然后将其还原:

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'])

尽管如此,它们仍无法正常工作.我已经读过该调用有两个值:可执行文件和参数,但是看起来参数被忽略了,因为调用backupDatabase之后的输出是:

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:

用法:mysqldump [OPTIONS]数据库[tables]或...有关更多选项, se mysqldump-帮助

Usage: mysqldump [OPTIONS] database [tables] OR ... For more options, se mysqldump --help

怎么了?我知道我可以使用Pipes(我现在不知道怎么做,只知道它们存在并且可以替代),但是由于这看起来很简单,我想subprocess.call应该就足够了.因此,是否可以用subprocess.call修复此问题? (如果没有,请提供有关Pipes或任何其他解决方案的帮助.)

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).

此外,我将MySQLdb软件包用于其他目的,因此,如果可以使用此软件包进行某种方式的备份和还原,那就太好了.

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.

推荐答案

首先,subprocess.call希望您分别传递每个命令行参数,如下所示:

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

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

第二,要重定向输出,请传递附加的stdout参数,该参数除其他外可以是一个打开的文件对象:

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)

(对于第二种重定向,您自然会使用stdin.更多详细信息,请参见常见问题解答)

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

这篇关于Python subprocess.call似乎忽略了参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆