Python如何实现对adb命令封装

小编给大家分享一下Python如何实现对adb命令封装,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

adb命令

Python如何实现对adb命令封装

#!/usr/bin/evnpython
#-*-coding:utf-8-*-

#FileNameadbtools.py
#Author:HeyNiu
#CreatedTime:2016/9/19
"""
adb工具类
"""

importos
importplatform
importre
importtime
importutils.timetools


classAdbTools(object):

def__init__(self,device_id=''):
self.__system=platform.system()
self.__find=''
self.__command=''
self.__device_id=device_id
self.__get_find()
self.__check_adb()
self.__connection_devices()

def__get_find(self):
"""
判断系统类型,windows使用findstr,linux使用grep
:return:
"""
ifself.__systemis"Windows":
self.__find="findstr"
else:
self.__find="grep"

def__check_adb(self):
"""
检查adb
判断是否设置环境变量ANDROID_HOME
:return:
"""
if"ANDROID_HOME"inos.environ:
ifself.__system=="Windows":
path=os.path.join(os.environ["ANDROID_HOME"],"platform-tools","adb.exe")
ifos.path.exists(path):
self.__command=path
else:
raiseEnvironmentError(
"Adbnotfoundin$ANDROID_HOMEpath:%s."%os.environ["ANDROID_HOME"])
else:
path=os.path.join(os.environ["ANDROID_HOME"],"platform-tools","adb")
ifos.path.exists(path):
self.__command=path
else:
raiseEnvironmentError(
"Adbnotfoundin$ANDROID_HOMEpath:%s."%os.environ["ANDROID_HOME"])
else:
raiseEnvironmentError(
"Adbnotfoundin$ANDROID_HOMEpath:%s."%os.environ["ANDROID_HOME"])

def__connection_devices(self):
"""
连接指定设备,单个设备可不传device_id
:return:
"""
ifself.__device_id=="":
return
self.__device_id="-s%s"%self.__device_id

defadb(self,args):
"""
执行adb命令
:paramargs:参数
:return:
"""
cmd="%s%s%s"%(self.__command,self.__device_id,str(args))
#print(cmd)
returnos.popen(cmd)

defshell(self,args):
"""
执行adbshell命令
:paramargs:参数
:return:
"""
cmd="%s%sshell%s"%(self.__command,self.__device_id,str(args))
#print(cmd)
returnos.popen(cmd)

defmkdir(self,path):
"""
创建目录
:parampath:路径
:return:
"""
returnself.shell('mkdir%s'%path)

defget_devices(self):
"""
获取设备列表
:return:
"""
l=self.adb('devices').readlines()
return(i.split()[0]foriinlif'devices'notiniandlen(i)>5)

defget_current_application(self):
"""
获取当前运行的应用信息
:return:
"""
returnself.shell('dumpsyswindoww|%s\/|%sname='%(self.__find,self.__find)).read()

defget_current_package(self):
"""
获取当前运行app包名
:return:
"""
reg=re.compile(r'name=(.+?)/')
returnre.findall(reg,self.get_current_application())[0]

defget_current_activity(self):
"""
获取当前运行activity
:return:package/activity
"""
reg=re.compile(r'name=(.+?)\)')
returnre.findall(reg,self.get_current_application())[0]

def__get_process(self,package_name):
"""
获取进程信息
:parampackage_name:
:return:
"""
ifself.__systemis"Windows":
pid_command=self.shell("ps|%s%s$"%(self.__find,package_name)).read()
else:
pid_command=self.shell("ps|%s-w%s"%(self.__find,package_name)).read()
returnpid_command

defprocess_exists(self,package_name):
"""
返回进程是否存在
:parampackage_name:
:return:
"""
process=self.__get_process(package_name)
returnpackage_nameinprocess

defget_pid(self,package_name):
"""
获取pid
:return:
"""
pid_command=self.__get_process(package_name)
ifpid_command=='':
print("Theprocessdoesn'texist.")
returnpid_command

