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

2023-07-21Python开发问题
9

本文介绍了如何从 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 中的子进程获取返回码和输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10