Python 请问,python 中执行 adb logcat 这种,怎么样控制输出呢

王加 · 2019年07月29日 · 最后由 Heroman 回复于 2021年11月11日 · 3472 次阅读

最近需要通过对 adb logcat 中的关键字个数做断言,具体操作就是,连上 adb logcat 后,对手机进行操作,结束 adb logcat 连接,对日志进行过滤,获取关键字个数。
目前就是不知道怎么处理 adb logcat 这块的输出。贴上代码

目前报错是直接报超时

麻烦大佬帮忙看看,赶紧不尽

共收到 6 条回复 时间 点赞

我觉得是: command 命令一直执行,但设置了超时 5s , 5s 到了,子进程没返回,超时报错。
你需要修改 command ,但怎么做还是看需求,现在你的描述我感觉没有描述清你的代码目的,所以无法提供有效的意见

比如改成 command='adb logcat -t 50 >./logcat.txt' 之类的

用 os.popen()
fd = os.popen("adb logcat")
while True:
content = fd.read(10)

匿名 #3 · 2019年07月29日

看了一下我以前的写法,如下:

results = subprocess.Popen("adb devices", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.readlines()
    for line in results:
      print line

仅供参考,很久没写了,也不知道现在能不能用了

里面有些方法,希望能够提供帮助
https://github.com/NJ-zero/Android-Excel

logcat 的进程一直在运行,所以你 wait 肯定是会超时的,有两种方案:
1、同 1 楼,指定 logcat 输出的日志数量,前提是你能知道日志有多少;
2、实时获取 logcat 输出,跟命令行实时刷新一样:

import subprocess

logcat = subprocess.Popen(["adb", "logcat"], stdout=subprocess.PIPE)
while not logcat.poll():
    line = logcat.stdout.readline()
    if line:
        print(line)  # your logic
    else:
        break
print("Return code", logcat.returncode)

logcat.kill()  # kill logcat process if needed

以上。

原因是 logcat 一直输出导致占用。而你设置的 5 所以会 timeout。 可以试试用多线程的方式。


请看下遇到过这个问题么

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册