Skip to content
Advertisement

Kill process by name?

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.

Advertisement

Answer

Assuming you’re on a Unix-like platform (so that ps -A exists),

>>> import subprocess, signal
>>> import os
>>> p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
>>> out, err = p.communicate()

gives you ps -A‘s output in the out variable (a string). You can break it down into lines and loop on them…:

>>> for line in out.splitlines():
...   if 'iChat' in line:
...     pid = int(line.split(None, 1)[0])
...     os.kill(pid, signal.SIGKILL)
... 

(you could avoid importing signal, and use 9 instead of signal.SIGKILL, but I just don’t particularly like that style, so I’d rather used the named constant this way).

Of course you could do much more sophisticated processing on these lines, but this mimics what you’re doing in shell.

If what you’re after is avoiding ps, that’s hard to do across different Unix-like systems (ps is their common API to get a process list, in a sense). But if you have a specific Unix-like system in mind, only (not requiring any cross-platform portability), it may be possible; in particular, on Linux, the /proc pseudo-filesystem is very helpful. But you’ll need to clarify your exact requirements before we can help on this latter part.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement