[英]How to capture the output from “subprocess.call” to a file?
In my code I have a line similar to this: 在我的代码中,我有一个类似于这样的行:
rval = subprocess.call(["mkdir",directoryName], shell=True)
and I can check rval
to see if it is 0
or 1
, but if it is 1
, I would like to have the text from the command "A subdirectory or file ben already exists."
我可以检查
rval
以查看它是0
还是1
,但如果它是1
,我希望命令"A subdirectory or file ben already exists."
的文本"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. 在文件格式中,如果我想确保文本是相同的,我可以将它与另一个文件进行比较。
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 rval
still has the return code? 所以无论命令发生了什么,文本都是在
filename
捕获的,而rval
仍然有返回码?
The subprocess module has a built in 'check_output' function for doing this: 子进程模块具有内置的'check_output'功能,用于执行此操作:
In [11]: result = subprocess.check_output(['pwd'])
In [12]: print result
/home/vagrant
import subprocess
f = open(r'c:\temp\temp.txt','w')
subprocess.call(['dir', r'c:\temp'], shell=True, stdout=f)
f.close()
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,因为如果返回代码非零,它会抛出异常:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.