【问题标题】:How to capture the output from "subprocess.call" to a file?如何将“subprocess.call”的输出捕获到文件中?
【发布时间】:2011-04-28 03:37:17
【问题描述】:

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

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

我可以检查rval 以查看它是0 还是1,但如果是1,我希望将命令"A subdirectory or file ben already exists." 中的文本以文件格式保存,所以如果我想确保文本相同,我可以将它与另一个文件进行比较。

是否可以有这样的一行,但我知道这行不通

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

所以无论该命令发生什么,文本都被捕获在filename 中,而rval 仍然有返回码?

【问题讨论】:

  • Capture subprocess output的可能重复
  • 你为什么不使用 Python 的内置 mkdir()
  • 我这样做是为了一个我不能在这里发布的命令,但它具有与 mkdir 相似的特性。
  • @S.Lott,它几乎是重复的。区别在于Popencall(我同意这是微妙的),以及写入文件而不是捕获程序中的输出的愿望。尽管提问者似乎更愿意捕获输出,但按原样回答问题很有用。

标签: python subprocess


【解决方案1】:

子进程模块有一个内置的'check_output'函数来做这个:

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

In [12]: print result
/home/vagrant

【讨论】:

  • 但是你失去了退出值:(
  • 请注意,check_output 仅在 2.7 之后才有可能
【解决方案2】:
import subprocess
f = open(r'c:\temp\temp.txt','w')
subprocess.call(['dir', r'c:\temp'], shell=True, stdout=f)
f.close()

【讨论】:

  • 在这种情况下你为什么使用'shell=True'?因为我读到这是一个坏主意(至少在 *nix 上)。
  • @PulpFiction,有两个原因:首先它包含在原始问题中,其次我使用 Windows shell 命令进行测试。
【解决方案3】:
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,因为如果返回码不为零,它会引发异常:)

【讨论】:

  • 使用except CalledProcessError as e: returncode=e.returncode会更简单。
猜你喜欢
  • 2018-11-01
  • 2012-11-23
  • 1970-01-01
  • 1970-01-01
  • 2014-11-15
  • 1970-01-01
  • 2012-06-07
  • 2011-01-18
  • 2020-02-28
相关资源
最近更新 更多