Search code examples
androidpythonstreambootloaderfastboot

Output from Python and Android Fastboot


I'm creating a python script to work with some fastboot commands, and I am trying to do

fastboot getvar product

In order to see what product I have selected. The problem is when I run this code:

p = subprocess.Popen(['fastboot', "getvar", "all"])
out, err = p.communicate()
print "We got: " + out

Out is empty. It works fine if i pass in devices instead of getvar all.

I think it has something to do with this stack overflow question but I'm having a hard time translating it to python:

fastboot getvar from batch file

How can I get the output from getvar back in a string, instead of just outputted to the terminal?

Edit:

I found a github account of someone who made a similiar function for adb, and modified it to achieve what I want:

def callFastboot(self, command):
    command_result = ''
    command_text = 'fastboot %s' % command
    results = os.popen(command_text, "r")
    while 1:
        line = results.readline()
        if not line: break
        command_result += line
    return command_result

out = test.callFastboot("getvar product 2>&1")
print "We got: " + out

The problem is that this uses the old os.popen method. So my new question is the same, but how do I do this with subprocess?


Solution

  • For fastboot getvar all you need to capture stderr instead of stdout:

    print subprocess.check_output(['fastboot', 'getvar', 'all'], stderr=subprocess.STDOUT)