相关学习推荐:python教程
本文主要介绍使用Python调用ADB命令实现实时监控logcat关键字的功能
采用多进程,可同时监控多个设备,监控多个关键字。
需要配置ADB环境,具体配置就不多介绍,随便搜一下一大把,直接上代码
通过一个全局变量控制开启和关闭监控功能, INSTRUCTION 用于根据指令获取对应的方法名
import os, threading, datetime # 获取当前文件所在目录,拼接出LOG路径 LOG_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "log") # 配置需要监控的关键字 KEYWORDS = ["ANR ", "NullPointerException", "CRASH", "Force Closed"] # 控制开启和关闭 STOP_LOGCAT = True # 指令对应具体操作 INSTRUCTION = { "1": "filter_keywords", "2": "stop_filter_keywords", "3": "exit" } def filter_keywords(): global STOP_LOGCAT STOP_LOGCAT = False devices = get_devices() # 先获取所有连接的设备 print("开始监控关键字") for device in devices: t = threading.Thread(target=filter_keyword, args=(device,)) t.start() def stop_filter_keywords(): global STOP_LOGCAT if STOP_LOGCAT: print("没有正在执行的任务\n") else: STOP_LOGCAT = True print("正在停止关键字监控\n")
监控关键字主函数,
def filter_keyword(device): print("设备%s关键字监控已开启" % str(device)) sub = logcat(device) with sub: for line in sub.stdout: # 子进程会持续输出日志,对子进程对象.stdout进行循环读取 for key in KEYWORDS: if line.decode("utf-8").find(key) != -1: # stdout输出为字节类型,需要转码 message = "设备:%s 检测到:%s\n" % (device, key)# 设备:192.168.56.104:5555 检测到:ANR path = get_log_path("bugreport") # 根据时间创建文件夹 bugreport(device, path)# 拉取完整日志压缩包到创建的文件夹内 send_message(message) # 这里可以换成自己要做的事情,比如发送邮件或钉钉通知 if STOP_LOGCAT: break print("设备%s关键字监控已停止" % str(device)) sub.kill()
通过 subprocess.Popen 创建进程执行命令,持续输出日志到 stdout
# logcat持续输出日志 def logcat(device): command = "adb -s " + str(device) + " logcat -v time" sub = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return sub
获取所有已连接设备的方法,执行"adb devices"后输出如下,通过对命令执行拿到的字符串切割获取所有设备号以列表方式存储
# 获取所有device def get_devices(): command = "adb devices" res = os.popen(command).read() devices = [] res = res.split("\n") for i in res: if i.endswith("device"): de<i>本文来源gaodai$ma#com搞$代*码网2</i>vices.append(i.split('\t')[0]) return devices
# 打包下载所有日志到当前目录 def bugreport(device, path): os.chdir(path)# bugreport会下载日志到当前文件夹,所以需要先切换到已经创建的目录 command = "adb -s " + str(device) + " bugreport" subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1) print("设备:%s 日志路径:%s" % (str(device), path))