req=re.compile(r"\d+")
result=str(pid_command).split()
result.remove(result[0])
returnreq.findall("".join(result))[0]

defget_uid(self,pid):
"""
获取uid
:parampid:
:return:
"""
result=self.shell("cat/proc/%s/status"%pid).readlines()
foriinresult:
if'uid'ini.lower():
returni.split()[1]

defget_flow_data_tcp(self,uid):
"""
获取应用tcp流量
:return:(接收,发送)
"""
tcp_rcv=self.shell("catproc/uid_stat/%s/tcp_rcv"%uid).read().split()[0]
tcp_snd=self.shell("catproc/uid_stat/%s/tcp_snd"%uid).read().split()[0]
returntcp_rcv,tcp_snd

defget_flow_data_all(self,uid):
"""
获取应用流量全部数据
包含该应用多个进程的所有数据tcpudp等
(rx_bytes,tx_bytes)>>(接收,发送)
:paramuid:
:return:list(dict)
"""
all_data=[]
d={}
data=self.shell("cat/proc/net/xt_qtaguid/stats|%s%s"%(self.__find,uid)).readlines()
foriindata:
ifnoti.startswith('\n'):
item=i.strip().split()
d['idx']=item[0]
d['iface']=item[1]
d['acct_tag_hex']=item[2]
d['uid_tag_int']=item[3]
d['cnt_set']=item[4]
d['rx_bytes']=item[5]
d['rx_packets']=item[6]
d['tx_bytes']=item[7]
d['tx_packets']=item[8]
d['rx_tcp_bytes']=item[9]
d['rx_tcp_packets']=item[10]
d['rx_udp_bytes']=item[11]
d['rx_udp_packets']=item[12]
d['rx_other_bytes']=item[13]
d['rx_other_packets']=item[14]
d['tx_tcp_bytes']=item[15]
d['tx_tcp_packets']=item[16]
d['tx_udp_bytes']=item[17]
d['tx_udp_packets']=item[18]
d['tx_other_bytes']=item[19]
d['tx_other_packets']=item[20]

all_data.append(d)
d={}
returnall_data

@staticmethod
defdump_apk(path):
"""
dumpapk文件
:parampath:apk路径
:return:
"""
#检查build-tools是否添加到环境变量中
#需要用到里面的aapt命令
l=os.environ['PATH'].split(';')
build_tools=False
foriinl:
if'build-tools'ini:
build_tools=True
ifnotbuild_tools:
raiseEnvironmentError("ANDROID_HOMEBUILD-TOOLSCOMMANDNOTFOUND.\nPleasesettheenvironmentvariable.")
returnos.popen('aaptdumpbadging%s'%(path,))

@staticmethod
defdump_xml(path,filename):
"""
dumpapkxml文件
:return:
"""
returnos.popen('aaptdumpxmlstrings%s%s'%(path,filename))

defuiautomator_dump(self):
"""
获取屏幕uiautomatorxml文件
:return:
"""
returnself.shell('uiautomatordump').read().split()[-1]

defpull(self,source,target):
"""
从手机端拉取文件到电脑端
:return:
"""
self.adb('pull%s%s'%(source,target))

defpush(self,source,target):
"""
从电脑端推送文件到手机端
:paramsource:
:paramtarget:
:return:
"""
self.adb('push%s%s'%(source,target))

defremove(self,path):
"""
从手机端删除文件
:return:
"""
self.shell('rm%s'%(path,))

defclear_app_data(self,package):
"""
清理应用数据
:return:
"""
self.shell('pmclear%s'%(package,))

