"""Stop any python/uvicorn process listening on 127.0.0.1:. Usage: stop_port.py """ import subprocess import sys def main() -> int: if len(sys.argv) != 2: print("usage: stop_port.py ", file=sys.stderr) return 2 port = sys.argv[1] stopped = [] try: out = subprocess.check_output( [ "powershell", "-NoProfile", "-Command", ( f"$c=Get-NetTCPConnection -LocalPort {port} -State Listen -ErrorAction SilentlyContinue; " f"if($c){{ $c | ForEach-Object {{ " f"$p=Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue; " f"if($p){{ Stop-Process -Id $_.OwningProcess -Force; " f"Write-Output $_.OwningProcess }} }} }}" ), ], stderr=subprocess.DEVNULL, timeout=20, ) text = out.decode("utf-8", errors="replace").strip() if text: stopped = [line.strip() for line in text.splitlines() if line.strip()] except Exception as exc: print(f"WARN {type(exc).__name__}: {exc}", file=sys.stderr) print("stopped=" + ",".join(stopped) if stopped else "none") return 0 if __name__ == "__main__": raise SystemExit(main())