使用python脚本实现adb 持续抓log日志,并使用正则匹配关键字log

网上找了一遍,没找到合适的代码,自己写了个,不解释,直接上代码,自己下载试试吧!

import os
import datetime
import subprocess
import re
import time
import threading


class adblog(threading.Thread):
    def __init__(self,action,thread_id,logfile):
        threading.Thread.__init__(self)
        self.action = action
        self.threadID = thread_id
        self.log_file = logfile
        self.logstr = ''
        self.is_running = False
        self.p = subprocess.Popen(self.action, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    def mark_start(self):
        self.is_running = True

    def mark_stop(self):
        self.is_running = False

    def run(self):
        with open(self.log_file, 'w') as file:
            while self.p.poll() is None and self.is_running:
                line = self.p.stdout.readline()
                line = line.strip()
                if line:
                    self.logstr = line.decode("utf-8", "ignore")  # 日志内存在不兼容的字符编码,加上ignore忽略异常
                    file.write(self.logstr+"\n")
                    file.flush()
                    time.sleep(0.02)

    def get_read(self):
        return self.logstr

    def get_adbresult(self,zhengze):
        result = ""
        times = 30
        while times > 0:
            content = str(self.get_read())
            get_result = re.match(zhengze, content)
            if get_result:
                result = get_result.group(1)
                return result
            time.sleep(0.1)
            times -= 1
        return result


if __name__ == '__main__':
    adbdebug = adblog("adb shell \"logcat |grep Wifi\"","adb","adb.log")
    adbdebug.start()
    adbdebug.mark_start()
    #print(adbdebug.get_read())
    time.sleep(2)
    print("开始正则匹配")
    print(adbdebug.get_adbresult(".*WifiService(.*)"))
    time.sleep(3)
    print(adbdebug.get_adbresult(".*getCurrentNetwork(.*)"))
    time.sleep(3)
    adbdebug.mark_stop()

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值