Getting the adb output using Python

2019-02-28 04:26发布

问题:

I'm trying to get the output of a adb command using the following code:

pathCmd = './adb shell pm path ' + packageName


pathData = subprocess.Popen(pathCmd,stdout = subprocess.PIPE)
result = pathData.stdout.read()
print result

Any idea why doesn't this command work?

This is the error I see:

OSError: [Errno 2] No such file or directory

I can get the output as os.system but it fails for a subprocess

回答1:

import subprocess

def adbshell(command, serial=None, adbpath='adb'):
    args = [adbpath]
    if serial is not None:
        args.extend(['-s', serial])
    args.extend(['shell', command])
    return subprocess.check_output(args)

def pmpath(pname, serial=None, adbpath='adb'):
    return adbshell('pm path {}'.format(pname), serial=serial, adbpath=adbpath)


回答2:

You should use check_output, below is my code which works successfully.

from subprocess import check_output, CalledProcessError

from tempfile import TemporaryFile

def __getout(*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()

# cmd is string, split with blank
def getout(cmd):
    cmd = str(cmd)
    args = cmd.split(' ')
    return __getout(*args)

def bytes2str(bytes):
    return str(bytes, encoding='utf-8')

def isAdbConnected():
    cmd = 'adb devices'
    (code, out) = getout(cmd)
    if code != 0:
        print('something is error')
        return False
    outstr = bytes2str(out)
    if outstr == 'List of devices attached\n\n':
        print('no devices')
        return False
    else:
        print('have devices')
        return True

Call isAdbConnected() to check whether device is connected. Hope to help you.