1. 程式人生 > >python實現adb shell之後的連續執行

python實現adb shell之後的連續執行

import subprocess

#最基本的啟動程序方式類似cmd下執行: notepad.exe text.txt 命令
obj = subprocess.Popen(['notepad.exe','text.txt'], shell = True, stdin=subprocess.PIPE, stdout=subprocess.PIPE ,stderr=subprocess.PIPE)
print(obj.stderr.read().decode('gbk'))

#進入某個環境執行語句,需要依賴上次執行的狀態
obj = subprocess.Popen('python', shell =
True, stdin=subprocess.PIPE, stdout=subprocess.PIPE ,stderr=subprocess.PIPE) obj.stdin.write('print(6+7)'.encode('utf-8')) info,err = obj.communicate() print(info.decode('gbk')) #進入某個環境執行語句(adb shell),注意shell內部命令需要帶\n,執行完後一定記得執行exit命令退出,否則會阻塞 obj = subprocess.Popen(['adb', 'shell'], shell = True, stdin=
subprocess.PIPE, stdout=subprocess.PIPE ,stderr=subprocess.PIPE) obj.stdin.write('ls\n'.encode('utf-8')) obj.stdin.write('exit\n'.encode('utf-8')) #重點,一定要執行exit info,err = obj.communicate() print(info.decode('gbk')) print(err.decode('gbk')) #進入某個環境執行語句(adb shell),命令用列表方式全部列出 cmds = [ "cd data"
, 'cd data', "ls", "exit",#這是是非常關鍵的,退出 ] obj = subprocess.Popen("adb shell", shell= True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) info = obj.communicate(("\n".join(cmds) + "\n").encode('utf-8')); for item in info: if item: print(item.decode('gbk')) #當需要連續實時輸出資訊時,採用obj.stdout.readline方式讀取 import chardet obj = subprocess.Popen("adb logcat", shell = True, stdin=subprocess.PIPE, stdout=subprocess.PIPE ,stderr=subprocess.PIPE) for item in iter(obj.stdout.readline,'b'): encode_type = chardet.detect(item) if encode_type['encoding'] == 'utf-8': print(item.decode('utf-8')) else: print(item.decode('gbk'))