要在Python中調用ADB命令,您可以使用subprocess
模塊
import subprocess
def run_adb_command(command):
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
output, error = process.communicate()
if process.returncode != 0:
print(f"Error occurred while running ADB command: {error.decode('utf-8')}")
else:
print(f"ADB command output: {output.decode('utf-8')}")
# 示例:列出設備上的所有應用程序
adb_command = "adb devices"
run_adb_command(adb_command)
# 示例:安裝一個應用程序(請確保將路徑替換為您的APK文件的實際路徑)
apk_path = "/path/to/your/app.apk"
adb_command = f"adb install {apk_path}"
run_adb_command(adb_command)
在這個示例中,我們定義了一個名為run_adb_command
的函數,它接受一個ADB命令作為參數。我們使用subprocess.Popen
來運行命令,并通過stdout
和stderr
捕獲輸出和錯誤。如果命令執行成功,我們將輸出打印到控制臺;否則,我們將錯誤打印到控制臺。
請注意,您可能需要根據您的系統和ADB安裝路徑調整示例中的ADB命令。此外,如果您尚未安裝ADB,請訪問Android開發者網站以獲取有關如何下載和安裝它的說明。