definstall(self,path):
"""
安装apk文件
:return:
"""
#adbinstall安装错误常见列表
errors={'INSTALL_FAILED_ALREADY_EXISTS':'程序已经存在',
'INSTALL_DEVICES_NOT_FOUND':'找不到设备',
'INSTALL_FAILED_DEVICE_OFFLINE':'设备离线',
'INSTALL_FAILED_INVALID_APK':'无效的APK',
'INSTALL_FAILED_INVALID_URI':'无效的链接',
'INSTALL_FAILED_INSUFFICIENT_STORAGE':'没有足够的存储空间',
'INSTALL_FAILED_DUPLICATE_PACKAGE':'已存在同名程序',
'INSTALL_FAILED_NO_SHARED_USER':'要求的共享用户不存在',
'INSTALL_FAILED_UPDATE_INCOMPATIBLE':'版本不能共存',
'INSTALL_FAILED_SHARED_USER_INCOMPATIBLE':'需求的共享用户签名错误',
'INSTALL_FAILED_MISSING_SHARED_LIBRARY':'需求的共享库已丢失',
'INSTALL_FAILED_REPLACE_COULDNT_DELETE':'需求的共享库无效',
'INSTALL_FAILED_DEXOPT':'dex优化验证失败',
'INSTALL_FAILED_DEVICE_NOSPACE':'手机存储空间不足导致apk拷贝失败',
'INSTALL_FAILED_DEVICE_COPY_FAILED':'文件拷贝失败',
'INSTALL_FAILED_OLDER_SDK':'系统版本过旧',
'INSTALL_FAILED_CONFLICTING_PROVIDER':'存在同名的内容提供者',
'INSTALL_FAILED_NEWER_SDK':'系统版本过新',
'INSTALL_FAILED_TEST_ONLY':'调用者不被允许测试的测试程序',
'INSTALL_FAILED_CPU_ABI_INCOMPATIBLE':'包含的本机代码不兼容',
'CPU_ABIINSTALL_FAILED_MISSING_FEATURE':'使用了一个无效的特性',
'INSTALL_FAILED_CONTAINER_ERROR':'SD卡访问失败',
'INSTALL_FAILED_INVALID_INSTALL_LOCATION':'无效的安装路径',
'INSTALL_FAILED_MEDIA_UNAVAILABLE':'SD卡不存在',
'INSTALL_FAILED_INTERNAL_ERROR':'系统问题导致安装失败',
'INSTALL_PARSE_FAILED_NO_CERTIFICATES':'文件未通过认证>>设置开启未知来源',
'INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES':'文件认证不一致>>先卸载原来的再安装',
'INSTALL_FAILED_INVALID_ZIP_FILE':'非法的zip文件>>先卸载原来的再安装',
'INSTALL_CANCELED_BY_USER':'需要用户确认才可进行安装',
'INSTALL_FAILED_VERIFICATION_FAILURE':'验证失败>>尝试重启手机',
'DEFAULT':'未知错误'
}
print('Installing...')
l=self.adb('install-r%s'%(path,)).read()
if'Success'inl:
print('InstallSuccess')
if'Failure'inl:
reg=re.compile('\\[(.+?)\\]')
key=re.findall(reg,l)[0]
try:
print('InstallFailure>>%s'%errors[key])
exceptKeyError:
print('InstallFailure>>%s'%key)
returnl

defuninstall(self,package):
"""
卸载apk
:parampackage:包名
:return:
"""
print('Uninstalling...')
l=self.adb('uninstall%s'%(package,)).read()
print(l)

defscreenshot(self,target_path=''):
"""
手机截图
:paramtarget_path:目标路径
:return:
"""
format_time=utils.timetools.timestamp('%Y%m%d%H%M%S')
self.shell('screencap-p/sdcard/%s.png'%(format_time,))
time.sleep(1)
iftarget_path=='':
self.pull('/sdcard/%s.png'%(format_time,),os.path.expanduser('~'))
else:
self.pull('/sdcard/%s.png'%(format_time,),target_path)
self.remove('/sdcard/%s.png'%(format_time,))

defget_cache_logcat(self):
"""
导出缓存日志
:return:
"""
returnself.adb('logcat-vtime-d')

defget_crash_logcat(self):
"""
导出崩溃日志
:return:
"""
returnself.adb('logcat-vtime-d|%sAndroidRuntime'%(self.__find,))

