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

Eric eric at digitalert.net
Mon Sep 13 08:55:25 CEST 2004


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