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')
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)