小编典典

Python-检索subprocess.call()的输出

python

我如何获得使用运行的流程的输出subprocess.call()

StringIO.StringIO对象传递stdout给此错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 444, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 588, in __init__
    errread, errwrite) = self._get_handles(stdin, stdout, stderr)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 945, in _get_handles
    c2pwrite = stdout.fileno()
AttributeError: StringIO instance has no attribute 'fileno'
>>> 

阅读 1001

收藏
2020-02-14

共2个答案

小编典典

输出subprocess.call()仅应重定向到文件。

你应该subprocess.Popen()改用。然后,你可以传递subprocess.PIPEstderr,stdout和/或stdin参数,并使用以下communicate()方法从管道读取:

from subprocess import Popen, PIPE

p = Popen(['program', 'arg1'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate(b"input data that is passed to subprocess' stdin")
rc = p.returncode

原因是所使用的类似文件的对象subprocess.call()必须具有真实的文件描述符,从而实现该fileno()方法。仅使用任何类似文件的对象都无法解决问题。

2020-02-14
小编典典

如果你的Python版本> = 2.7,则可以使用subprocess.check_output,它基本上可以完成你想要的操作(它以字符串形式返回标准输出)。

简单示例(Linux版本,请参见注释):

import subprocess

print subprocess.check_output(["ping", "-c", "1", "8.8.8.8"])

请注意,ping命令使用的是Linux表示法(-c用于计数)。如果你在Windows上尝试此操作,请记住将其更改-n为相同的结果。

如下所述,你可以在其他答案中找到更详细的说明。

2020-02-14