Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Sat Sep 09 2023

Kill processes based on ports in Python

In this short guide, I will share some code that we can use to automatically kill processes based on their port number, using Python.

When developing applications with a lot of services, we might end up in situations where port numbers are already taken when we rerun our code or if some process is not fully terminated etc. Having a neat little script that we can execute might be a good companion in these situations so we don't have to manually do it from the terminal. So today, I will share some code in Python that we can run for terminating the processes, based on the port numbers.

The logic

The logic we will follow, is basically finding the PID and then take it and kill it. The commands we will use are:

lsof -i tcp:{port}
kill -9 {PID}

We will make the script accept an array of ports so we can kill multiple processes.

Create process-killer.py file

We will create a Python file, and add following code:

import os import signal from subprocess import Popen, PIPE ports = [9000, 9001, 9002, 9003, 9004, 9005, 9006] for port in ports: process = Popen(["lsof", "-i", "tcp:{0}".format(port)], stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate() for process in str(stdout.decode("utf-8")).split("\n")[1:]: data = [x for x in process.split(" ") if x != ''] if (len(data) <= 1): continue os.kill(int(data[1]), signal.SIGKILL) print("Killed PID:{0} on port :{1}".format(data[1], port))

Run the script

To run the script, simply call it in the terminal like:

python3 process-killer.py

Output

And in the terminal, you should see something like below:

Killed PID:32747 on port :9000 Killed PID:32743 on port :9001 Killed PID:32741 on port :9002 Killed PID:32767 on port :9003 Killed PID:32748 on port :9004 Killed PID:32766 on port :9005 Killed PID:32749 on port :9006

Summary

In this short guide, we created a script that could be used as an assistant in our development when working with a lot of processes locally. I hope this helped, and thanks for reading!

All the best,

signatureSat Sep 09 2023
See all our articles