如何在python脚本中使用进程名称杀死进程
我的要求是杀死一个进程。我有进程名称。下面是我的代码:
def kill_process(name):
os.system(f"TASKKILL /F /IM {name}")
它适用于 Windows,但不适用于 Mac。我的要求是它应该适用于两个操作系统。有没有办法使上述代码独立于操作系统,或者如何为 Mac 编码?
任何帮助表示赞赏。谢谢你。
问候,拉什凯什·卡达姆。
回答
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()