Kill process by name?

Aaron picture Aaron · May 31, 2010 · Viewed 218.5k times · Source

I'm trying to kill a process (specifically iChat). On the command line, I use these commands:

ps -A | grep iChat 

Then:

kill -9 PID

However, I'm not exactly sure how to translate these commands over to Python.

Answer

Giampaolo Rodolà picture Giampaolo Rodolà · Nov 20, 2010

psutil can find process by name and kill it:

import psutil

PROCNAME = "python.exe"

for proc in psutil.process_iter():
    # check whether the process name matches
    if proc.name() == PROCNAME:
        proc.kill()