defclear_cache_logcat(self):
"""
清理缓存区日志
:return:
"""
self.adb('logcat-c')

defget_device_time(self):
"""
获取设备时间
:return:
"""
returnself.shell('date').read().strip()

defls(self,command):
"""
shellls命令
:return:
"""
returnself.shell('ls%s'%(command,)).readlines()

deffile_exists(self,target):
"""
判断文件在目标路径是否存在
:return:
"""
l=self.ls(target)
foriinl:
ifi.strip()==target:
returnTrue
returnFalse

defis_install(self,target_app):
"""
判断目标app在设备上是否已安装
:paramtarget_app:目标app包名
:return:bool
"""
returntarget_appinself.shell('pmlistpackages%s'%(target_app,)).read()

defget_device_model(self):
"""
获取设备型号
:return:
"""
returnself.shell('getpropro.product.model').read().strip()

defget_device_id(self):
"""
获取设备id
:return:
"""
returnself.adb('get-serialno').read().strip()

defget_device_android_version(self):
"""
获取设备Android版本
:return:
"""
returnself.shell('getpropro.build.version.release').read().strip()

defget_device_sdk_version(self):
"""
获取设备SDK版本
:return:
"""
returnself.shell('getpropro.build.version.sdk').read().strip()

defget_device_mac_address(self):
"""
获取设备MAC地址
:return:
"""
returnself.shell('cat/sys/class/net/wlan0/address').read().strip()

defget_device_ip_address(self):
"""
获取设备IP地址
pass:适用WIFI蜂窝数据
:return:
"""
ifnotself.get_wifi_state()andnotself.get_data_state():
return
l=self.shell('ipaddr|%sglobal'%self.__find).read()
reg=re.compile('\d+\.\d+\.\d+\.\d+')
returnre.findall(reg,l)[0]

defget_device_imei(self):
"""
获取设备IMEI
:return:
"""
sdk=self.get_device_sdk_version()
#Android5.0以下方法
ifint(sdk)<21:
l=self.shell('dumpsysiphonesubinfo').read()
reg=re.compile('[0-9]{15}')
returnre.findall(reg,l)[0]
elifself.root():
l=self.shell('servicecalliphonesubinfo1').read()
print(l)
print(re.findall(re.compile("'.+?'"),l))
imei=''
foriinre.findall(re.compile("'.+?'"),l):
imei+=i.replace('.','').replace("'",'').replace('','')
returnimei
else:
print('Thedevicenotroot.')
return''

defcheck_sim_card(self):
"""
检查设备SIM卡
:return:
"""
returnlen(self.shell('getprop|%sgsm.operator.alpha]'%self.__find).read().strip().split()[-1])>2

defget_device_operators(self):
"""
获取运营商
:return:
"""
returnself.shell('getprop|%sgsm.operator.alpha]'%self.__find).read().strip().split()[-1]

defget_device_state(self):
"""
获取设备状态
:return:
"""
returnself.adb('get-state').read().strip()

defget_display_state(self):
"""
获取屏幕状态
:return:亮屏/灭屏
"""
l=self.shell('dumpsyspower').readlines()
foriinl:
if'mScreenOn='ini:
returni.split()[-1]=='mScreenOn=true'
if'DisplayPower'ini:
return'ON'ini.split('=')[-1].upper()

defget_screen_normal_size(self):
"""
获取设备屏幕分辨率>>标配
:return:
"""
returnself.shell('wmsize').read().strip().split()[-1].split('x')

defget_screen_reality_size(self):
"""
获取设备屏幕分辨率>>实际分辨率
:return:
"""
x=0
y=0
l=self.shell(r'getevent-p|%s-e"0"'%self.__find).readlines()
forninl:
iflen(n.split())>0:
ifn.split()[0]=='0035':
x=int(n.split()[7].split(',')[0])
elifn.split()[0]=='0036':
y=int(n.split()[7].split(',')[0])
returnx,y

