Search code examples
pythonpython-3.xpython-sockets

Python - How to close a port left open?


I have a process which at times is opening a port and then not closing it (I'm on Windows 10).

What is the best way to close this via Python? The port number is 1300 and will not change.

I know this can be done manually via command line by killing the PID, however I would like to keep it all in one easy to use batch file.


Solution

  • You can use the psutil module.

    from psutil import process_iter
    from signal import SIGKILL # Unix-only enum
    
    for proc in process_iter():
        for conn in proc.net_connections(kind='inet'):
            if conn.laddr[1] == 1300:
                proc.send_signal(SIGKILL) 
                continue
    

    Otherwise, you should just call kill from subprocess.