使用Python获取adb输出

时间:2013-12-23 23:36:41

标签: python subprocess adb

我正在尝试使用以下代码获取adb命令的输出:

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


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

知道为什么这个命令不起作用?

这是我看到的错误:

OSError: [Errno 2] No such file or directory

我可以将输出作为os.system获取但是它对子进程失败

3 个答案:

答案 0 :(得分:1)

import subprocess

ADB_PATH="adb"

def adbdevices(adbpath=ADB_PATH):
    return set([device.split('\t')[0] for device in subprocess.check_output([adbpath, 'devices']).splitlines() if device.endswith('\tdevice')])

def adbshell(command, serial=None, adbpath=ADB_PATH):
    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_PATH):
    return adbshell('pm path {}'.format(pname), serial=serial, adbpath=adbpath)

答案 1 :(得分:0)

您应该使用check_output,以下是我的代码,该代码可以成功运行。

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

致电isAdbConnected()以检查设备是否已连接。希望能帮到你。

答案 2 :(得分:0)

my_df <-
  structure(list(Date = structure(c(1505779200, 1505779500, 1505779800, 1505780100),
                                  class = c("POSIXct", "POSIXt"), tzone = "UTC"),
                 A = c(212.429693925327, 211.464088210329, 211.653306685973, 210.981936189015),
                 B = c(75.9448191760481, 76.2501222022257, 76.1316674891558, 76.8299563088116)),
            row.names = c(NA, 4L),
            class = "data.frame")