defget_device_interior_sdcard(self):
"""
获取内部SD卡空间
:return:(path,total,used,free,block)
"""
returnself.shell('df|%s\/mnt\/shell\/emulated'%self.__find).read().strip().split()

defget_device_external_sdcard(self):
"""
获取外部SD卡空间
:return:(path,total,used,free,block)
"""
returnself.shell('df|%s\/storage'%self.__find).read().strip().split()

def__fill_rom(self,path,stream,count):
"""
填充数据
:parampath:填充地址
:paramstream:填充流大小
:paramcount:填充次数
:return:
"""
self.shell('ddif=/dev/zeroof=%sbs=%scount=%s'%(path,stream,count)).read().strip()

deffill_interior_sdcard(self,filename,size):
"""
填充内置SD卡
:paramfilename:文件名
:paramsize:填充大小,单位byte
:return:
"""
ifsize>10485760:#10m
self.__fill_rom('sdcard/%s'%filename,10485760,size/10485760)
else:
self.__fill_rom('sdcard/%s'%filename,size,1)

deffill_external_sdcard(self,filename,size):
"""
填充外置SD卡
:paramfilename:文件名
:paramsize:填充大小,单位byte
:return:
"""
path=self.get_device_external_sdcard()[0]
ifsize>10485760:#10m
self.__fill_rom('%s/%s'%(path,filename),10485760,size/10485760)
else:
self.__fill_rom('%s/%s'%(path,filename),size,1)

defkill_process(self,pid):
"""
杀死进程
pass:一般需要权限不推荐使用
:return:
"""
returnself.shell('kill%s'%pid).read().strip()

defquit_app(self,package):
"""
退出应用
:return:
"""
returnself.shell('amforce-stop%s'%package).read().strip()

defreboot(self):
"""
重启设备
:return:
"""
self.adb('reboot')

defrecovery(self):
"""
重启设备并进入recovery模式
:return:
"""
self.adb('rebootrecovery')

deffastboot(self):
"""
重启设备并进入fastboot模式
:return:
"""
self.adb('rebootbootloader')

defroot(self):
"""
获取root状态
:return:
"""
return'notfound'notinself.shell('su-cls-l/data/').read().strip()

defwifi(self,power):
"""
开启/关闭wifi
pass:需要root权限
:return:
"""
ifnotself.root():
print('Thedevicenotroot.')
return
ifpower:
self.shell('su-csvcwifienable').read().strip()
else:
self.shell('su-csvcwifidisable').read().strip()

defdata(self,power):
"""
开启/关闭蜂窝数据
pass:需要root权限
:return:
"""
ifnotself.root():
print('Thedevicenotroot.')
return
ifpower:
self.shell('su-csvcdataenable').read().strip()
else:
self.shell('su-csvcdatadisable').read().strip()

defget_wifi_state(self):
"""
获取WiFi连接状态
:return:
"""
return'enabled'inself.shell('dumpsyswifi|%s^Wi-Fi'%self.__find).read().strip()

defget_data_state(self):
"""
获取移动网络连接状态
:return:
"""
return'2'inself.shell('dumpsystelephony.registry|%smDataConnectionState'%self.__find).read().strip()

defget_network_state(self):
"""
设备是否连上互联网
:return:
"""
return'unknownhost'notinself.shell('ping-w1www.baidu.com').read().strip()

defget_wifi_password_list(self):
"""
获取WIFI密码列表
:return:
"""
ifnotself.root():
print('Thedevicenotroot.')
return[]
l=re.findall(re.compile('ssid=".+?"\s{3}psk=".+?"'),self.shell('su-ccat/data/misc/wifi/*.conf').read())
return[re.findall(re.compile('".+?"'),i)foriinl]

defcall(self,number):
"""
拨打电话
:paramnumber:
:return:
"""
self.shell('amstart-aandroid.intent.action.CALL-dtel:%s'%number)

defopen_url(self,url):
"""
打开网页
:return:
"""
self.shell('amstart-aandroid.intent.action.VIEW-d%s'%url)

