"""gui_core_pkg.adb - ADB 可执行文件查找与设备列表。 - find_adb_executable 在 PATH / 项目目录内查找 adb 可执行 - list_adb_devices 列出当前已连接设备 - resolve_adb_device 按 device_id 解析具体设备(含模糊匹配) """ from __future__ import annotations import os import shutil import subprocess from typing import Optional def find_adb_executable() -> str: """返回可用的 adb 可执行文件路径(优先 PATH,其次默认安装目录)。""" adb = shutil.which("adb") if adb: return adb # 默认安装目录(我们之前下载的 platform-tools) localapp = os.environ.get("LOCALAPPDATA") or "" candidates = [] if localapp: candidates.append(os.path.join(localapp, "platform-tools", "adb.exe")) # 兼容某些人手动放到用户目录的情况 userprofile = os.environ.get("USERPROFILE") or "" if userprofile: candidates.append( os.path.join(userprofile, "AppData", "Local", "platform-tools", "adb.exe") ) for p in candidates: if os.path.exists(p): return p return "" def list_adb_devices(adb_exe: str) -> list[str]: try: if not adb_exe: return [] proc = subprocess.run( [adb_exe, "devices", "-l"], capture_output=True, text=True, encoding="utf-8", errors="replace", check=False, ) except FileNotFoundError: return [] devices: list[str] = [] for line in (proc.stdout or "").splitlines()[1:]: parts = line.split() if len(parts) >= 2 and parts[1] == "device": devices.append(parts[0]) return devices def resolve_adb_device(adb_exe: str, requested_device_id: str = "") -> str: device_id = str(requested_device_id or "").strip() devices = list_adb_devices(adb_exe) if device_id: if device_id in devices: return device_id raise RuntimeError(f"指定的 device_id '{device_id}' 当前不可用") if len(devices) == 1: return devices[0] if len(devices) > 1: raise RuntimeError(f"检测到多台 adb 设备,请先明确选择 device_id: {', '.join(devices)}") raise RuntimeError("未检测到可用的 adb 设备")