getting a process's PID

eldorado eldorado at io.com
Wed Dec 27 15:05:16 EST 2006


On Wed, 27 Dec 2006, Sebastian 'lunar' Wiesner wrote:

> eldorado <eldorado at io.com> typed
>
>> Hello,
>>
>> I am trying to get python to give me the PID of a process (in this
>> case
>> HUB).  I have it working, except for the fact that the output includes
>> \012 (newline).  Is there a way to ask python not to give me a
>> newline?
>>
>> Python 1.4 (Oct 14 1997) [C]
>> Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>>>> import os
>>>>> g = os.popen("ps -ef | grep HUB | grep -v grep | awk '{ print $2
>>>>> }'") h = g.readlines()
>>>>> g.close()
>>>>> h
>> ['87334\012']
>>
>> Thanks in advanced for any guidance.
>
> Well, you could do everything in python itself, without using grep and
> awk at all:
>
>>>>> g = os.popen("ps -e -o pid,command")
>>>>> for line in g.readlines():
>>>>>     if 'HUB' in line:
>>>>>         pid = line.strip().split(' ')[0]
>>>>>         break
>>>>> print pid
>

This looks cleaner than the way I was going.  I created a file 
called ps.py

#!/usr/local/bin/python
import os
g = os.popen("ps -e -o pid,command")
for line in g.readlines():
         if 'HUB' in line:
                 pid = line.strip().split(' ')[0]
                 break
print pid

When I run ps.py I get the following error.

Traceback (innermost last):
   File "./ps.py", line 5, in ?
     if 'HUB' in line:
TypeError: string member test needs char left operand

I googled this error, but wasn't smart enough to figure out exactly what 
it means.

-- 
Randomly generated signature
On the other hand, the early worm gets eaten.



More information about the Python-list mailing list