如何获得使用 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'
>>>
最佳答案
如果您的 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
以获得相同的结果。
如下所述,您可以在 this other answer 中找到更详细的说明。 .
关于python - 检索 subprocess.call() 的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1996518/