How to get both return code and output from subprocess in Python?(如何从 Python 中的子进程获取返回码和输出?)
问题描述
在为 Android Debug Bridge (ADB) 开发 python 包装库时,我使用 subprocess 在 shell 中执行 adb 命令.这是简化的示例:
While developing python wrapper library for Android Debug Bridge (ADB), I'm using subprocess to execute adb commands in shell. Here is the simplified example:
import subprocess
...
def exec_adb_command(adb_command):
return = subprocess.call(adb_command)
如果命令正确执行 exec_adb_command 返回 0 即可.
If command executed propery exec_adb_command returns 0 which is OK.
但是一些 adb 命令不仅返回0"或1",而且还生成一些我想捕获的输出.adb 设备 例如:
But some adb commands return not only "0" or "1" but also generate some output which I want to catch also. adb devices for example:
D:gitadb-lib est>adb devices
List of devices attached
07eeb4bb device
我已经为此尝试过 subprocess.check_output(),它确实返回输出但不返回返回码(0"或1").
I've already tried subprocess.check_output() for that purpose, and it does return output but not the return code ("0" or "1").
理想情况下,我希望得到一个元组,其中 t[0] 是返回码,t[1] 是实际输出.
Ideally I would want to get a tuple where t[0] is return code and t[1] is actual output.
我是否在子流程模块中遗漏了一些已经允许获得这种结果的东西?
Am I missing something in subprocess module which already allows to get such kind of results?
谢谢!
推荐答案
Popen and communication 将允许您获取输出和返回码.
Popen and communicate will allow you to get the output and the return code.
from subprocess import Popen,PIPE,STDOUT
out = Popen(["adb", "devices"],stderr=STDOUT,stdout=PIPE)
t = out.communicate()[0],out.returncode
print(t)
('List of devices attached
', 0)
check_output 也可能是合适的,非零退出状态将引发 CalledProcessError:
check_output may also be suitable, a non-zero exit status will raise a CalledProcessError:
from subprocess import check_output, CalledProcessError
try:
out = check_output(["adb", "devices"])
t = 0, out
except CalledProcessError as e:
t = e.returncode, e.message
你还需要重定向stderr来存储错误输出:
You also need to redirect stderr to store the error output:
from subprocess import check_output, CalledProcessError
from tempfile import TemporaryFile
def get_out(*args):
with TemporaryFile() as t:
try:
out = check_output(args, stderr=t)
return 0, out
except CalledProcessError as e:
t.seek(0)
return e.returncode, t.read()
只需传递您的命令:
In [5]: get_out("adb","devices")
Out[5]: (0, 'List of devices attached
')
In [6]: get_out("adb","devices","foo")
Out[6]: (1, 'Usage: adb devices [-l]
')
这篇关于如何从 Python 中的子进程获取返回码和输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 Python 中的子进程获取返回码和输出?
基础教程推荐
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 包装空间模型 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 求两个直方图的卷积 2022-01-01