defstart_application(self,component):
"""
启动一个应用
e.g:com.android.settings/com.android.settings.Settings
"""
self.shell("amstart-n%s"%component)

defsend_keyevent(self,keycode):
"""
发送一个按键事件
https://developer.android.com/reference/android/view/KeyEvent.html
:return:
"""
self.shell('inputkeyevent%s'%keycode)

defrotation_screen(self,param):
"""
旋转屏幕
:paramparam:0>>纵向,禁止自动旋转;1>>自动旋转
:return:
"""
self.shell('/system/bin/contentinsert--uricontent://settings/system--bind'
'name:s:accelerometer_rotation--bindvalue:i:%s'%param)

definstrument(self,command):
"""
启动instrumentapp
:paramcommand:命令
:return:
"""
returnself.shell('aminstrument%s'%command).read()

defexport_apk(self,package,target_path='',timeout=5000):
"""
从设备导出应用
:paramtimeout:超时时间
:paramtarget_path:导出后apk存储路径
:parampackage:包名
:return:
"""
num=0
iftarget_path=='':
self.adb('pull/data/app/%s-1/base.apk%s'%(package,os.path.expanduser('~')))
while1:
num+=1
ifnum<=timeout:
ifos.path.exists(os.path.join(os.path.expanduser('~'),'base.apk')):
os.rename(os.path.join(os.path.expanduser('~'),'base.apk'),
os.path.join(os.path.expanduser('~'),'%s.apk'%package))

else:
self.adb('pull/data/app/%s-1/base.apk%s'%(package,target_path))
while1:
num+=1
ifnum<=timeout:
ifos.path.exists(os.path.join(os.path.expanduser('~'),'base.apk')):
os.rename(os.path.join(os.path.expanduser('~'),'base.apk'),
os.path.join(os.path.expanduser('~'),'%s.apk'%package))


