[ale] Help Processing a Log File

Joe Knapka jknapka at kneuro.net
Thu May 13 01:39:37 EDT 2004


I just had to present an alternative to Perl :-)

Here's a complete solution in Python. It will print the total pages
printed by each user, alphabetized by username.  It is doubtless a bit
more verbose than a complete Perl solution, at 29 lines including
whilespace and comments, but anyone with any programming experience at
all should be able to read and understand this, I think. It might help
to know that {} is an empty associative array, and string[n:m] picks
the part of a string between the nth and mth characters, where
negative numbers count backward from the end of the string. Another
slightly magical bit is commented in the code. Invoke "python
parselogs.py <fileToParse>".

--- File parselogs.py --
import sys

data = {}

def jobstart(words):
	global user
	user = words[2][3:-1]

def filestart(words):
	global start
	start = int(words[2][3:-1])

def fileend(words):
	global end
	end = int(words[4][3:-1])
	data[user] = data.get(user,0) + (end-start)

for line in open(sys.argv[1]).readlines():
	words = line.split()
	if len(words)>0:
		# If there's a global function named the same as the first word
		# on the line, call it with the line (as a list of words) as input.
		func = globals().get(words[0],None)
		if callable(func): func(words)

keys = data.keys()
keys.sort()
for key in keys:
	print key,"printed",data[key],"pages."
--- end ---

Cheers,

-- Joe

Jonathan Glass <jonathan.glass at ibb.gatech.edu> writes:

> I'm trying to parse a printer log file.  Here is a snippet of a single
> print job (I added the extra lines for legibility):

[snip]

-- 
Resist the feed.
--
If you really want to get my attention, send mail to
jknapka .at. kneuro .dot. net.



More information about the Ale mailing list