How can I get running process list using Python on Linux?
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).
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
...
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.
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()
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.