python批量安装apk
目的:节省apk安装花费时间
#! Python3 # -- coding: utf-8 -- import datetime import os import re import subprocess from concurrent.futures import ThreadPoolExecutor, as_completed seq = '-' * 30 def get_devices_list(): """获取设备列表""" cmd = ['exit'] try: obj = subprocess.Popen('adb devices', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) tup = obj.communicate((''.join(cmd) + "\n").encode('utf-8')) lists_info = ''.encode('utf-8').join(tup).decode('utf-8').rstrip().splitlines() lists_info.pop(0) for i in lists_info: if 'offline' in i: lists_info.remove(i) lists = [x.split('\t')[0] for x in lists_info] if not lists: return '未连接设备' else: return lists except Exception as e: return e def device_install_app(device, app_path): """安装单个apk""" try: install_cmd = f'adb -s {device} install -r -t {app_path}' result = subprocess.Popen(install_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) global status status = False for i in result.stdout.readlines(): if 'Success' in i.decode('utf-8').strip(): status = True return status, device, app_path except Exception as err: return err def device_install_apps(device, filenames): """批量安装apk""" try: start = datetime.datetime.now() out_result = {} success = [] error = [] log = [] t_exec = ThreadPoolExecutor(max_workers=4) tasks = [t_exec.submit(device_install_app, device, app_path) for app_path in filenames] for feature in as_completed(tasks): global status status, device, app_path = feature.result() app_path_list = re.findall('(.*?).apk', os.path.basename(app_path)) if status: success.append(app_path_list) elif not status: error.append(app_path_list) log.append(success) log.append(error) out_result.update({device: log}) t_exec.shutdown() result = '' for k, v in out_result.items(): st, er = v s = '无' if not st else '\n'.join(x[0] for x in st) e = '无' if not er else '\n'.join(y[0] for y in er) result += f'{k}\n成功:\n{s}\n失败:\n{e}\n' end = datetime.datetime.now() return f'{result}耗时:{(end - start).seconds} 秒\n' except Exception as err: return err def devices_install_apps(filenames): """多设备批量安装apk""" try: if not filenames: return '待安装apk为空' devices_result = '' devices_list = get_devices_list() t_exec = ThreadPoolExecutor(max_workers=50) tasks = [t_exec.submit(device_install_apps, device, filenames) for device in devices_list] for future in as_completed(tasks): fu_result = future.result() devices_result += f'{fu_result}{seq}\n' t_exec.shutdown() return devices_result except Exception as e: return e path = [r"C:\Users\..\student_ui-debug.apk"] print(devices_install_apps(path))
执行效果:
S161001002c 成功: student_ui-debug 失败: 无 耗时:11 秒 ------------------------------ SX12456893n 成功: student_ui-debug 失败: 无 耗时:11 秒 ------------------------------
每次安装改apk地址,若觉得麻烦,可起一个gui界面,如:
path = (title='安装APP', filetypes=[('apk文件', '*.apk')], initialdir=os.getcwd())