views:

295

answers:

3
+1  Q: 

Processlist

How do I get a process list of all running processes from Python, on Unix, containing then name of the command/process and process id, so I can filter and kill processes.

A: 

Why Python?
You can directly use killall on the process name.

nik
he said he would filter and then kill
Umair Ahmed
Good observation, but why filter the `ps` output for the command name, gather process id values and then kill, when the `killall` does it for you?
nik
because I need to match up the processes with other data.
Johan Carlsson
+2  A: 

On linux, the easiest solution is probably to use the external ps command:

>>> import os
>>> data = [(int(p), c) for p, c in [x.rstrip('\n').split(' ', 1) \
...        for x in os.popen('ps h -eo pid:1,command')]]

On other systems you might have to change the options to ps.

Still, you might want to run man on pgrep and pkill.

krawyoti
pgrep/pkill looks like a good solution for what I need (at least this time).I've always missed a built in ps function in Python, so that's part of the reason I posted this question. Cheers
Johan Carlsson
os.popen is deprecated. Use the subprocess module.
nosklo
Huh, this is interesting. It's worth a question on its own: http://stackoverflow.com/questions/1098257
krawyoti
+2  A: 

On Linux, with a suitably recent Python which includes the subprocess module:

from subprocess import Popen, PIPE

process = Popen(['ps', '-eo' ,'pid,args'], stdout=PIPE, stderr=PIPE)
stdout, notused = process.communicate()
for line in stdout.splitlines():
    pid, cmdline = line.split(' ', 1)
    #Do whatever filtering and processing is needed

You may need to tweak the ps command slightly depending on your exact needs.

Vinay Sajip