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.
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()
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With