getting a process's PID

Erik Johnson ejatwellkeeperdotcom
Wed Dec 27 12:59:50 EST 2006


"eldorado" <eldorado at io.com> wrote in message
news:20061227113158.J21223 at eris.io.com...

> >>> g = os.popen("ps -ef | grep HUB | grep -v grep | awk '{ print $2 }'")
> >>> h = g.readlines()
> >>> g.close()
> >>> h
> ['87334\012']
> >>> h = h[:-1]
> >>> h
> []

Oh, sorry... h is a list here because you are using readlines().
I am used to doing this:

fd = os.popen('ps -ef | grep python')
s = fd.read()

to get a single string. You can do something like

s = h[0]

and then operate on s, or you can use read() in place of readlines() to get
h as a single string, or you can operate on the first element of h:

>>> h = ['87334\012']
>>> h[0][:-1]
'87334'
>>> h[0].rstrip('\n')
'87334'

 All the error handling to do in the case where you actually have multiple
processes being matched is up to you. ;)

-ej





More information about the Python-list mailing list