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.
he said he would filter and then kill
Umair Ahmed
2009-07-07 09:55:17
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
2009-07-07 09:57:39
because I need to match up the processes with other data.
Johan Carlsson
2009-07-07 11:29:33
+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
2009-07-07 10:01:45
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
2009-07-07 11:32:46
Huh, this is interesting. It's worth a question on its own: http://stackoverflow.com/questions/1098257
krawyoti
2009-07-08 13:59:01
+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
2009-07-07 10:02:17