昨天搞了半天,终于把这两个环节打通了。后续可以进一步调用adb命令执行一些操作,细节说明已在代码中添加注释。
图1:程序调用“adb devices”后的运行情况
代码如下:
import subprocess import threading import platform def run_cmd(cmd): plat = platform.system() try: p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) #shell=True 保障多个参数支持 #return_code = p.poll() #获取cmd运行结束标志,如果未结束,则返回值为None。 while p.poll() is None: line = p.stdout.readline() #逐行读取结果,可以运行循环指令,如果是readlines,不会显示吧。 line = line.strip() #Python strip() 方法用于移除字符串头尾指定的字符(默认为空格)。 if line: if "Windows" in plat: print line.decode("gb2312") else: print line #print "[*] Done.\r\n" except: print "[*] Failed to execute command.\r\n" #确保误操作不导致程序崩溃 def cmd_loop(): print "[*] your command:" while True: cmd = raw_input(">>>") #threading.Thread(target=run_cmd,args=(cmd,)).start() run_cmd(cmd) #if "q" in raw_input(): #print "[*] exited by press q" #exit(0) cmd_loop()