Android 調(diào)試橋(adb)是多種用途的工具,該工具可以幫助你管理設(shè)備或模擬器?的狀態(tài)。實(shí)際運(yùn)用中我們可以通過(guò)adb進(jìn)行shell命令的相關(guān)操作,但是大部分這需要在CMD命令窗口一次又一次的重復(fù)輸入,為了提高日常工作效率,今天給大家普及一下如何通過(guò)腳本的形式一次編輯,多次維護(hù)來(lái)解決日常adb命令重復(fù)輸入的尷尬境遇。
首先,我們需要在電腦上裝好adb工具,配置好adb的環(huán)境變量,先確保shell中可以調(diào)用adb命令。其次,編輯腳本我采用Python這門(mén)膠水語(yǔ)言,為什么用Python呢?因?yàn)樯鲜秩菀?,好用啊?/p>
1、Python編輯腳本要想調(diào)用windows系統(tǒng)中的CMD窗口,可以有兩種方法:
????a、import os
????b、import subprocess
os和subprocess模塊二選一即可,有些人可能問(wèn)為什么都可以實(shí)現(xiàn)對(duì)CMD命令窗口的調(diào)用還有2種模塊支持。主要是因?yàn)閛s是Python2.4之前的產(chǎn)物且其特征是“阻塞式”,subprocess是從Python2.4之后才加入的模塊其特征“非阻塞式”。
2、Python如何通過(guò)subprocess調(diào)用adb命令詳解,附:subprocess官方文檔。
1)概述
? subprocess模塊是在2.4版本中新增的,官方文檔中描述為可以用來(lái)替換以下函數(shù):
? ? os.system、os.spawn、os.popen、popen2
2)參數(shù)
官方對(duì)于subprocess模塊的參數(shù)解釋如下:
args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.
參數(shù)既可以是string,也可以是list。?
subprocess.Popen([“cat”,”test.txt”])?
subprocess.Popen(“cat test.txt”, shell=True)?
對(duì)于參數(shù)是字符串,需要指定shell=True
3)使用示例
其中subprocess.call()用于代替os.system(),但是這2個(gè)函數(shù)無(wú)法返回命令的輸出。只會(huì)返回函數(shù)運(yùn)行成功與否的0或其他值。示例:
import subprocess
returnCode = subprocess.call('adb devices')
print returnCode
subprocess.check_output
import subprocess
# returns output as byte stringreturned_output = subprocess.check_output(cmd)# using decode() function to convert byte string to string
cmd = "date"
print('Current date is:', returned_output.decode("utf-8"))
subprocess.Popen的使用
1.執(zhí)行結(jié)果保存在文件
cmd ="adb shell ls /sdcard/ | findstr aa.png"
fhandle = open(r"e:\aa.txt","w")?
?pipe = subprocess.Popen(cmd, shell=True, stdout=fhandle).stdout??
fhandle.close()
?2.執(zhí)行結(jié)果使用管道輸出
import subprocess
cmd = 'adb help'
pi= subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE)
print pi.stdout.read()
注:stdin, stdout, stderr 分別表示程序的標(biāo)準(zhǔn)輸入、輸出、錯(cuò)誤句柄