views:

78

answers:

5

Hello, I'm trying to kill a process (specifically iChat) using python. I know how to use the command:

ps -A | grep iChat 

Then:

kill -9 PID

However, I'm not exactly sure how to translate these commands over to python. My guess is that it's not very difficult but I just don't know. Any help would be greatly appreciated!

+2  A: 

If you have killall:

os.system("killall -9 iChat");

Or:

os.system("ps -C iChat -o pid=|xargs kill -9")
Matthew Flaschen
There's also `pkill`, although I think I'm the only person in the world that uses it instead of `killall`
Michael Mrozek
Ok cool, yea it looks like the first command worked perfect. Thanks for the help.
Aaron
A: 

you can those exact commands from python like this

import os 
print os.system('kill -9 ' + pid)

But your command on getting the pid needs a bit of work though (can't just assume just because it has iChat that it really is iChat) you should use killall instead as suggested by Matthew Flaschen

hhafez
+2  A: 

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

>>> import subprocess, signal
>>> 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.

Alex Martelli
That worked very well! I'm running a Mac environment so I think this will be perfect. Thank you for all your help.
Aaron
@Aaron, you're welcome!
Alex Martelli
A: 

You can use pkill <process_name> in a unix system to kill process by name.

Then the python code will be:

>>> import os
>>> process_name=iChat
>>> os.system('pkill '+process_name)
xaph
All the the systems I'm using are Mac and when I try to run pkill it's just telling me that the command cannot be found.
Aaron
A: 

you can use WMI module to do this on windows, though it's a lot clunkier than you unix folks are used to; import WMI takes a long time and there's intermediate pain to get at the process.

amwinter