How to get the active process list on a Linux machine using python

To retrieve the active process list on a Linux machine we will use the subprocess module . This module will allow us to create new subprocesses, connect to their input / output / error pipes, and eventually retrieve their exit codes .

It offers us a higher level and cleaner approach by defining only one class: subprocess.Popen(), intended to replace the functionality offered by methods such as: os.system(), os.popen() or os.popen2() .

To obtain the active processes and their associated information (USER, PID, CPU, MEM, TTY, STAT, TIME, COMMAND, etc.) we will spawn a ps aux subprocess, connect to its output pipe and parse the results .

But first let’s analyze a little the output of ps aux :

Our first step will be to create a data structure capable of encapsulating the above information . We will write the Proc class that will wrap all the process meta-information present in the ‘ps aux‘ output :

A list of Proc objects will probably do the job . Now let’s see how we are going to create the list:

And to test the above function:

The output may look like:

And putting all togheter (full source of the example):

4 thoughts to “How to get the active process list on a Linux machine using python”

  1. proc_info = split(” *”, line.strip())

    This LOC throws the following error which looks like a legacy bug in python-

    File “/usr/local/lib/python2.7/”, line 167, in split
    return _compile(pattern, flags).split(string, maxsplit)
    TypeError: expected string or buffer

  2. In your give code:

    #Discard the first line (ps aux header)
    how does it Discard the first line (ps aux header)?

Leave a Reply

Your email address will not be published. Required fields are marked *

Are we human, or are we dancer *