"""Save uvicorn PID for the local package (best effort). Usage: save_pid.py """ import subprocess import sys from pathlib import Path def main() -> int: if len(sys.argv) != 3: print("usage: save_pid.py ", file=sys.stderr) return 2 port = sys.argv[1] pidfile = Path(sys.argv[2]) pid = "" try: out = subprocess.check_output( [ "powershell", "-NoProfile", "-Command", ( "Get-CimInstance Win32_Process -Filter \"Name='python.exe'\" | " "Where-Object { $_.CommandLine -match 'uvicorn' -and $_.CommandLine -match 'app.main' " f"-and $_.CommandLine -match '{port}' }} | " "Select-Object -First 1 -ExpandProperty ProcessId" ), ], stderr=subprocess.DEVNULL, timeout=15, ) text = out.decode("utf-8", errors="replace").strip() if text: pid = text.splitlines()[0].strip() except Exception as exc: print(f"WARN {type(exc).__name__}", flush=True) pidfile.parent.mkdir(parents=True, exist_ok=True) pidfile.write_text(pid + "\n", encoding="utf-8") print(pid or "PID_NOT_FOUND") return 0 if __name__ == "__main__": raise SystemExit(main())