Python 如何将“subprocess.call”的输出捕获到文件中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3979888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:40:07  来源:igfitidea点击:

How to capture the output from "subprocess.call" to a file?

pythonsubprocess

提问by Dag

In my code I have a line similar to this:

在我的代码中,我有一行类似于:

rval = subprocess.call(["mkdir",directoryName], shell=True)

and I can check rvalto see if it is 0or 1, but if it is 1, I would like to have the text from the command "A subdirectory or file ben already exists."in a file format, so I can compare it to another file if I want to make sure the text is the same.

我可以检查rval它是否是01,但如果是1,我希望命令"A subdirectory or file ben already exists."中的文本采用文件格式,因此如果我想确保文本相同,我可以将其与另一个文件进行比较.

Is it possible to have a line like this, but I know this does not work

有没有可能有这样的一条线,但我知道这行不通

rval = subprocess.call(["mkdir",directoryName], shell=True) >> filename

so no matter what happens with the command, the text is captured in filename, and rvalstill has the return code?

所以无论命令发生什么,文本都会被捕获filename,并且rval仍然有返回码?

采纳答案by Mark Ransom

import subprocess
f = open(r'c:\temp\temp.txt','w')
subprocess.call(['dir', r'c:\temp'], shell=True, stdout=f)
f.close()

回答by btubbs

The subprocess module has a built in 'check_output' function for doing this:

subprocess 模块有一个内置的“check_output”函数来执行此操作:

In [11]: result = subprocess.check_output(['pwd'])

In [12]: print result
/home/vagrant

回答by Jatin Kumar

import subprocess

try:
    result = subprocess.check_output(['dir', r'c:\temp'], shell=True)
    print result
except subprocess.CalledProcessError as e:
    return_code = e.returncode

You anyway need to use try catch because it throws exception if return code is non zero :)

你无论如何都需要使用 try catch 因为如果返回代码非零它会抛出异常:)