Tailing a log file?
Falcolas
garrickp at gmail.com
Fri Jun 22 15:01:13 EDT 2007
On Jun 22, 12:50 pm, "Kenji Noguchi" <tokyo... at gmail.com> wrote:
> > I checked the source code for tail and they actually poll the file by
> > using fstat and sleep to check for changes in the file size. This
> > didn't seem right so I thought about it more and realized I ought to
> > be using inotify. So I guess I answered my own question.
I built something which worked on the "check stat and sleep" method.
Using notify or select may work, but it's not portible to Windows
systems, which may or may not be an issue for you.
#! /usr/bin/env python
import os
import sys
import time
from stat import *
class Watchfile(object):
def __init__(self, f_loc):
self.file_loc = f_loc
self.prev_lm = 0
self.last_read_pos = 0
f = open(self.file_loc, "r")
for l in f:
pass
self.last_read_pos = f.tell()
f.close()
self.prev_lm = os.stat(self.file_loc)[ST_MTIME]
def changed(self):
lm_time = os.stat(self.file_loc)[ST_MTIME]
if lm_time > self.prev_lm:
return True
else:
return False
def get_since_last_read(self):
f = open(self.file_loc, "r")
f.seek(self.last_read_pos)
lines = f.readlines()
self.last_read_pos = f.tell()
f.close
self.prev_lm = os.stat(self.file_loc)[ST_MTIME]
return lines
if __name__ == "__main__":
x_file = Watchfile("<file path>")
y_file = Watchfile("<file path>")
while True:
if x_file.changed():
lines = x_file.get_since_last_read()
# do something
if y_file.changed():
lines = y_file.get_since_last_read()
# do something else
try:
time.sleep(5)
except KeyboardInterrupt:
break
More information about the Python-list
mailing list