Bruno Ferreira wrote:
> Hi,
> 
> I wrote a very simple python program to generate a sorted list of
> lines from a squid access log file.
> 
> Here is a simplified version:
> 
> ##################################
> 1  logfile = open ("squid_access.log", "r")
> 2  topsquid = [["0", "0", "0", "0", "0", "0", "0"]]
> 3
> 4  def add_sorted (list):

Don't call your variable "list". There's already the built-in type "list".

> 5     for i in range(50):

You should probably use xrange here.

> 6          if int(list[4]) > int(topsquid[i][4]):
> 7              topsquid.insert(i,list)
> 8              break
> 8      # Max len = 50
> 10     if len(topsquid) > 50:
> 11         topsquid = topsquid[0:50]

I'd just use "[:50]", the 0 is implied.

> 13 while True:
> 14     logline = logfile.readline()
> 15     linefields = logline.split()
> 16
> 17     if logline != "":
> 18         add_sorted (linefields)
> 19     else:
> 20         break

for logline in logfile:
    if logline:
        linefields = logline.split()
        add_sorted(linefields)
    else:
        break

> 22 for i in range (len(topsquid)):
> 23     print topsquid[i][4]

for i in topsquid:
    print i[4]

(You probably want to use a name other than "i" then.)

> ####################################
>
> When I execute the program _without_ the lines 10 and 11:
> 
> 10     if len(topsquid) > 50:
> 11         topsquid = topsquid[0:50]
> 
> it runs perfectly.
> 
> But if I execute the program _with_ those lines, this exception is thrown:
> 
> [EMAIL PROTECTED]:~$ python topsquid.py
> Traceback (most recent call last):
>   File "topsquid.py", line 20, in <module>
>     add_sorted (linefields)
>   File "topsquid.py", line 6, in add_sorted
>     if int(list[4]) > int(topsquid[i][4]):
> UnboundLocalError: local variable 'topsquid' referenced before assignment
> 
> 
> Note that now the error shown is not related with the lines 10 and 11,
> but wiht a line prior to them.
> 
> Any hints?

Basically, you're trying to read the global variable "topsquid", and
then you're trying to define a local variable "topsquid". Python doesn't
like that. Declare it as global by adding "global topsquid" to the top
of the function.
-- 
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to