Python如何通过subprocess调用adb命令详解
前言
本文主要给大家介绍了关于使用Python通过subprocess调用adb命令,subprocess包主要功能是执行外部命令(相对Python而言)。和shell类似。
换言之除了adb命令外,利用subprocess可以执行其他的命令,比如ls,cd等等。
subprocess可参考:https://docs.python.org/2/library/subprocess.html
在电脑上装好adb工具,配置好adb的环境变量,先确保shell中可以调用adb命令。
代码示例
Python2.7
类Adb,封装了一些adb的方法
importos
importsubprocess
classAdb(object):
"""Providessomeadbmethods"""
@staticmethod
defadb_devices():
"""
Doadbdevices
:returnThefirstconnecteddeviceID
"""
cmd="adbdevices"
c_line=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()[0]
ifc_line.find("Listofdevicesattached")<0:#adbisnotworking
returnNone
returnc_line.split("\t")[0].split("\r\n")[-1]#Thislinemayhavedifferentformat
@staticmethod
defpull_sd_dcim(device,target_dir='E:/files'):
"""PullDCIMfilesfromdevice"""
print"Pullingfiles"
des_path=os.path.join(target_dir,device)
ifnotos.path.exists(des_path):
os.makedirs(des_path)
printdes_path
cmd="adbpull/sdcard/DCIM/"+des_path
result=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()
printresult
print"Finish!"
returndes_path
@staticmethod
defsome_adb_cmd():
p=subprocess.Popen('adbshellcdsdcard&&ls&&cd../sys&&ls',
stdout=subprocess.PIPE,stderr=subprocess.PIPE)
return_code=p.poll()
whilereturn_codeisNone:
line=p.stdout.readline()
return_code=p.poll()
line=line.strip()
ifline:
printline
print"Done"
some_adb_cmd方法执行一连串的命令。各个命令之间用&&连接。
接着是一个死循环,将执行结果打印出来。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。