如何将Python的subprocess.call()输出重定向到文件?

时间:2014-07-22 09:45:43

标签: python

我从Python调用exe工具:

args = '-i' + inputFile
cl = ['info.exe', args]
subprocess.call(cl)

如何将info.exe的输出重定向到out.txt

1 个答案:

答案 0 :(得分:5)

您可以通过将输出指定为subprocess.callstdout参数,将输出重定向到文件对象。将它放在上下文管理器中以安全地写入文件。

with open('out.txt', 'w') as f:
    subprocess.call(cl, stdout=f)

或者以wb模式打开文件并使用subprocess.check_output

with open('out.txt', 'wb') as f:
    f.write(subprocess.check_output(cl))