|
37 | 37 | from plotly.io import to_json
|
38 | 38 | from redis import Redis
|
39 | 39 | from rich.console import Console
|
| 40 | +from rich.prompt import Prompt |
40 | 41 |
|
41 | 42 | from pynecone import constants
|
42 | 43 | from pynecone.base import Base
|
@@ -582,20 +583,63 @@ def get_api_port() -> int:
|
582 | 583 | return port
|
583 | 584 |
|
584 | 585 |
|
585 |
| -def kill_process_on_port(port): |
586 |
| - """Kill the process on the given port. |
| 586 | +def get_process_on_port(port) -> Optional[psutil.Process]: |
| 587 | + """Get the process on the given port. |
587 | 588 |
|
588 | 589 | Args:
|
589 | 590 | port: The port.
|
| 591 | +
|
| 592 | + Returns: |
| 593 | + The process on the given port. |
590 | 594 | """
|
591 | 595 | for proc in psutil.process_iter(["pid", "name", "cmdline"]):
|
592 | 596 | try:
|
593 | 597 | for conns in proc.connections(kind="inet"):
|
594 |
| - if conns.laddr.port == port: |
595 |
| - proc.kill() |
596 |
| - return |
| 598 | + if conns.laddr.port == int(port): |
| 599 | + return proc |
597 | 600 | except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
|
598 | 601 | pass
|
| 602 | + return None |
| 603 | + |
| 604 | + |
| 605 | +def is_process_on_port(port) -> bool: |
| 606 | + """Check if a process is running on the given port. |
| 607 | +
|
| 608 | + Args: |
| 609 | + port: The port. |
| 610 | +
|
| 611 | + Returns: |
| 612 | + Whether a process is running on the given port. |
| 613 | + """ |
| 614 | + return get_process_on_port(port) is not None |
| 615 | + |
| 616 | + |
| 617 | +def kill_process_on_port(port): |
| 618 | + """Kill the process on the given port. |
| 619 | +
|
| 620 | + Args: |
| 621 | + port: The port. |
| 622 | + """ |
| 623 | + if get_process_on_port(port) is not None: |
| 624 | + get_process_on_port(port).kill() # type: ignore |
| 625 | + |
| 626 | + |
| 627 | +def terminate_port(port, _type): |
| 628 | + """Terminate the port. |
| 629 | +
|
| 630 | + Args: |
| 631 | + port: The port. |
| 632 | + _type: The type of the port. |
| 633 | + """ |
| 634 | + console.print( |
| 635 | + f"Something is already running on port [bold underline]{port}[/bold underline]. This is the port the {_type} runs on." |
| 636 | + ) |
| 637 | + frontend_action = Prompt.ask("Kill it?", choices=["y", "n"]) |
| 638 | + if frontend_action == "y": |
| 639 | + kill_process_on_port(port) |
| 640 | + else: |
| 641 | + console.print("Exiting...") |
| 642 | + sys.exit() |
599 | 643 |
|
600 | 644 |
|
601 | 645 | def run_backend(app_name: str, loglevel: constants.LogLevel = constants.LogLevel.ERROR):
|
|
0 commit comments