如何获得使用 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'
>>>
原文由 Jeffrey Aylesworth 发布,翻译遵循 CC BY-SA 4.0 许可协议
subprocess.call()
的输出应该只重定向到文件。您应该使用
subprocess.Popen()
代替。然后,您可以将subprocess.PIPE
传递给 stderr、stdout 和/或 stdin 参数,并使用communicate()
方法从管道中读取:推理是
subprocess.call()
使用的类文件对象必须有一个真实的文件描述符,从而实现fileno()
方法。仅仅使用任何类似文件的对象都不会成功。请参阅 此处 了解更多信息。