Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill all processes of a Python program?

I am running a Python program service_host.py, which started multiple processes. And when I use ps -ef | grep python

to check the pids, it shows a lot:

congmin  26968 22897  0 Jun20 ?        00:00:00 python service_host.py
congmin  26969 22897  0 Jun20 ?        00:00:00 python service_host.py
congmin  26970 22897  0 Jun20 ?        00:00:00 python service_host.py
congmin  26971 22897  0 Jun20 ?        00:00:00 python service_host.py
congmin  26972 22897  0 Jun20 ?        00:00:00 python service_host.py
congmin  26973 22897  0 Jun20 ?        00:00:00 python service_host.py
congmin  26974 22897  0 Jun20 ?        00:00:00 python service_host.py
congmin  26975 22897  0 Jun20 ?        00:00:00 python service_host.py

What's the best way to kill all these processes at once? I am on Linux and don't want to kill one by one through the process ID. Is there a way to kill them by the Python name 'service_host.py'? I tried this but it didn't kill at all:

import psutil

PROCNAME = "service_host.py"

for proc in psutil.process_iter():
    # check whether the process name matches
    if proc.name() == PROCNAME:
        proc.kill()

Is there a terminal command that can do this job easily?

like image 490
marlon Avatar asked Aug 24 '26 23:08

marlon


1 Answers

Linux has command pkill to kill by name

pkill python

exact matching

pkill -e 'python service_host.py'

check in full name

pkill -f 'service_host.py'

More in man pkill

BTW: There is also pgrep to get PIDs using names.

like image 115
furas Avatar answered Aug 26 '26 12:08

furas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!