如何从 Python 中的子进程获取返回码和输出?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30937829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:11:41  来源:igfitidea点击:

How to get both return code and output from subprocess in Python?

pythonsubprocessadb

提问by Viktor Malyi

While developing python wrapper library for Android Debug Bridge (ADB), I'm using subprocessto execute adb commands in shell. Here is the simplified example:

在为 Android Debug Bridge (ADB) 开发 python 包装库时,我使用进程在 shell 中执行 adb 命令。这是一个简化的例子:

import subprocess

...

def exec_adb_command(adb_command):
    return = subprocess.call(adb_command)

If command executed propery exec_adb_commandreturns 0 which is OK.

如果命令执行属性 exec_adb_command返回 0,这是正常的。

But some adb commands return not only "0" or "1" but also generate some output which I want to catch also. adb devicesfor example:

但是一些 adb 命令不仅返回“0”或“1”,而且还生成一些我也想捕获的输出。以 adb 设备为例:

D:\git\adb-lib\test>adb devices
List of devices attached
07eeb4bb        device

I've already tried subprocess.check_output()for that purpose, and it does return output but not the return code ("0" or "1").

我已经为此目的尝试了subprocess.check_output(),它确实返回输出但不返回代码(“0”或“1”)。

Ideally I would want to get a tuple where t[0] is return code and t[1] is actual output.

理想情况下,我希望得到一个元组,其中 t[0] 是返回码,而 t[1] 是实际输出。

Am I missing something in subprocess module which already allows to get such kind of results?

我是否在 subprocess 模块中遗漏了一些已经允许获得这种结果的东西?

Thanks!

谢谢!

采纳答案by Padraic Cunningham

Popen and communicate will allow you to get the output and the return code.

Popen 和communication 将允许您获得输出和返回码。

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 \n\n', 0)

check_output may also be suitable, a non-zero exit status will raise a CalledProcessError:

check_output 也可能适用,非零退出状态将引发 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

You also need to redirect stderr to store the error output:

您还需要重定向 stderr 以存储错误输出:

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()

Just pass your commands:

只需传递您的命令:

In [5]: get_out("adb","devices")
Out[5]: (0, 'List of devices attached \n\n')

In [6]: get_out("adb","devices","foo")
Out[6]: (1, 'Usage: adb devices [-l]\n')