Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a process using process name in python script

My requirement is to kill a process. I have the process name. Below is my code:

def kill_process(name):
  os.system(f"TASKKILL /F /IM {name}")

It works for Windows but not for Mac. My requirement is that it should work for both the OS. Is there a way to make the above code OS independent or how can I code it for Mac?

Any help is appreciated. Thank you.

Regards, Rushikesh Kadam.

like image 909
rushikesh Avatar asked Dec 31 '22 17:12

rushikesh


2 Answers

psutil supports a number of platforms (including Windows and Mac).

The following solution should fit the requirement:

import psutil

def kill_process(name):
    for proc in psutil.process_iter():
        if proc.name() == name:
            proc.kill()
like image 99
Jea Avatar answered Jan 02 '23 07:01

Jea


You can try this

import os, signal

def kill_process(name):
    for line in os.popen("ps ax | grep " + name + " | grep -v grep"):
        fields = line.split()
        pid = fields[0]
        os.kill(int(pid), signal.SIGKILL)
like image 42
Shehan Jayalath Avatar answered Jan 02 '23 07:01

Shehan Jayalath