"len()" gives a curious error

Mike McKernan mck at pobox.com
Wed Mar 5 21:25:04 CET 2003


Hi List,

I am an admirer of Python, but only an occasional user, so I may
easily be overlooking something.  Here's the story.

I just wrote a quicky script to convert ip address ranges in the
masked form (192.168.231.64/23 e.g.) to the first address - last
address form (192.168.230.0 - 192.168.231.255), which worked fine
until I added a few checks.  

The check that's bothering me is trying to confirm that there are
exactly four elements in the dotted quad address.  This line should
produce a list of the individual elements:

        addr = string.split(addr,".")

and     print type(addr)

does indeed produce <type 'list'>

but     print len(addr)

gives the following:

        Traceback (most recent call last):
          File "/u/mck/bin/ipaddr", line 27, in ?
            print len(addr)
        TypeError: 'str' object is not callable

Curiously, everything works as expected if I run interactively.

What's going on?

I am running Python-2.2.2 on Mandrake 9.0.

Thanks,

Mike



This is (a debugging version of) the script.


#!/usr/bin/python

import getopt, sys, string, os

def usage() :
    print('usage: %s nnn.nnn.nnn.nnn/mm' % (os.path.basename(sys.argv[0])))
    print('       where nnn.nnn.nnn.nnn is the base IP Address')
    print('       and mm is the length of the bit mask for the')
    print('       fixed part of the address range.')
    sys.exit(1)

try:
    opts, args = getopt.getopt(sys.argv[1:], "")
except getopt.GetoptError:
    usage()

#try :

# temporarily unindented

addr, len = string.split(args[0],"/")
addr = string.split(addr,".")

# debugging prints

print type(addr)
print len(addr)

# a check for the right number of elements would go here

addr = int(addr[0])<<24 | int(addr[1])<<16 | int(addr[2])<<8 | int(addr[3])
mask = 0xFFFFFFFF << 32-int(len)
#except :
#    usage()

low = addr & mask
high = addr | ~mask

low_addr = low>>24&0xFF, low>>16&0xFF, low>>8&0xFF, low&0xFF
high_addr = high>>24&0xFF, high>>16&0xFF, high>>8&0xFF, high&0xFF

print('%d.%d.%d.%d - %d.%d.%d.%d' %
      (low_addr[0],  low_addr[1],  low_addr[2],  low_addr[3],
       high_addr[0], high_addr[1], high_addr[2], high_addr[3]))





More information about the Python-list mailing list