Python实现过滤单个Android程序日志脚本分享

yipeiwu_com5年前Python基础

在Android软件开发中,增加日志的作用很重要,便于我们了解程序的执行情况和数据。Eclipse开发工具会提供了可视化的工具,但是还是感觉终端效率会高一些,于是自己写了一个python的脚本来通过包名来过滤某一程序的日志。

原理

通过包名得到对应的进程ID(可能多个),然后使用adb logcat 过滤进程ID即可得到对应程序的日志。

源码

复制代码 代码如下:

#!/usr/bin/env python
#coding:utf-8
#This script is aimed to grep logs by application(User should input a packageName and then we look up for the process ids then separate logs by process ids).

import os
import sys

packageName=str(sys.argv[1])

command = "adb shell ps | grep %s | awk '{print $2}'"%(packageName)
p = os.popen(command)
##for some applications,there are multiple processes,so we should get all the process id
pid = p.readline().strip()
filters = pid
while(pid != ""):
    pid = p.readline().strip()
    if (pid != ''):
        filters = filters +  "|" + pid
        #print 'command = %s;filters=%s'%(command, filters)
if (filters != '') :
    cmd = 'adb logcat | grep --color=always -E "%s" '%(filters)
    os.system(cmd)

使用方法

复制代码 代码如下:

python logcatPkg.py com.mx.browser

最新代码

复制代码 代码如下:

#!/usr/bin/env python
#coding:utf-8
#This script is aimed to grep logs by application(User should input a packageName and then we look up for the process ids then separate logs by process ids).

import os
import sys

packageName=str(sys.argv[1])

command = "adb shell ps | grep %s | awk '{print $2}'"%(packageName)
p = os.popen(command)
##for some applications,there are multiple processes,so we should get all the process id
pid = p.readline().strip()
filters = pid
while(pid != ""):
    pid = p.readline().strip()
    if (pid != ''):
        filters = filters +  "|" + pid
        #print 'command = %s;filters=%s'%(command, filters)
if (filters != '') :
    cmd = 'adb logcat | grep --color=always -E "%s" '%(filters)
    os.system(cmd)

不足

当脚本执行后,Android程序如果关闭或者重新启动,导致进程ID变化,无法自动继续输出日志,只能再次执行此脚本。

相关文章

python3操作mysql数据库的方法

软硬件环境 OS X EI Capitan Python 3.5.1 mysql 5.6 前言 在开发中经常涉及到数据库的使用,而python对于数据库也有多种解决方法。本文以pyth...

Python的净值数据接口调用示例分享

代码描述:基于Python的净值数据接口调用代码实例 关联数据:净值数据 接口地址:https://www.juhe.cn/docs/api/id/25 #!/usr/bin/pyt...

python TCP Socket的粘包和分包的处理详解

python TCP Socket的粘包和分包的处理详解

概述 在进行TCP Socket开发时,都需要处理数据包粘包和分包的情况。本文详细讲解解决该问题的步骤。使用的语言是Python。实际上解决该问题很简单,在应用层下,定义一个协议:消息头...

Python排序搜索基本算法之冒泡排序实例分析

Python排序搜索基本算法之冒泡排序实例分析

本文实例讲述了Python排序搜索基本算法之冒泡排序。分享给大家供大家参考,具体如下: 冒泡排序和选择排序类似,也是第n次把最小的元素排在第n的位置上,也是该元素的绝对位置,只是冒泡排序...

Python全栈之列表数据类型详解

前言 列表(list)同字符串一样都是有序的,因为他们都可以通过切片和索引进行数据访问,且列表是可变的。 创建列表的几种方法 第一种 name_list = ['Python',...