1

I don't have a lot of familiarity with Python but I do with Ruby. So I will provide analogues for what I want to achieve

In Ruby I would

val = `adb devices`

to get the "raw output" of adb devices stored in val, and

val=system("adb devices")

to get the status code

I want to perform the same tasks in Python. I looked at

from subprocess import call
call(["adb devices"])

but that failed, I don't want to use os.system cause I want to get some proper error handling. how do i make call work and how do i obtain raw output from backticks in Python

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
Srini
  • 1,619
  • 1
  • 19
  • 34
  • Never mind. I just did `call(["adb", "devices"])` and it worked. However, I stil want to know how to get backticks output – Srini Dec 22 '14 at 13:30
  • 1
    Ruby note: If you use the backtick syntax (`\`adb devices\``), you can use `$?.exitstatus` to get the status code; no need for `system()`. – Martin Tournoij Dec 22 '14 at 14:05
  • Thanks, I never knew that :) – Srini Dec 22 '14 at 14:09
  • it is `subprocess.check_output(['adb', 'devices'])` in Python (note: this command doesn't run the shell). – jfs Dec 23 '14 at 22:27

1 Answers1

5

Pass the command and arguments as separate elements of a list:

from subprocess import call
return_code = call(["adb", "devices"])

However, this sends the output to stdout and you can't capture it. Instead you can use subprocess.check_ouput():

from subprocess import check_output

adb_ouput = check_output(["adb", "devices"])
# stdout of adb in adb_output.

If the return code is non-zero an exception is raised. You should catch it to see what the return code is. No exception is raised for return code 0:

from subprocess import check_output, CalledProcessError

try:
    adb_ouput = check_output(["adb", "devices"])
except CalledProcessError as e:
    print e.returncode
mhawke
  • 84,695
  • 9
  • 117
  • 138