tags:

views:

266

answers:

5

How can I get running process list using Python on Linux?

+1  A: 

I would use the subprocess module to execute the command ps with appropriate options. By adding options you can modify which processes you see. Lot's of examples on subprocess on SO. This question answers how to parse the output of ps for example:)

You can, as one of the example answers showed also use the PSI module to access system information (such as the process table in this example).

extraneon
+1  A: 

In addition to the mentionend subprocess module, you could also use the commands module.

The commands module contains wrapper functions for os.popen() which take a system command as a string and return any output generated by the command and, optionally, the exit status.

import commands
pl = commands.getoutput("ps -U 0")
print pl
...
The MYYN
You shouldn't use the commands module. The subprocess module was made to replace the commands module, the os.popen calls, the popen modules and all of the other many forms of opening other processes. Thus you should never try to use the commands library as the module may be deprecated and removed in the future.
Matt
+4  A: 

You can use a third party library, such as PSI:

PSI is a Python package providing real-time access to processes and other miscellaneous system information such as architecture, boottime and filesystems. It has a pythonic API which is consistent accross all supported platforms but also exposes platform-specific details where desirable.

ars
+5  A: 

IMO looking at the /proc filesystem is less nasty than hacking the text output of ps.

pids= [pid for pid in os.listdir('/proc') if pid.isdigit()]

for pid in pids:
    print open(os.path.join('/proc', pid, 'cmdline'), 'rb').read()
bobince
+1 for /proc, that's what it's there for. http://linux.die.net/man/5/proc
orip
A: 

The sanctioned way of creating and using child processes is through the subprocess module.

import subprocess
pl = subprocess.Popen(['ps', '-U', '0'], stdout=subprocess.PIPE).communicate()[0]
print pl

The command is broken down into a python list of arguments so that it does not need to be run in a shell (By default the subprocess.Popen does not use any kind of a shell environment it just execs it). Because of this we cant simply supply 'ps -U 0' to Popen.

Matt