Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 521
Aaron Avatar asked May 31 '10 00:05

Aaron


People also ask

How do you kill a process with its name?

Kill process by name with killall and pkill First, killall accepts a process name as an argument rather than PID. And the other difference is that killall will, as the name implies, kill all instances of a named process. Contrast this to the regular kill command which only ends the processes you explicitly specify.


2 Answers

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() 
like image 196
Giampaolo Rodolà Avatar answered Oct 25 '22 04:10

Giampaolo Rodolà


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.

like image 44
Alex Martelli Avatar answered Oct 25 '22 04:10

Alex Martelli