Python implements filtering for individual Android program log script sharing

  • 2020-04-02 14:32:25
  • OfStack

In Android software development, it is important to add a log, so that we can understand the execution and data of the program. Eclipse development tools provide visual tools, but the end result is still more efficient, so I write my own python script to filter a program's logs by package name.

The principle of

The package name is used to get the corresponding process ID (possibly more than one), and then adb logcat is used to filter the process ID to get the log of the corresponding program.

The source code


#!/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)

Method of use


python logcatPkg.py com.mx.browser

The latest code


#!/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)

insufficient

When the script is executed, if the Android program is closed or restarted, the process ID will change and the log will not continue automatically, so the script can only be executed again.


Related articles: