diff --git a/pynecone/pc.py b/pynecone/pc.py index 15f7c7922..cba0c8293 100644 --- a/pynecone/pc.py +++ b/pynecone/pc.py @@ -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() diff --git a/pynecone/utils.py b/pynecone/utils.py index f8c376700..a415b46a2 100644 --- a/pynecone/utils.py +++ b/pynecone/utils.py @@ -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.