classKeyCode:
KEYCODE_CALL=5#拨号键
KEYCODE_ENDCALL=6#挂机键
KEYCODE_HOME=3#Home键
KEYCODE_MENU=82#菜单键
KEYCODE_BACK=4#返回键
KEYCODE_SEARCH=84#搜索键
KEYCODE_CAMERA=27#拍照键
KEYCODE_FOCUS=80#对焦键
KEYCODE_POWER=26#电源键
KEYCODE_NOTIFICATION=83#通知键
KEYCODE_MUTE=91#话筒静音键
KEYCODE_VOLUME_MUTE=164#扬声器静音键
KEYCODE_VOLUME_UP=24#音量+键
KEYCODE_VOLUME_DOWN=25#音量-键
KEYCODE_ENTER=66#回车键
KEYCODE_ESCAPE=111#ESC键
KEYCODE_DPAD_CENTER=23#导航键>>确定键
KEYCODE_DPAD_UP=19#导航键>>向上
KEYCODE_DPAD_DOWN=20#导航键>>向下
KEYCODE_DPAD_LEFT=21#导航键>>向左
KEYCODE_DPAD_RIGHT=22#导航键>>向右
KEYCODE_MOVE_HOME=122#光标移动到开始键
KEYCODE_MOVE_END=123#光标移动到末尾键
KEYCODE_PAGE_UP=92#向上翻页键
KEYCODE_PAGE_DOWN=93#向下翻页键
KEYCODE_DEL=67#退格键
KEYCODE_FORWARD_DEL=112#删除键
KEYCODE_INSERT=124#插入键
KEYCODE_TAB=61#Tab键
KEYCODE_NUM_LOCK=143#小键盘锁
KEYCODE_CAPS_LOCK=115#大写锁定键
KEYCODE_BREAK=121#Break/Pause键
KEYCODE_SCROLL_LOCK=116#滚动锁定键
KEYCODE_ZOOM_IN=168#放大键
KEYCODE_ZOOM_OUT=169#缩小键
KEYCODE_0=7
KEYCODE_1=8
KEYCODE_2=9
KEYCODE_3=10
KEYCODE_4=11
KEYCODE_5=12
KEYCODE_6=13
KEYCODE_7=14
KEYCODE_8=15
KEYCODE_9=16
KEYCODE_A=29
KEYCODE_B=30
KEYCODE_C=31
KEYCODE_D=32
KEYCODE_E=33
KEYCODE_F=34
KEYCODE_G=35
KEYCODE_H=36
KEYCODE_I=37
KEYCODE_J=38
KEYCODE_K=39
KEYCODE_L=40
KEYCODE_M=41
KEYCODE_N=42
KEYCODE_O=43
KEYCODE_P=44
KEYCODE_Q=45
KEYCODE_R=46
KEYCODE_S=47
KEYCODE_T=48
KEYCODE_U=49
KEYCODE_V=50
KEYCODE_W=51
KEYCODE_X=52
KEYCODE_Y=53
KEYCODE_Z=54
KEYCODE_PLUS=81#+
KEYCODE_MINUS=69#-
KEYCODE_STAR=17#*
KEYCODE_SLASH=76#/
KEYCODE_EQUALS=70#=
KEYCODE_AT=77#@
KEYCODE_POUND=18##
KEYCODE_APOSTROPHE=75#'
KEYCODE_BACKSLASH=73#\
KEYCODE_COMMA=55#,
KEYCODE_PERIOD=56#.
KEYCODE_LEFT_BRACKET=71#[
KEYCODE_RIGHT_BRACKET=72#]
KEYCODE_SEMICOLON=74#;
KEYCODE_GRAVE=68#`
KEYCODE_SPACE=62#空格键
KEYCODE_MEDIA_PLAY=126#多媒体键>>播放
KEYCODE_MEDIA_STOP=86#多媒体键>>停止
KEYCODE_MEDIA_PAUSE=127#多媒体键>>暂停
KEYCODE_MEDIA_PLAY_PAUSE=85#多媒体键>>播放/暂停
KEYCODE_MEDIA_FAST_FORWARD=90#多媒体键>>快进
KEYCODE_MEDIA_REWIND=89#多媒体键>>快退
KEYCODE_MEDIA_NEXT=87#多媒体键>>下一首
KEYCODE_MEDIA_PREVIOUS=88#多媒体键>>上一首
KEYCODE_MEDIA_CLOSE=128#多媒体键>>关闭
KEYCODE_MEDIA_EJECT=129#多媒体键>>弹出
KEYCODE_MEDIA_RECORD=130#多媒体键>>录音


if__name__=='__main__':
a=AdbTools()
pass

补充知识:Python调用adb命令实现对多台设备同时进行reboot

首先,adb实现对设备的reboot命令是:adb reboot . 但是如果是两台/多台设备的时候,需要声明serial number: adb -s serial_no reboot.

那么,如何用python实现对多台设备进行adb操作呢(reboot)?

这里涉及到 python 下 subprocess model的使用:

import subprocess

adb device 获取所有设备的 serial number:

devices=subprocess.Popen(
'adbdevices'.split(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
).communicate()[0]

这样adb device命令的返回信息都在devices下,但是我们只需要 serial number的:

serial_nos=[]
foritemindevices.split():
filters=['list','of','device','devices','attached']
ifitem.lower()notinfilters:
serial_nos.append(item)

这样serial_nos 下保存的就是所有设备的 serial number 了,下面我们只需要依次对其进行adb -s [serial_number] reboot即可:

forserial_noinserial_nos:
reboot_cmds.append('adb-s%sreboot'%serial_no)
forreboot_cmdinreboot_cmds:
subprocess.Popen(
reboot_cmd.split(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
).communicate()[0]

这样,每个设备都进行了reboot的操作了……

以上是“Python如何实现对adb命令封装”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注恰卡编程网行业资讯频道!

发布于 2021-03-24 01:19:51
收藏
分享
海报
0 条评论
158
上一篇:python实现超级马里奥的案例 下一篇:python怎么实现用户名密码校验
目录

    推荐阅读

    0 条评论

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码