Close unclosed ports (#388)

This commit is contained in:
Alek Petuskey 2023-01-29 15:50:11 -08:00 committed by GitHub
parent b06f612a7d
commit 1ab8620852
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 5 deletions

View File

@ -87,10 +87,14 @@ def run(
assert frontend_cmd and backend_cmd, "Invalid env"
# Run the frontend and backend.
if frontend:
frontend_cmd(app.app, Path.cwd(), port)
if backend:
backend_cmd(app.__name__, loglevel=loglevel)
try:
if frontend:
frontend_cmd(app.app, Path.cwd(), port)
if backend:
backend_cmd(app.__name__, loglevel=loglevel)
finally:
utils.kill_process_on_port(os.environ["PORT"])
utils.kill_process_on_port(utils.get_api_port())
@cli.command()

View File

@ -30,7 +30,7 @@ from typing import (
Union,
)
from urllib.parse import urlparse
import psutil
import plotly.graph_objects as go
import typer
import uvicorn
@ -582,6 +582,22 @@ def get_api_port() -> int:
return port
def kill_process_on_port(port):
"""Kill the process on the given port.
Args:
port: The port.
"""
for proc in psutil.process_iter(["pid", "name", "cmdline"]):
try:
for conns in proc.connections(kind="inet"):
if conns.laddr.port == port:
proc.kill()
return
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
def run_backend(app_name: str, loglevel: constants.LogLevel = constants.LogLevel.ERROR):
"""Run the backend.