Tailing files with Python Generators
I’m slowly improving my Python skills, which always goes much better when you’re on a real mission.
I’m now working on some tools to monitor PostgreSQL performance and I thought Python would be a good choice for that. One of the things I need to do is follow a log file so that I can parse interesting information out of it. Here is a first try to do that with a Python generator function:
def tail(path=None, file=None, delay=1):
if path: file = open(path, 'r')
while 1:
where = file.tell()
line = file.readline()
if not line:
time.sleep(delay)
file.seek(where)
else:
yield line
Here is a little example on how to use this:
for line in tail('/var/log/postgresql/postgresql-8.1-main.log'):
process_line(line)
Pretty sweet. Next step is to make this behave more like ‘tail -F’ so that it follows log files as they are rotated daily.
Created
