安卓检测logcat输出内容脚本

import subprocess
import datetime
import os
import re
import time
#logcat中的关键词例子,根据需要添加
INFO = ["Launch Bugly"]
#logcat中的关键词+输出结果,1对1关系,根据需要添加
RESULT = {"Launch Bugly":"检测到启动bugly"}   
timeForLog = "%m-%d %H:%M:%S"
timeForFile = "%Y-%m-%d %H-%M-%S"
fileTime = datetime.datetime.now().strftime(timeForFile)
PATH = os.getcwd()
FILEPATH = PATH + r"/"+fileTime+"logcat.txt"
def logcatCatcher():
    result = os.popen("adb shell date '+%s'")    
    timestamp = result.read()  
    timestamp = int(timestamp)
    timeLocal  = time.localtime(timestamp)
    #手机系统当前时间,手机时间有改动最好清一下logcat
    phoneTime = time.strftime("%m-%d %H:%M:%S",timeLocal) 
    #'adb logcat -v time |findstr keyword'
    ps = subprocess.Popen('adb logcat -v time ',stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
    with open(FILEPATH,"a", encoding='utf-8') as file:
        file.write("===========开始===========")
        file.close()
    for lines in ps.stdout:
        for inf in INFO : 
            #每行的内容,有需要可以加入正则提取         
            line = str(lines, encoding = "utf-8")
            mat = re.search(r"(\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2}:\d{1,2})",line)
            LogTime = datetime.datetime.now().strftime(timeForLog)
            if inf in line:                
                mat = re.search(r"(\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2}:\d{1,2})",line)
                LogTime = datetime.datetime.now().strftime(timeForLog)
                #生成时间要比程序启动要晚
                if mat.group(0)  >= phoneTime:
                    print(RESULT[inf])
                    # 输出符合条件的行
                    # print(line)
                    LogTime = datetime.datetime.now().strftime(timeForLog)
                    res = "\n"+LogTime+RESULT[inf]+"\n"
                    #输出到文件
                    with open(FILEPATH,"a", encoding='utf-8') as file:
                        file.write(res)
                        # 输出符合条件的行到文件
                        # file.write(line)
                        file.close()
if __name__=='__main__':    
    logcatCatcher()    

 

你可能感兴趣的:(Python)