DEV Community

Niuniu Ox
Niuniu Ox

Posted on

Quick Tip: Kill a Runaway Python Process by Port in 3 Lines (No Task Manager)

Quick Tip

Every dev has hit this: you restart your dev server and get Address already in use. Something is squatting on port 8000 and lsof -i :8000 never sticks in my memory.

With psutil it's three lines and it works the same on macOS, Linux, and Windows:

import psutil

for conn in psutil.net_connections(kind="inet"):
    if conn.laddr.port == 8000 and conn.status == "LISTEN":
        print(f"PID {conn.pid} is holding :8000")
        psutil.Process(conn.pid).terminate()
Enter fullscreen mode Exit fullscreen mode

No shell piping, no grep, no remembering whether this machine has lsof, netstat, or ss. Install with pip install psutil (that's the whole dependency tree).

I keep this as a killport.py in my dotfiles. Run it, port's free, dev server starts. I timed it against my usual lsof | grep | awk | kill dance — 4 seconds vs ~30 seconds of fumbling, every single time.

I sketched the snippet with an AI coding assistant (MonkeyCode, free tier: https://ly.cyberserval.tech/iIETXiF) and it nailed the net_connections API on the first try — including the Windows edge case where conn.pid can be None for system sockets.

What's the one tiny utility script you keep in your dotfiles that you'd fight someone over?

Top comments (0)