Programmatically Getting Process ID

Justin Sheehy dworkin at ccs.neu.edu
Fri Mar 3 20:13:32 EST 2000


kc5tja at garnet.armored.net (Samuel A. Falvo II) writes:

> That's bloody insane.  There's no way to iterate through the list of running
> processes and query them for name and ID?

Nothing that is even close to portable.  There are alternatives to ps, 
though.  For instance, if you have a procfs on your machine, the
information in there may be quite useful.

A quick example, just off the top of my head:

import os.path, string, glob

def pid(name):
    procfs = '/proc/'
    for i in glob.glob(procfs + '[0-9]*'):
        if string.find(open(os.path.join(i, 'cmdline')).read(), name) != -1:
            return int(os.path.basename(i))
    raise 'No such process.'

>>> pid('inetd')
168

>From my UNIX shell:

bash$ cat /proc/168/cmdline 
inetd

Of course, this is far from portable (and probably buggy besides).  I
just find procfs a bit friendlier than ps.

-Justin

 




More information about the Python-list mailing list