昨天搞了半天遵岩,終于把這兩個環(huán)節(jié)打通了。后續(xù)可以進(jìn)一步調(diào)用adb命令執(zhí)行一些操作,細(xì)節(jié)說明已在代碼中添加注釋尘执。
create:2018-05-16 09:16
圖1:程序調(diào)用“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 保障多個參數(shù)支持
#return_code = p.poll() #獲取cmd運行結(jié)束標(biāo)志舍哄,如果未結(jié)束,則返回值為None誊锭。
while p.poll() is None:
line = p.stdout.readline() #逐行讀取結(jié)果,可以運行循環(huán)指令表悬,如果是readlines,不會顯示吧。
line = line.strip() #Python strip() 方法用于移除字符串頭尾指定的字符(默認(rèn)為空格)丧靡。
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" #確保誤操作不導(dǎo)致程序崩潰
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()