Kill process using a specific port (cross-platform)
(port: int)
| 130 | |
| 131 | |
| 132 | def kill_process_on_port(port: int): |
| 133 | """Kill process using a specific port (cross-platform)""" |
| 134 | current_platform = get_platform() |
| 135 | |
| 136 | try: |
| 137 | if current_platform == "windows": |
| 138 | # Windows: use netstat and taskkill |
| 139 | result = subprocess.run( |
| 140 | f"netstat -ano | findstr :{port}", |
| 141 | capture_output=True, |
| 142 | text=True, |
| 143 | shell=True, |
| 144 | ) |
| 145 | if result.stdout: |
| 146 | for line in result.stdout.strip().split("\n"): |
| 147 | parts = line.split() |
| 148 | if len(parts) >= 5: |
| 149 | pid = parts[-1] |
| 150 | if pid.isdigit(): |
| 151 | subprocess.run( |
| 152 | f"taskkill /F /PID {pid}", |
| 153 | shell=True, |
| 154 | capture_output=True, |
| 155 | ) |
| 156 | print(f" ✓ Killed process on port {port} (PID: {pid})") |
| 157 | else: |
| 158 | # macOS/Linux: use lsof |
| 159 | result = subprocess.run( |
| 160 | f"lsof -ti :{port}", capture_output=True, text=True, shell=True |
| 161 | ) |
| 162 | if result.stdout: |
| 163 | pids = result.stdout.strip().split("\n") |
| 164 | for pid in pids: |
| 165 | if pid.isdigit(): |
| 166 | os.kill(int(pid), signal.SIGKILL) |
| 167 | print(f" ✓ Killed process on port {port} (PID: {pid})") |
| 168 | except Exception as e: |
| 169 | print(f" ⚠️ Could not kill process on port {port}: {e}") |
| 170 | |
| 171 | |
| 172 | def cleanup_ports(): |
no test coverage detected