I'm currently using pyinotify to monitor an irssi (irc client for linux command line) log file, and this log file is written to by irssi using the IN_MODIFY mask from pyinotify, it reads the file just fine, and is told every time when its changed, but I'm trying to find a specific phrase in a line, in this line the phrase is:
COMPLETE:
Now i have code that checks the last line to see if its there, but irssi writes to the logfile in chunks sometimes because things come in all at once due to it being a bot readout. This code works fine, what I'm having problems with is finding the last line closest to the bottom with the COMPLETE: phrase in it.
I know I'm probably doing it wrong but the way I've come up with(and it doesn't work, so i am doing it wrong) is to save the last COMPLETE: line and search for that line and for loop enumerate over the file with an offset of the line number the last line is found at and process each complete line after that. Below is the code, if anyone has any ideas, or perhaps a better way of doing this, it would be greatly appreciated!
def getlastline(self):
logfile = "/home/user/irclogs/kta/#kta-all.log"
with open(logfile, "rb") as f:
if self.lastline != "":
#This part doesn't work.
thenum = 0
for num, line in enumerate(f, 1):
if line == self.lastline:
thenum = num
if thenum == 0:
return
for i, ln in enumerate(f, thenum):
if ln.find("COMPLETE:") > 0:
self.setlast(ln)
self.extractdata(ln)
return
else:
#This part here works
first = f.readline()
f.seek(-2, 2)
while f.read(1) != "\n":
f.seek(-2, 1)
last = f.readline()
if last.find("COMPLETE:") > 0:
self.setlast(last)
self.extractdata(last)
else:
#This part doesn't work
for line in reversed(f.readlines()):
if line.find("COMPLETE:") > 0:
self.setlast(line)
return
Edit:
self.extractdata is a function to regex out certain parts of the line i'm getting, the line is sent to self.extractdata from the getlastline function, and self.setlast merely sets self.lastline and print's something for testing.
def __init__(self):
self.lastline = ""
def setlast(self, line):
self.lastline = line
print "Next-Newest complete line found."