Python subprocess.check_output(args) 失败,而通过 Windows 命令行执行的 args 正常

Python subprocess.check_output(args) fails, while args executed via Windows command line work OK

pythonsubprocess.check_output 存在一些问题。

output = subprocess.check_output(args)

我的 args 是:

args = "C:\DO\bin\Config.exe --ChCfg7 --LFE -b1152000 C:\DO\PCM\1.wav C:\DO\PCM\2.wav C:\DO\PCM\3.wav C:\DO\PCM\4.wav C:\DO\PCM\5.wav C:\DO\PCM.wav --ModeBCast -oC:\DO\OUT\outfile > C:\DO\OUT\log.txt

这在从标准 windows 命令行执行时有效,但在通过 Python subprocess.check_output 执行时无效。在 win cmd 的情况下,产生了输出文件和 log.txt,python 脚本产生了大小为 0 的文件,根本没有 log.txt。

output = subprocess.check_output(args,shell=True)

运行 这与 shell=True

使用参数列表并将输出重定向到文件:

import subprocess

args = ['C:/DO/bin/Config.exe', '--ChCfg7', '--LFE', '-b1152000', 'C:/DO/PCM/1.wav', 'C:/DO/PCM/2.wav', 'C:/DO/PCM/3.wav', 'C:/DO/PCM/4.wav', 'C:/DO/PCM/5.wav', 'C:/DO/PCM/6.wav', '--ModeBCast', '-oC:/DO/OUT/outfile']

with open("C:/DO/OUT/log.txt", "w") as f:
    subprocess.check_call(args, stdout=f)

您可以使用 shell=True,但对于 security reasons 通常这不是一个好主意,使用上面的代码并简单地将输出重定向到文件可以很容易地实现相同的目的。

> 是一个 shell 重定向运算符。 运行 shell 中的命令或(更好) 在 Python 中模拟它:

#!/usr/bin/env python
import subprocess

args = r"C:\DO\bin\Config.exe --ChCfg7 --LFE -b1152000".split()
args += [r'C:\DO\PCM\%d.wav' % i for i in range(1, 7)]
args += ["--ModeBCast", r"-oC:\DO\OUT\outfile"]    
with open(r"C:\DO\OUT\log.txt", "wb", 0) as output_file:
    subprocess.check_call(args, stdout=output_file)

代码对 Windows 路径使用原始字符串文字以避免转义反斜杠。

通常没有必要在 Windows 上使用 shell=True,除非您想 运行 一个内置命令,例如 dir。如果 args 不是使用来自外部源的输入构建的,那么 security considerations do not apply. shell=True starts additional process (%COMSPEC%) and it changes how the executable is searched and it changes — 除非必要,否则不要使用 shell=True