Retrieving the output of subprocess.call()(检索 subprocess.call() 的输出)
问题描述
如何获得使用 subprocess.call() 运行的进程的输出?
How can I get the output of a process run using subprocess.call()?
将 StringIO.StringIO 对象传递给 stdout 会出现以下错误:
Passing a StringIO.StringIO object to stdout gives this error:
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() 的输出只能重定向到文件.
Output from subprocess.call() should only be redirected to files.
您应该改用 subprocess.Popen().然后,您可以为 stderr、stdout 和/或 stdin 参数传递 subprocess.PIPE,并使用 communicate() 方法从管道中读取:
You should use subprocess.Popen() instead. Then you can pass subprocess.PIPE for the stderr, stdout, and/or stdin parameters and read from the pipes by using the communicate() method:
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()方法.仅使用任何类似文件的对象都无法解决问题.
The reasoning is that the file-like object used by subprocess.call() must have a real file descriptor, and thus implement the fileno() method. Just using any file-like object won't do the trick.
请参阅此处了解更多信息.
这篇关于检索 subprocess.call() 的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检索 subprocess.call() 的输出
基础教程推荐
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 包装空间模型 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
