能夠直接在命令行中輸入adb shell dumpsys window | findstr mCurrentFocus
python
以手機QQ爲例,讀取到的mCurrentFocus的信息爲shell
mCurrentFocus=Window{cb7270e u0 com.tencent.mobileqq/com.tencent.mobileqq.activity.AddAccountActivity}
app
而後經過字符串分割,提取出包名 "com.tencent.mobileqq", 若是有須要的話一樣能夠獲取到當前活動名。命令行
若是在Python中使用的話,能夠用以下方法日誌
import os data = os.popen("adb shell dumpsys window | findstr mCurrentFocus") mCurrentFocus = data.read() list1 = mCurrentFocus.split(' ') list2 = list1[4].split('/') packageName = list2[0] print(packageName)
在命令行中直接輸入命令adb shell "ps | grep com.tencent.mobileqq"
能夠獲得這個應用全部的進程信息,有的App只有一個進程,有些App會有多個進程。這裏注意 grep命令是在Linux 下使用的,若是想在Windows環境下使用,先後須要加上雙引號,不然會報錯。code
u0_a98 991 744 2202676 125564 0 0 S com.tencent.mobileqq:tool u0_a98 31810 744 1938984 68956 0 0 S com.tencent.mobileqq:MSF u0_a98 32714 744 2218736 226968 0 0 S com.tencent.mobileqq
其中第二列爲進程的PID,而後咱們能夠經過Python中的分割字符串等操做來獲取PID。server
網上一些帖子都使用了find
方法或者grep
方法,這些在查找的時候都會附加一些其餘的日誌,經過查看adb logcat的幫助文檔,發現其中有一條進程
--pid=<pid> Only prints logs from the given pid
文檔
這樣咱們能夠經過以下命令來獲取制定的PID的日誌字符串
adb shell logcat --pid=32714
或者更簡便的
adb shell logcat --pid=$(pidof -s com.tencent.mobileqq)
同時咱們還能夠加以約束,好比只要Warning以上的日誌
adb shell logcat *:W --pid=$(pidof -s com.tencent.mobileqq)
獲得的日誌以下
--------- beginning of main 06-04 20:39:56.804 32714 710 E DingdongPluginBizHandler: 0x51d_1 respond msf error: retCode[1002]. 06-04 20:40:52.953 32714 32714 W InputMethodManager: startInputReason = 1 06-04 20:40:52.971 32714 32747 W libEGL : EGLNativeWindowType 0xe0e6d808 disconnect failed
有兩種方法
1.一種是在命令中直接添加> filepath
,命令以下
adb shell logcat *:W > E:/log.txt
2.更改subprocess.Popen的屬性
logfile = open("E:/log.txt", 'w') command = "adb shell logcat *:W" subprocess.Popen(command, stdout = logfile, shell=True)
運行代碼後,一共會打開兩個進程, 一個是 cmd.exe
,第二個是adb.exe
,都要關閉
log = subprocess.Popen(command) ##關閉 try: log.terminate() #關閉 cmd.exe os.popen("adb kill-server") #關閉 adb.exe except: pass
經過更改subprocess 中的startupinfo
st = subprocess.STARTUPINFO st.dwFlags = subprocess.STARTF_USESHOWWINDOW st.wShowWindow = subprocess.SW_HIDE cmd = subprocess.Popen(command, startupinfo=st)