使用夜神模拟器跑自动化时不时的发现模拟器黑屏挂掉。该脚本通过定时查询模拟器的连接状态,一旦发现连接状态异常了即重新启动模拟器。
需要传入3个参数:
--nox_dir: eg:D:\Nox
--monitor_device: eg:127.0.0.1:62.25
--emulator_name eg:自动化模拟器(模拟器设置名称)
import logging
import subprocess
import time
import argparse
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
CHECK_EMULATOR_STATUS_INTERVAL_TIME = 15
REBOOT_STATUS_CHECK_INTERVAL_TIME = 3
def check_device_status(monitor_device):
"""检查设备连接状态。"""
try:
cmd = ["adb", "devices"]
result = subprocess.run(cmd, capture_output=True, text=True)
lines = result.stdout.splitlines()
for line in lines:
if monitor_device in line and 'offline' not in line:
return True
logging.info(f"设备可能断开连接了, 查询信息:{lines}")
return False
except Exception as e:
logging.error(f"查询设备连接状态时异常,命令:{cmd},错误信息:{e}")
return False
def check_emulator_status(nox_console_cmd_path, emulator_name):
"""检查模拟器启动状态。"""
cmd = [nox_console_cmd_path, "list"]
result = subprocess.run(cmd, capture_output=True, text=True)
lines = result.stdout.splitlines()
for line in lines:
if emulator_name in line:
ps_id = int(line.split(",")[-1])
if ps_id == -1:
return False
else:
return True
def start_emulator(nox_console_cmd_path, emulator_name):
"""启动模拟器。"""
cmd = [nox_console_cmd_path, "launch", f"-name:{emulator_name}"]
subprocess.run(cmd)
def quit_emulator(nox_console_cmd_path, emulator_name):
"""退出模拟器。"""
cmd = [nox_console_cmd_path, "quit", f"-name:{emulator_name}"]
subprocess.run(cmd)
def check_and_restart_emulator(nox_dir, monitor_device, emulator_name):
"""检查并重启模拟器。"""
nox_console_inner_path = r"\bin\NoxConsole.exe"
nox_console_cmd_path = nox_dir + nox_console_inner_path
while True:
if not check_device_status(monitor_device):
logging.info("CheckPoint1: 连接异常,准备重启模拟器")
quit_emulator(nox_console_cmd_path, emulator_name)
while check_emulator_status(nox_console_cmd_path, emulator_name):
time.sleep(REBOOT_STATUS_CHECK_INTERVAL_TIME)
logging.info("CheckPoint2: 模拟器关闭成功,准备启动")
start_emulator(nox_console_cmd_path, emulator_name)
while not check_device_status(monitor_device):
time.sleep(REBOOT_STATUS_CHECK_INTERVAL_TIME)
logging.info("CheckPoint3: 模拟器重启成功")
time.sleep(CHECK_EMULATOR_STATUS_INTERVAL_TIME)
def show_command_example():
"""显示启动命令的样例。"""
example = (
"python your_script_name.py --nox_dir <path_to_nox_directory> "
"--monitor_device <device_address> --emulator_name <emulator_name>"
)
print(example)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Monitor and restart Nox emulator.')
parser.add_argument('--nox_dir', required=True, help='Path to Nox installation directory.')
parser.add_argument('--monitor_device', required=True, help='Device address to monitor.')
parser.add_argument('--emulator_name', required=True, help='Name of the emulator.')
parser.add_argument('--show-example', action='store_true', help='Show command example.')
args = parser.parse_args()
if args.show_example:
show_command_example()
else:
check_and_restart_emulator(args.nox_dir, args.monitor_device, args.emulator_name)