#!/usr/bin/env python3 # -*- coding: utf-8 -*- """修复浏览器池初始化 - 在socketio启动前同步初始化""" import re with open('/www/wwwroot/zsglpt/app.py', 'r', encoding='utf-8') as f: content = f.read() # 1. 删除模块级别的后台初始化线程启动代码 # 这行代码在 if __name__ == '__main__': 之前,会在eventlet接管后执行 old_init_code = '''def init_pool_background(): import time time.sleep(5) # 等待应用启动 try: config = database.get_system_config() pool_size = config.get('max_screenshot_concurrent', 3) print(f"[浏览器池] 开始预热 {pool_size} 个浏览器...") init_browser_pool(pool_size=pool_size) except Exception as e: print(f"[浏览器池] 初始化失败: {e}") threading.Thread(target=init_pool_background, daemon=True).start() if __name__ == '__main__':''' # 替换为新的代码 - 移除后台线程 new_init_code = '''if __name__ == '__main__':''' if old_init_code in content: content = content.replace(old_init_code, new_init_code) print("OK - 已移除后台初始化线程") else: print("WARNING - 未找到后台初始化代码,尝试其他模式") # 2. 在 socketio.run 之前添加同步初始化 # 查找 socketio.run 位置,在其之前添加初始化代码 old_socketio_run = ''' print("=" * 60 + "\\n") socketio.run(app, host=config.SERVER_HOST, port=config.SERVER_PORT, debug=config.DEBUG)''' new_socketio_run = ''' print("=" * 60 + "\\n") # 同步初始化浏览器池(必须在socketio.run之前,否则eventlet会导致asyncio冲突) try: system_cfg = database.get_system_config() pool_size = system_cfg.get('max_screenshot_concurrent', 3) if system_cfg else 3 print(f"正在预热 {pool_size} 个浏览器实例(截图加速)...") init_browser_pool(pool_size=pool_size) print("✓ 浏览器池初始化完成") except Exception as e: print(f"警告: 浏览器池初始化失败: {e}") socketio.run(app, host=config.SERVER_HOST, port=config.SERVER_PORT, debug=config.DEBUG)''' if old_socketio_run in content: content = content.replace(old_socketio_run, new_socketio_run) print("OK - 已添加同步初始化代码") else: print("WARNING - 未找到socketio.run位置") with open('/www/wwwroot/zsglpt/app.py', 'w', encoding='utf-8') as f: f.write(content) print("完成!浏览器池将在socketio启动前同步初始化")