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 \n\n', 0)
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
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()
Just pass your 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')