How to kill a process using process name in python script
Asked Answered
B

2

6

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.

Beatup answered 22/1, 2021 at 13:34 Comment(0)
I
8

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()
Instil answered 22/1, 2021 at 13:58 Comment(0)
H
2

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)
Hoyt answered 22/1, 2021 at 15:35 Comment(1)
pgrep and pkill are more specialized commands dealing with this than parsing ps ax and the OP specifically requested a platform-agnostic solution while this is Linux/macOS.Girish

© 2022 - 2024 — McMap. All rights reserved.