如何捕获“subprocess.call”的输出到一个文件?

发布于 2024-09-28 00:37:57 字数 496 浏览 1 评论 0原文

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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

温暖的光 2024-10-05 00:37:57

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

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

In [12]: print result
/home/vagrant

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

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

In [12]: print result
/home/vagrant
笛声青案梦长安 2024-10-05 00:37:57
import subprocess
f = open(r'c:\temp\temp.txt','w')
subprocess.call(['dir', r'c:\temp'], shell=True, stdout=f)
f.close()
import subprocess
f = open(r'c:\temp\temp.txt','w')
subprocess.call(['dir', r'c:\temp'], shell=True, stdout=f)
f.close()
顾挽 2024-10-05 00:37:57
import subprocess

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

无论如何,您需要使用 try catch,因为如果返回代码非零,它会引发异常:)

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 :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文