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):
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@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?
--
Bruno A. C. Ferreira
Linux Registered User #181386 5 1231
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@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.
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):
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@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?
Use
def add_sorted(list):
global topsquid
...
to make topsquid a global variable to add_sorted. Otherwise python sees that
it gets referred by in the if-statement before assigning to it, thus
resulting in the error you see.
The reason for this is that a (limited) static analysis of python-code is
performed to determine which variables are local to a function and which
not. The criteria essentially is the appearance on the left-hand-side of an
expression makes a variable (or name) local to that function. Which makes
it require the explicit global declaration.
Apart from that there are quite a few things worth mentioning in your code:
- don't shadow built-in names like list
- it's superfluous to do
for i in xrange(len(some_list)):
.. some_list[i] ..
as you do, unless you need the index. Instead do
for element in some_list:
... element ...
If you need an index, do
for i, element in enumerate(some_list):
...
- don't use range, use xrange if you don't need a list but rather
want to enumerate indices.
- the while-loop is superfluous as well, just do
for line in logfile:
...
or if your python is older do
for line in logfile.xreadlines():
...
Diez
On Thu, 03 Jan 2008 11:38:48 -0300, 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"]]
[snip]
Others have already solved the immediate problem, but a much better
design would be to avoid using a global variable in the first place.
def add_sorted(alist, data):
"""Add figures from alist to collated data and return data."""
# do your processing here...
return data
topsquid=[["0", "0", "0", "0", "0", "0", "0"]]
for line in logfile:
linefields = logline.split()
topsquid = add_sorted(linefields, topsquid)
--
Steven
Bruno Ferreira wrote:
I wrote a very simple python program to generate a sorted list of
lines from a squid access log file.
Now that your immediate problem is solved it's time to look at the heapq
module. It solves the problem of finding the N largest items in a list
much more efficiently. I think the following does the same as your code:
import heapq
def key(record):
return int(record[4])
logfile = open("squid_access.log", "r")
records = (line.split() for line in logfile)
topsquid = heapq.nlargest(50, records, key=key)
for record in topsquid:
print record[4]
Peter
Hello all,
Amazing :)
The program is working properly now, the code is much better and I
learned a bit more Python.
Thank you all, guys.
Bruno.
2008/1/4, Peter Otten <__*******@web.de>:
Bruno Ferreira wrote:
I wrote a very simple python program to generate a sorted list of
lines from a squid access log file.
Now that your immediate problem is solved it's time to look at the heapq
module. It solves the problem of finding the N largest items in a list
much more efficiently. I think the following does the same as your code:
import heapq
def key(record):
return int(record[4])
logfile = open("squid_access.log", "r")
records = (line.split() for line in logfile)
topsquid = heapq.nlargest(50, records, key=key)
for record in topsquid:
print record[4]
Peter
-- http://mail.python.org/mailman/listinfo/python-list This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Bartosz Wegrzyn |
last post by:
I need help with sessions.
I createt set of web site for nav with authorization.
first I go into main.php which looks like this:
<?php
//common functions
include_once '../login/common.php';...
|
by: Spur |
last post by:
Hi all,
I implemented a memory allocation/deallocation class that logs all
new/delete calls (overloaded) and remembers for each allocated
block where it was allocated from (using a macro that...
|
by: Steven Fox |
last post by:
============================================================
About DB2 Administration Tools Environment
============================================================
DB2 administration tools level:...
|
by: zubair |
last post by:
Hello everyone!
I have uploaded my site on a webserver. Some times it works fine but some
time it gives error "Null Object reference exception".
The same site on my local server works just fine.
...
|
by: Ankit Aneja |
last post by:
I put the code for url rewrite in my Application_BeginRequest on global.ascx
some .aspx pages are in root ,some in folder named admin and some in folder
named user
aspx pages which are in user...
|
by: Ron |
last post by:
I have a web project compiled with the new "Web Deployment Projects" plugin
for VS2005.
I'm deploying the web project to one assembly and with updateable option set
to ON.
When I'm running the...
|
by: Babak |
last post by:
Hi Everyone,
I've written a standard C code for a simple finite element analysis
in MSVC++ . When I save the file as a cpp file, it compiles and runs
perfectly, but when I save it as a c file,...
|
by: Florian Lindner |
last post by:
Hello,
I have a little problem with the global statement.
def executeSQL(sql, *args):
try:
import pdb; pdb.set_trace()
cursor = db.cursor() # db is <type 'NoneType'>.
except:
print...
|
by: Royan |
last post by:
Ok the problem is quite hard to explain, but i'll try to keep it as
simple as i can. Imagine I have the following structure of my files
and folders:
/root/global.inc
|__/files/foo.php...
|
by: Brock |
last post by:
Thanks in advance... (you can see a screenshot of what my form looks
like currently at http://www.juggernautical.com/DataGrid.jpg - the
Datalist is super-imposed in 'design view' but the DataGrid...
|
by: DJRhino |
last post by:
Was curious if anyone else was having this same issue or not....
I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM)
The start time is equivalent to 19:00 (7PM) in Central...
|
by: tracyyun |
last post by:
Hello everyone,
I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
|
by: giovanniandrean |
last post by:
The energy model is structured as follows and uses excel sheets to give input data:
1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
|
by: NeoPa |
last post by:
Introduction
For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
|
by: Teri B |
last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course.
0ne-to-many. One course many roles.
Then I created a report based on the Course form and...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM)
Please note that the UK and Europe revert to winter time on...
|
by: NeoPa |
last post by:
Introduction
For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
|
by: GKJR |
last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...
| |