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.

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.