problem with global var
wes
oweston at earthlink.net
Thu Jan 3 09:45:56 EST 2008
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):
global topsquid
> 5 for i in range(50):
> 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]
> 12
> 13 while True:
> 14 logline = logfile.readline()
> 15 linefields = logline.split()
> 16
> 17 if logline != "":
> 18 add_sorted (linefields)
> 19 else:
> 20 break
> 21
> 22 for i in range (len(topsquid)):
> 23 print topsquid[i][4]
> ####################################
>
> 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:
>
> bruno at ts:~$ 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?
>
Try line 4 add.
More information about the Python-list
mailing list