Listing processes with Python

Alan Kennedy alanmk at hotmail.com
Thu May 22 16:27:51 EDT 2003


Matthew Knepley wrote:

> Is there a portable way to obtain a process list in Python?

You could try and parse the output of the (almost, but not quite)
portable "ps" command, using os.popen* methods: something along the
lines of 

#---------------
import os
import string
options = "al"
for line in os.popen("ps -%s" % options):
    fields = string.split(line, " \t")
    doStuffWithFields(fields)
#---------------

If you have cygwin installed, this could even work on win* (although I
can't find the option for listing all processes in cygwin->ps)

The option string is likely to need changing on other versions of *nix,
and the number and types of fields returned will very likely to be
different between different versions of *nix.

I suppose you could read the first line, which gives the column headers)
and parse it to tell you what data is each in field. Something along the
lines of (in python 2.3)

def parseHeaders(line):
    return [x for x in line.split()]

for ix, line in enumerate(os.popen("ps -%s" % options)):
    if ix == 0:
        colNames = parseHeaders(line)
        print "Columns: %s" % colNames
        print "#=-=-=-=-=-=-=-=-=-=-=-=-="
    else:
        fields = line.split()
        if len(fields) != len(colNames):
            raise "Received invalid number of fields on line '%s'" %
line
        else:
            for col, colName in enumerate(colNames):
                print "%s=%s" % (colName, fields[col])
            print "#=-=-=-=-=-=-=-=-=-=-=-=-="

Perhaps a solution that has a better chance of being portable, albeit
with a lot of tweaking and a lot of exceptional cases?

HTH,

-- 
alan kennedy
-----------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan:              http://xhaus.com/mailto/alan




More information about the Python-list mailing list