检索 subprocess.call() 的输出[重复]
- 2024-12-16 08:35:00
- admin 原创
- 125
问题描述:
如何获取使用运行的进程的输出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'
解决方案 1:
如果您拥有 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
以获得相同的结果。
如下面所评论的,您可以在另一个答案中找到更详细的解释。
解决方案 2:
输出subprocess.call()
应该仅重定向到文件。
您应该使用subprocess.Popen()
。然后,您可以传递subprocess.PIPE
stderr、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()
方法。仅使用任何类文件对象都无法解决问题。
请参阅此处以了解更多信息。
解决方案 3:
对于 Python 3.5 或更高版本,建议使用subprocess 模块中的 run 函数。它将返回一个CompletedProcess
对象,您可以从中轻松获取输出以及返回代码。
from subprocess import PIPE, run
command = ['echo', 'hello']
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(result.returncode, result.stdout, result.stderr)
解决方案 4:
我有以下解决方案。它捕获执行的外部命令的退出代码、stdout 和 stderr:
import shlex
from subprocess import Popen, PIPE
def get_exitcode_stdout_stderr(cmd):
"""
Execute the external command and get its exitcode, stdout and stderr.
"""
args = shlex.split(cmd)
proc = Popen(args, stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
exitcode = proc.returncode
#
return exitcode, out, err
cmd = "..." # arbitrary external command, e.g. "python mytest.py"
exitcode, out, err = get_exitcode_stdout_stderr(cmd)
我在这里也发表了一篇关于该内容的博客文章。
编辑:解决方案已更新为不需要写入临时文件的较新解决方案。
解决方案 5:
我最近刚刚弄清楚如何做到这一点,下面是我当前项目中的一些示例代码:
#Getting the random picture.
#First find all pictures:
import shlex, subprocess
cmd = 'find ../Pictures/ -regex ".*(JPG|NEF|jpg)" '
#cmd = raw_input("shell:")
args = shlex.split(cmd)
output,error = subprocess.Popen(args,stdout = subprocess.PIPE, stderr= subprocess.PIPE).communicate()
#Another way to get output
#output = subprocess.Popen(args,stdout = subprocess.PIPE).stdout
ber = raw_input("search complete, display results?")
print output
#... and on to the selection process ...
现在,命令的输出已存储在变量“output”中。“stdout = subprocess.PIPE”指示类在 Popen 中创建一个名为“stdout”的文件对象。据我所知,communication() 方法只是一种方便的方式来返回输出的元组和您运行的进程的错误。此外,实例化 Popen 时会运行该进程。
解决方案 6:
关键是使用函数subprocess.check_output
例如,以下函数捕获进程的 stdout 和 stderr 并返回该信息以及调用是否成功。它兼容 Python 2 和 3:
from subprocess import check_output, CalledProcessError, STDOUT
def system_call(command):
"""
params:
command: list of strings, ex. `["ls", "-l"]`
returns: output, success
"""
try:
output = check_output(command, stderr=STDOUT).decode()
success = True
except CalledProcessError as e:
output = e.output.decode()
success = False
return output, success
output, success = system_call(["ls", "-l"])
如果您想将命令作为字符串而不是数组传递,请使用此版本:
from subprocess import check_output, CalledProcessError, STDOUT
import shlex
def system_call(command):
"""
params:
command: string, ex. `"ls -l"`
returns: output, success
"""
command = shlex.split(command)
try:
output = check_output(command, stderr=STDOUT).decode()
success = True
except CalledProcessError as e:
output = e.output.decode()
success = False
return output, success
output, success = system_call("ls -l")
解决方案 7:
在Ipython
shell 中:
In [8]: import subprocess
In [9]: s=subprocess.check_output(["echo", "Hello World!"])
In [10]: s
Out[10]: 'Hello World!
'
基于萨格的回答。归功于萨尔格。
- 2025年20款好用的项目管理软件推荐,项目管理提效的20个工具和技巧
- 2024年开源项目管理软件有哪些?推荐5款好用的项目管理工具
- 2024年常用的项目管理软件有哪些?推荐这10款国内外好用的项目管理工具
- 项目管理软件有哪些?推荐7款超好用的项目管理工具
- 项目管理软件有哪些最好用?推荐6款好用的项目管理工具
- 项目管理软件哪个最好用?盘点推荐5款好用的项目管理工具
- 项目管理软件排行榜:2024年项目经理必备5款开源项目管理软件汇总
- 项目管理必备:盘点2024年13款好用的项目管理软件
- 项目管理软件有哪些,盘点推荐国内外超好用的7款项目管理工具
- 2024项目管理软件排行榜(10类常用的项目管理工具全推荐)