本文摘自php中文网,作者coldplay.xixi,侵删。

相关学习推荐:python教程
本文主要介绍使用Python调用ADB命令实现实时监控logcat关键字的功能
采用多进程,可同时监控多个设备,监控多个关键字。
需要配置ADB环境,具体配置就不多介绍,随便搜一下一大把,直接上代码
通过一个全局变量控制开启和关闭监控功能, INSTRUCTION 用于根据指令获取对应的方法名
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 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" )
|
监控关键字主函数,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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
1 2 3 4 5 | # 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"后输出如下,通过对命令执行拿到的字符串切割获取所有设备号以列表方式存储

1 2 3 4 5 6 7 8 9 10 | # 获取所有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" ):
devices.append(i.split( '\t' )[0])
return devices
|
1 2 3 4 5 6 | # 打包下载所有日志到当前目录
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))
|
以 当前文件所在目录/年/月/日 格式获取日志路径,如果不存在自动创建
1 2 3 4 5 6 7 8 9 | # 获取日志存放路径,如果不存在则按日期创建
def get_log_path(tag):
year = datetime.datetime.now(). strftime ( '%Y' )
month = datetime.datetime.now(). strftime ( '%m' )
day = datetime.datetime.now(). strftime ( '%d' )
path = os.path.join(LOG_PATH, tag, year, month, day)
if not os.path.exists(path):
os.makedirs(path)
return path
|
main函数,循环接收指令,根据接收的指令拿到方法名,并通过eval()方法执行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def main():
while True:
print ( "-" * 100)
print ( "1:开启关键字监控\n2:停止关键字监控\n3:退出" )
print ( "-" * 100)
instruction = str(input( "\n\n请输入要进行的操作号:\n" ))
print ( "-" * 100)
while instruction not in INSTRUCTION.keys():
instruction = str(input( "\n\n输入无效,请重新输入:" ))
if int(instruction) == 9:
exit () # TODO 退出前需要判断是否有正在执行的monkey任务和关键字监控任务
eval (INSTRUCTION[str(instruction)] + "()" )
if __name__ == '__main__' :
main()
|
代码分段之后有点凌乱,看不明白可以把代码复制到一个文件里捋一下就明白了
想了解更多编程学习,敬请关注php培训栏目!
以上就是监控python logcat关键字的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python单引号和双引号的区别
Python的cmd命令行在哪里
Python int()怎么用
Python类变量和实例变量的区别
Python爬虫多少线程合适
Python英语是什么意思
Python 匹配url中是否存在ip地址的方法
利用Python反向输出一个字符串
Python中怎么定义一个类
Python实现的求解最大公约数算法示例
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » 监控python logcat关键字