网上找了一遍,没找到合适的代码,自己写了个,不解释,直接上代码,自己下载试试吧!
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()