检查环境变量
#判断是否设置环境变量ANDROID_ HOME if "ANDROID_ HОME" in os. environ: command = os. path. join( os.environ["ANDROID_HОME"], "platform-tools", "adb") else: raise EnvironmentError( "Adb not found in $ANDROID_ HOME path: %s." % os. environ ["ANDROID_ HOME"] )
命令执行
class Shell: def_ init_ (self): pass @staticmethod def invoke(cmd): output,errors=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stder-subprocess PIPF).communicate() o=output.decode("utf-8") return 0
ADB命令封装
class ADB(object): 参数:device_id def init(self,device id=""): if device id =="": self.device_id ="" else: self.device id="-ss"deviceid def adb(self,args): cmd="8S8S8S"%(commandselfdeviceid,str(arqs)) return Shell.invoke(cmd) def shell(self,args): cmd ="gs 8s shell &s"%(commandselfdevice id str(args),) return Shellinvoke(cmd) def get device state(self): 获取设备状态:offline|bootloaderdevice return self.adb("get-state).stdoutread().strip() def get_device_id(self): 获取设备id号,return serialNo return self.adb("get-serialno")stdoutread().strip() def get android version(self): 获取设备中的Android版本号,如4.2.2 return self.shell( "getprop ro.build.versionrelease")strip() def get_sdk version(self): 获取设备SDK版本号,如:24 return self.shell("getprop ro.buildversionsdk)strip()
设备信息获取
class DeviceInfo: def_init_(self,uid,os_type,os_version,sdk_version,brand,model,rom_version): self.uid=uid self.os_type=os_type self.os version=os version self.sdk_version=sdk version self.brand=brand self.model=model self.rom_version=rom version class Device: def _init_(self): pass @staticmethod def get android devices(): android devices list = [] android devices infos=[] for device in Shell.invoke(adb devices)splitlines(): if 'device' in device and 'devicesnot in device: device=devicesplit("\t)[0] android devices listappend(device) for device uid in android devices list: device info =DeviceInfo(device uid,"Android"ADB(device uid).get android version(), ADB(device uid).get sdk version(), ADB(device_uid).get_product brand(),ADB(device_uid).get_product model(), ADB(device uid).get product rom()) android devices infos.append(device info.dict) return android devices_infos
设备信息数据结构
"uid":"BY2WKN1519078327" "rom version":"Che2-UL00 V100R001CHNC00B287" "brand":"Honor", "os version": "4.4.2" "sdk version":"19" "os type": "Android" "model":"Che2-UL00"},{ "uid":"GWY0217414001213" "rom version":"MHA-AL00C00B213" "brand":"HUAWEI" "os_version": "7.0" "sdk version":"24" "os_type":"Android" "model":"MHA-ALO0"}