Programmatically Getting Process ID

Jarkko Torppa torppa at polykoira.megabaud.fi
Fri Mar 3 20:34:40 EST 2000


In article <slrn8c0lob.i2l.kc5tja at garnet.armored.net>, Samuel A. Falvo II wrote:
>In article <89pi3n$8lc$1 at nnrp1.deja.com>, Hernan M. Foffani wrote:
>>The portable way to do it (in UN*X, I mean) is to run a script and get
>>the output (via pipes), something like:
>
>That's bloody insane.  There's no way to iterate through the list of running
>processes and query them for name and ID?
...
>Thanks for the information.  It seems that I have absolutely no way to
>handle this except to use an exorbitantly expensive operation to determine
>the PID of a running process... :(
>
>(How the heck does PS get its process listing anyway?)

Very unportably, usally it either grovels thru kernel-memory (/dev/kmem),
or /proc mountpoint. On my system there are man-pages
kvm(3) and mount_procfs(8) where you can find about those methods.

procfs method is trivial to implement in python.

>>> import os,string
>>> r = []
>>> for d in os.listdir('/proc'):
...     name,pid=string.split(open('%s/status' % d).read())[:2]
...     r.append((name,int(pid)))
... 
>>> r
[('python', 3312), ('cpp', 7155),...,('init', 1), ('swapper', 0)]

-- 
 Jarkko Torppa                torppa at staff.megabaud.fi
  Megabaud Internet-palvelut



More information about the Python-list mailing list