如何在Python中从子进程获取返回代码和输出? [英] How to get both return code and output from subprocess in Python?

查看:417
本文介绍了如何在Python中从子进程获取返回代码和输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在为Android调试桥(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:\git\adb-lib\test>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和通讯将允许您获取输出和返回代码。

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

check_output也可能是sui表中,退出状态为非零将引发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 \n\n')

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

这篇关于如何在Python中从子进程获取返回代码和输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