如何防止子进程在某些参数之间添加空格?

Cyr*_*lle 2 python subprocess python-2.7

我想使用 Python 及其subprocess模块从 Linux 执行一些 Mysql 命令。

没有 Python,从 shell 中,我的命令行是:

mysql --database=mydb --host=localhost --port=3306 --password=  --execute="select * from mytable" --batch
Run Code Online (Sandbox Code Playgroud)

使用 Python,我有:

cmd = ['mysql']
cmd.extend(['--database=', self._database])
cmd.extend(['--password=', self._password])
cmd.extend(['--execute=', query])

(...)

p = subprocess.Popen(cmd, shell = False, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
out, err = p.communicate()
errcode = p.returncode
Run Code Online (Sandbox Code Playgroud)

不幸的是,它不起作用(mysql 只是打印用法),我认为,子进程会生成这种输出(' '.join(cmd)):

mysql --database= mydb --host= localhost --port= 3306 --password=  --execute= "select * from mytable" --batch
Run Code Online (Sandbox Code Playgroud)

IE。每个参数之间添加空格,分隔=和值。

当我删除=每个参数 ( cmd.extend(['--password', self._password])) 时,它工作正常,除非参数为空(因此,我测试每个参数是否为空,然后在需要时将其删除)。

最后,我通过测试 void 参数找到了一种解决方法,但为了将来参考,是否有任何我不知道处理这种类型的子流程提示或用法parameter=?必须有一些应用程序时,你必须使用=的,我尽量避免Shell=True

Dav*_*ker 6

将其更改为

cmd = [
    'mysql',
    '--database=%s' % self._database,
    '--password=%s' % self._password,
    '--execute=%s' % query
]

(...)

p = subprocess.Popen(cmd, shell = False, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
out, err = p.communicate()
errcode = p.returncode
Run Code Online (Sandbox Code Playgroud)

这样参数列表包含带有各自参数的开关