在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變化,無法自動繼續輸出日志,只能再次執行此腳本。