如果你希望使用Python進行一些簡單的安卓模擬器自動化操作,如自動化測試或腳本化一些例行任務,可以使用adb(Android Debug Bridge)工具來實現。下面是一個簡單的Python腳本示例,該腳本演示了如何使用adb命令來與安卓模擬器交互。
首先,你需要確保已經安裝adb,並且模擬器正在運行。
python
import subprocess
def run_adb_command(command):
"""運行 adb 命令並返回結果"""
result = subprocess.run(command, shell=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode == 0:
return result.stdout.strip()
else:
raise Exception(f"Command failed: {result.stderr.strip()}")
def get_connected_devices():
"""獲取所有已連接的安卓設備"""
command = "adb devices"
output = run_adb_command(command)
devices = []
for line in output.splitlines()[1:]: # 第一行是標題
if line.strip():
devices.append(line.split()[0])
return devices
def install_app(device_id, apk_path):
"""將 APK 安裝到指定設備"""
command = f"adb -s {device_id} install {apk_path}"
print(run_adb_command(command))
def launch_app(device_id, package_name):
"""啟動指定設備上的應用程式"""
command = f"adb -s {device_id} shell monkey -p {package_name} -c android.intent.category.LAUNCHER 1"
print(run_adb_command(command))
if __name__ == "__main__":
try:
devices = get_connected_devices()
if not devices:
print("No devices found.")
else:
print("Connected devices:", devices)
# 示例 APK 路徑和包名(根據實際情況替換)
apk_path = "/path/to/your/app.apk"
package_name = "com.example.yourapp"
# 針對第一臺檢測到的設備進行操作
device_id = devices[0]
install_app(device_id, apk_path)
launch_app(device_id, package_name)
except Exception as e:
print("An error occurred:", e)
注意事項:
- 確保
adb工具已正確安裝並添加到系統路徑中,以使腳本能夠正常運行。
- 替換
apk_path 和 package_name 為實際的應用程序文件路徑和包名。
- 請根據你的系統環境(Windows/Linux/MacOS)確認
shell=True 的使用是合理的。
這個腳本的目的是演示如何使用Python與安卓模擬器進行基本交互。如果你需要更複雜的功能或大規模自動化測試,建議考慮使用更專業的框架,如Appium。