[Tutor] Search text file, perform action if a given item found in file

Kent Johnson kent_johnson at skillsoft.com
Mon Sep 13 11:57:19 CEST 2004


Eric,

It's a difference between netstat on Windows and FreeBSD. The windows 
version includes a few header lines that don't split the way you expect - 
the resulting list doesn't have two elements:
 >>> import os
 >>> f=os.popen('netstat -an')
 >>> for l in f:
...   print len(l.split())
...
0
2
0
6
4
4
etc...

You could check the length of the split before you do further processing, 
or you could catch the exception and continue the loop.

Kent

At 02:55 AM 9/13/2004 -0400, Eric wrote:
>Ok, I'm still trying to figure this out..
>
>This is on Windows XP computer with Python version 2.3.4
>
> >>> import os
> >>> o=os.popen("netstat -an")
> >>> for l in o:
>    print l.split()[1]
>
>
>Traceback (most recent call last):
>  File "<pyshell#173>", line 2, in -toplevel-
>    print l.split()[1]
>IndexError: list index out of range
>
>
>
>And this is the same series of commands on a FreeBSD computer running 
>Python version 2.2.2
>
>
> >>> import os
> >>> o=os.popen("netstat -an")
> >>> for l in o:
>...     print l.split()[1]
>...
>Internet
>Recv-Q
>0
>0
>0
>0
>0
>0
>0
>0
>0
>0
>0
>0
>UNIX
>Type
>stream
>stream
>stream
>stream
>stream
>stream
>dgram
>dgram
>dgram
>dgram
>dgram
>
>
>
>So it seems to be working with a older version of python but not the newer 
>version? Is this a bug? If so that would explain
>why I have been having so many problems with this.
>
>
>Kent Johnson wrote:
>
>>Eric,
>>
>>l.split()[1:2] gives a list containing a string, rather than a bare 
>>string, so endswith() won't work on it. You should use l.split()[1] instead:
>> >>> l='a  b c'
>> >>> l.split()
>>['a', 'b', 'c']
>> >>> l.split()[1:2]
>>['b']
>>
>>That is a list containing a string so endswith won't work
>> >>> l.split()[1:2].endswith('b')
>>Traceback (most recent call last):
>>   File "<stdin>", line 1, in ?
>>AttributeError: 'list' object has no attribute 'endswith'
>> >>> l.split()[1]
>>'b'
>>
>>Now it's just a string and split works fine
>> >>> l.split()[1].endswith('b')
>>True
>>
>>Then you will need a string containing the port number preceded by a 
>>colon. You can do this with ':' + str(port)
>>
>>Finally, put an if statement inside your loop to test for the port string 
>>and do something with it. Brian's post shows how to do that.
>>
>>Kent
>
>



More information about the Tutor mailing list