最近在用python做一個小工具,自動執行一些adb shell命令,使用subprocess.Popen來實現。
不過遇到個問題就是執行adb shell后就無法執行后面adb shell里的命令了,查詢得知subprocess.Popen可以自定義stdin參數來源,比如可以使用上一個命令的stdout來做為下一個命令的stdin
p1 = subprocess.Popen('adb shell', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p2 = subprocess.Popen('ls', shell=True, stdin=p1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print p2.stdout.read()
但在這里並未執行成功,懷疑原因是用subprocess執行adb shell,是在CMD環境下執行,而后面執行ls命令,就已經進入adb shell環境了
當然,我們可以直接在CMD中輸入adb shell ls
來達到目的,但一些adb shell自有命令如ll、grep在CMD中就無法識別
找到兩個解決辦法:
一、
-
把命令先保存在一個txt文檔,如在D盤建一個a.txt,里面保存命令
cat /data/system/packages.xml | grep -E "a|b|c|d"
-
用輸入重定向的方法在CMD輸入:
adb shell < a.txt
可以看到命令已經在CMD中執行了,但是會卡死,此時任何輸入有效,但不顯示,需要CTRL+C后才會顯示出來 -
也可以將第2步做成BAT自動執行,建立一個run.bat,輸入
adb shell < d:\a.txt
保存后直接執行run.bat就可以了
二、
上個方法雖然可行,但太過麻煩,而且需要第3方的文件來周轉,之后在一個網友的幫助下,得到解決辦法:
1.依然用python的subprocess.Popen實現
p1 = subprocess.Popen('adb shell cd sdcard&&cd Android&&cd data&&ls |grep com', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print p1.stdout.read()
同時執行多行命令:
無論是 Linux/Mac 還是 Windows 的 shell 命令都支持一條命令來執行多條命令的。一共有&&
,&
,||
,|
這么幾種方式,這幾種方式分別代表着不同的含義:
&&:command1 && command2,如果 command1 執行成功了,就執行命令 command2,如果 command1 失敗了,就不會執行 command2 了。
&:command1 & command2,無論 command1 執行成功與否都會執行 command2。
||:command1 || command2,如果 command1 執行成功了,就不會執行 command2 了,如果 command1 失敗了,就會繼續執行 command2。
|:command1 | command2,command1 的結果做為 command2 的參數,如果 command1 失敗了,整個命令也就都失敗了。
Linux/Mac 下還可以使用;
來鏈接兩條命令,順序執行命令,不管成功與否都往后執行,和&
含義一樣。