#!/usr/bin/env python # -*- coding: utf-8 -*- """ 示例:后台主程序如何启动 GUI 将此文件放在后台工程根目录,作为参考 """ import subprocess import sys import os class GUIManager: """GUI 进程管理器""" def __init__(self, api_host='127.0.0.1', api_port=5050): self.api_host = api_host self.api_port = api_port self.gui_process = None def start_gui(self): """启动 GUI 前端""" gui_script = os.path.join( os.path.dirname(__file__), 'frontend_gui', 'launch_gui.py' ) if not os.path.exists(gui_script): print(f"错误: GUI 启动脚本不存在: {gui_script}") return False print(f"启动 GUI 前端...") print(f" API 地址: http://{self.api_host}:{self.api_port}") try: self.gui_process = subprocess.Popen( [ sys.executable, gui_script, '--api-host', self.api_host, '--api-port', str(self.api_port), '--debug' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=os.path.dirname(os.path.abspath(__file__)) ) print(f"GUI 进程已启动,PID: {self.gui_process.pid}") return True except Exception as e: print(f"启动 GUI 失败: {e}") return False def stop_gui(self): """停止 GUI 进程""" if self.gui_process: print("正在关闭 GUI...") self.gui_process.terminate() try: self.gui_process.wait(timeout=5) print("GUI 已关闭") except subprocess.TimeoutExpired: print("GUI 未响应,强制关闭") self.gui_process.kill() self.gui_process.wait() def is_running(self): """检查 GUI 是否运行""" if self.gui_process: return self.gui_process.poll() is None return False def main(): """示例:在后台程序中集成 GUI 启动""" print("=== 后台主程序示例 ===") # 1. 启动后台服务(这里省略,实际应该启动 Flask 等) print("1. 后台服务启动...") # 2. 创建 GUI 管理器并启动 GUI gui_manager = GUIManager(api_host='127.0.0.1', api_port=5050) if gui_manager.start_gui(): print("2. GUI 前端已启动") else: print("2. GUI 前端启动失败") return # 3. 等待用户操作 try: print("\n系统运行中,按 Ctrl+C 退出...\n") while gui_manager.is_running(): import time time.sleep(1) print("GUI 已退出") except KeyboardInterrupt: print("\n收到退出信号") finally: # 4. 清理 gui_manager.stop_gui() print("后台服务关闭") if __name__ == '__main__': main()