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

我如何获得使用运行的流程的输出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'

>>>

回答:

输出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()方法。仅使用任何类似文件的对象都无法解决问题。

以上是 Python-检索subprocess.call()的输出 的全部内容, 来源链接: utcz.com/qa/430298.html

回到顶部