DEV Community

Alex Chen
Alex Chen

Posted on

Quick Tip: See Every Python Process Listening on a Port in 2 Commands

Quick Tip

You start a dev server. OSError: [Errno 98] Address already in use. You don't remember which of your 12 terminal tabs holds the port. Instead of guessing, run:

ss -tlnp | grep :8000
# LISTEN 0 2048 127.0.0.1:8000 0.0.0.0:* users:(("python",pid=4123,fd=3))
Enter fullscreen mode Exit fullscreen mode

PID 4123 owns it. Kill precisely:

kill $(ss -tlnp | grep -oP '(?<=pid=)\d+' | head -1)
Enter fullscreen mode Exit fullscreen mode

Or the one-liner I actually keep in my shell config:

killport() { kill $(ss -tlnp "sport = :$1" | grep -oP '(?<=pid=)\d+' | head -1); }
# usage: killport 8000
Enter fullscreen mode Exit fullscreen mode

Why ss and not lsof -i :8000? On my machine ss returns in ~5ms vs ~800ms for lsof (it scans every open file descriptor of every process). When you're restarting a dev server 40 times a day, that difference adds up to real minutes per week.

Bonus β€” see everything Python is currently serving:

ss -tlnp | grep python
Enter fullscreen mode Exit fullscreen mode

I draft snippets like this with MonkeyCode (free AI coding tool): https://ly.cyberserval.tech/iIETXiF

What's your go-to "where is that port" command β€” ss, lsof, fuser, or something else?

Top comments (0)