如何从Python的子过程中获取返回代码和输出?[重复]

如何从Python的子过程中获取返回代码和输出?[重复],第1张

如何从Python的子过程中获取返回代码和输出?[重复]

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

from subprocess import Popen,PIPE,STDOUTout = Popen(["adb", "devices"],stderr=STDOUT,stdout=PIPE)t = out.communicate()[0],out.returnpreprint(t)('List of devices attached nn', 0)

check_output也可能是合适的,非零退出状态将引发CalledProcessError:

from subprocess import check_output, CalledProcessErrortry:    out = check_output(["adb", "devices"])    t = 0, outexcept CalledProcessError as e:    t = e.returnpre, e.message

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

from subprocess import check_output, CalledProcessErrorfrom tempfile import TemporaryFiledef 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.returnpre, t.read()

只需传递您的命令:

In [5]: get_out("adb","devices")Out[5]: (0, 'List of devices attached nn')In [6]: get_out("adb","devices","foo")Out[6]: (1, 'Usage: adb devices [-l]n')


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5632163.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存