如何为Android Studio虚拟机加载等待设置120秒超时并返回错误?
解决ADB等待设备启动超时问题
方法1:用subprocess替代os.system实现Python层面超时控制
os.system无法直接设置超时,改用subprocess.run()可以轻松实现120秒超时,超时后会抛出TimeoutExpired异常,可捕获并处理错误:
import subprocess import os # 启动Android模拟器 os.system('emulator -avd Galaxy_Note9_API_27 -writable-system -no-snapshot-update-time') # 等待设备完全启动,设置120秒超时阈值 try: subprocess.run( ["adb", "-s", "emulator-5554", "wait-for-device", "shell", "while [[ -z $(getprop dev.bootcomplete) ]] ; do sleep 1; done"], timeout=120, check=True ) except subprocess.TimeoutExpired: print("错误:等待设备启动超时(120秒),虚拟机可能卡死") # 可添加后续处理逻辑,例如强制终止模拟器进程 except subprocess.CalledProcessError: print("错误:ADB命令执行失败")
方法2:在Shell命令中嵌入超时逻辑(适用于Linux/macOS)
若坚持使用os.system,可借助系统自带的超时工具实现控制:
Linux环境
exit_code = os.system("timeout 120 adb -s emulator-5554 wait-for-device shell 'while [[ -z $(getprop dev.bootcomplete) ]] ; do sleep 1; done'") if exit_code != 0: print("等待设备启动超时或命令执行失败")
macOS环境
macOS需先安装coreutils(brew install coreutils),再使用gtimeout:
exit_code = os.system("gtimeout 120 adb -s emulator-5554 wait-for-device shell 'while [[ -z $(getprop dev.bootcomplete) ]] ; do sleep 1; done'") if exit_code != 0: print("等待设备启动超时或命令执行失败")
补充说明
wait-for-device仅保证ADB能连接设备,getprop dev.bootcomplete才是判断系统完全启动的标准(返回1表示启动完成),原循环逻辑是合理的。- Windows环境无原生适配的
timeout工具,更推荐使用方法1的subprocess实现跨平台超时控制。
内容的提问来源于stack exchange,提问作者Abdul Hossein Charkhi
相关产品推荐
相关产品推荐

