溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

監控python logcat關鍵字的方法

發布時間:2020-09-08 10:49:19 來源:億速云 閱讀:467 作者:小新 欄目:編程語言

這篇文章給大家分享的是有關監控python 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"后輸出如下,通過對命令執行拿到的字符串切割獲取所有設備號以列表方式存儲

監控python logcat關鍵字的方法

# 獲取所有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
# 打包下載所有日志到當前目錄
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))

以  當前文件所在目錄/年/月/日 格式獲取日志路徑,如果不存在自動創建

# 獲取日志存放路徑,如果不存在則按日期創建
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()方法執行。

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()

代碼分段之后有點凌亂,看不明白可以把代碼復制到一個文件里捋一下就明白了

感謝各位的閱讀!關于監控python logcat關鍵字的方法就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女