How to get both return code and output from subprocess in Python? -
this question has answer here:
- subprocess.check_output return code 2 answers
while developing python wrapper library android debug bridge (adb), i'm using subprocess execute adb commands in shell. here simplified example:
import subprocess ... def exec_adb_command(adb_command): return = subprocess.call(adb_command)
if command executed propery exec_adb_command returns 0 ok.
but adb commands return not "0" or "1" generate output want catch also. adb devices example:
d:\git\adb-lib\test>adb devices list of devices attached 07eeb4bb device
i've tried subprocess.check_output() purpose, , return output not return code ("0" or "1").
ideally want tuple t[0] return code , t[1] actual output.
am missing in subprocess module allows such kind of results?
thanks!
popen , communicate allow output , 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 may suitable, non-zero exit status raise calledprocesserror:
from subprocess import check_output, calledprocesserror try: out = check_output(["adb", "devices"]) t = 0, out except calledprocesserror e: t = e.returncode, e.message
you need redirect stderr store error output:
from subprocess import check_output, calledprocesserror tempfile import temporaryfile def get_out(*args): temporaryfile() t: try: out = check_output(args, stderr=t) return 0, out except calledprocesserror e: t.seek(0) return e.returncode, t.read()
just pass commands:
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')
Comments
Post a Comment