# -*- coding: utf-8 -*- """(win) webhost 启动器:杀掉旧实例 → 拉起 uvicorn → 用 PyWebView(WebView2) 打开原生应用窗口。 单用户本地工具。窗口关闭即停止服务并退出;端口被占用时判定旧实例并清理后重启。 若 WebView2 不可用则回退到系统浏览器打开。 """ from __future__ import annotations import socket import subprocess import sys import time import webbrowser from pathlib import Path import psutil PORT = 8799 URL = f"http://127.0.0.1:{PORT}" HERE = Path(__file__).resolve().parent PID_FILE = HERE / ".webhost.pid" def _port_pids() -> list[int]: return [c.pid for c in psutil.net_connections(kind="inet") if c.laddr.port == PORT and c.status in ("LISTEN", "LISTENING") and c.pid] def _kill_existing() -> None: """杀掉旧实例:优先按端口监听进程,兜底按 PID 文件。""" targets = set(_port_pids()) if PID_FILE.exists(): try: targets.add(int(PID_FILE.read_text().strip())) except ValueError: pass for pid in targets: try: proc = psutil.Process(pid) if proc.name().lower().startswith(("python", "uvicorn")): proc.terminate() proc.wait(timeout=4) except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.TimeoutExpired): continue for _ in range(40): # 等待端口释放 if not _port_pids(): break time.sleep(0.25) def _port_free() -> bool: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: return s.connect_ex(("127.0.0.1", PORT)) != 0 def _start_server() -> subprocess.Popen: if not _port_free(): _kill_existing() time.sleep(0.3) cmd = [sys.executable, "-m", "uvicorn", "webhost.backend.main:app", "--host", "127.0.0.1", "--port", str(PORT), "--log-level", "warning"] proc = subprocess.Popen(cmd, cwd=str(HERE.parent), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW) PID_FILE.write_text(str(proc.pid)) for _ in range(60): # 等待就绪 if not _port_free(): return proc if proc.poll() is not None: break time.sleep(0.25) raise RuntimeError("服务启动失败") def _open_window(app_name: str) -> bool: """尝试 PyWebView 原生窗口;失败返回显示不可用。""" try: import webview # noqa: WPS433 webview.create_window(app_name, URL, width=1200, height=780, min_size=(1000, 660), background_color="#eef2f9") webview.start(gui="edgechromium") return True except Exception: return False def _stop(proc: subprocess.Popen) -> None: try: proc.terminate() proc.wait(timeout=5) except Exception: try: proc.kill() except Exception: pass if PID_FILE.exists(): try: PID_FILE.unlink() except OSError: pass def main() -> int: app_name = "37du 业务场景工具集" proc = _start_server() if not _open_window(app_name): # 回退:系统浏览器 webbrowser.open(URL) print(f"[webhost] 已用系统浏览器打开:{URL}") try: while True: time.sleep(1) except KeyboardInterrupt: pass finally: _stop(proc) return 0 else: _stop(proc) return 0 if __name__ == "__main__": sys.exit(main())