【问题标题】:Python subprocess.check_output(args) fails, while args executed via Windows command line work OKPython subprocess.check_output(args) 失败,而通过 Windows 命令行执行的 args 工作正常
【发布时间】:2015-04-11 14:25:25
【问题描述】:

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\6.wav --ModeBCast -oC:\\DO\\OUT\\outfile > C:\\DO\\OUT\\log.txt

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

【问题讨论】:

  • 在处理文件路径时使用原始字符串r"C:\DO.... 或使用/。您还需要 shell=True 作为参数字符串。
  • r?在args 之前或ąrgs 内的每条路径之前一次?
  • 要清楚,你可以使用r"C:\path\file""C:\\path\\file",如果你使用r"",它会更容易阅读。
  • 感谢@DietrichEpp。
  • shell=True 解决了它。

标签: python cmd subprocess


【解决方案1】:

> 是一个 shell 重定向操作符。要么在 shell 中运行命令,要么(更好)作为@Padraic Cunningham suggested 在 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 不适用。 shell=True 启动附加进程 (%COMSPEC%) 并更改 how the executable is searched 并更改 what characters should be escaped (what characters are metacharacters) — 除非必要,否则不要使用 shell=True

【讨论】:

    【解决方案2】:

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

    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,这通常不是一个好主意,使用上面的代码并简单地将输出重定向到文件可以很容易地实现。

    【讨论】:

      【解决方案3】:
      output = subprocess.check_output(args,shell=True)
      

      使用shell=True 运行它

      【讨论】:

        猜你喜欢
        • 2022-01-10
        • 1970-01-01
        • 2020-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多