[Tutor] For loop question

w chun wescpy at gmail.com
Wed May 10 09:25:17 CEST 2006


> Been trying to understand why the following doesn't work:
>
> HostFile = open("hosts.txt", 'r')
> host = HostFile.readlines()
>
> for item in host:
>     print "Connecting to device",item
>     tn = telnetlib.Telnet(item)
>        :
>   File "c:\gideon\python24\lib\telnetlib.py", line 225, in open
>     for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
> socket.gaierror: (11001, 'getaddrinfo failed')
>
> Can't
> understand why I can't pass "item" as a string to the telnetlib.Telnet
> command.


hi gideon,

welcome to Python!  your program is very close to working.  without
actually being where you are, i'm going to try to figure out the
problem:

the error socket.gaierror means that it cannot find the address
information for the host you passed it.  because you are reading in
the hostnames from a file, my guess is that the trailing line
separators (NEWLINE [\n] for Unix-based machines and carriage RETURN
followed by NEWLINE [\r\n] on Win32 hosts) is being considered as part
of the hostname. Python does not strip the trailing line separators
for you (which is useful if you need to write the same strings out to
another file).

i would do something like: item = item.strip()
before creating the telnet session... that should help.

another thing is that if the host file is large, you may wish to
iterate through the file one line at a time with a list comprehension
to do the stripping for you:

HostFile = open("hosts.txt", 'r')
for item in [x.strip() for x in HostFile]:
        :

if you are using Python 2.4+, you can come up with an even better
solution by using a generator expression that does lazier, ad hoc
evaluation:

HostFile = open("hosts.txt", 'r')
for item in (x.strip() for x in HostFile):
        :

this one will read and strip one line from the file as you process it
while the previous solution still needs to come up with the entire
list of stripped hosts before the for-loop can begin.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list