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

How to get both return code and output from subprocess in Python?(如何从 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 中的子进程获取返回码和输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)