如何捕获“subprocess.call”的输出到一个文件?
在我的代码中,我有一行与此类似的行:
rval = subprocess.call(["mkdir",directoryName], shell=True)
我可以检查 rval
来查看它是 0
还是 1
,但如果是1
,我希望以文件格式获取命令“子目录或文件 ben 已存在。”
中的文本,以便我可以将其与另一个文件进行比较,如果我想确保文本是相同的。
是否可以有这样的一行,但我知道这行不通
rval = subprocess.call(["mkdir",directoryName], shell=True) >> filename
,所以无论命令发生什么,文本都会被捕获在 filename
中,并且 rval
仍然有返回码吗?
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."
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
subprocess 模块有一个内置的“check_output”函数来执行此操作:
The subprocess module has a built in 'check_output' function for doing this:
无论如何,您需要使用 try catch,因为如果返回代码非零,它会引发异常:)
You anyway need to use try catch because it throws exception if return code is non zero :)