2013-12-23 35 views
2

我尝试使用下面的代码获得亚行命令的输出亚行输出:获取使用Python

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但它没有一个子

+1

阅读[subprocess的文档](http://docs.python.org/2/library/subprocess.html#frequently-used-arguments)。将该命令作为列表传递。使用'check_output()'。 'os.system()'不可能让你输出,它只返回退出状态。 – jfs

回答

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) 
+0

如果'pname'可能包含一个空格,那么你可以使用'pipes.quote(pname)'来为shell转义它(假设'/ bin/sh'语法):''pm path {}'。 (pipes.quote(pname))'如果命令应该是一个字符串。否则,将命令作为列表传递:'args.extend(['shell'] + command)'。 – jfs

-1

你应该使用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()检查设备是否连接。希望能帮助你。