A simple implementation of the standard UNIX utility tail -f in Python.
| Python |
1 2 3 4 5 6 7 8 9 10 | import time
while 1:
where = file.tell()
line = file.readline()
if not line:
time.sleep(1)
file.seek(where)
else:
print line, # already has newline
|
Discussion
The recipe works by line, and actually differs from standard tail -f in that at startup it does not do the equivalent of a standard tail (that is, it will show what is appended to the file after it starts getting run, but that is all).


Comments
How to make it usable.
What tail-10 would do. Sometimes you actually just want the last 10 lines of the file. This will work quite happily on 10Meg files.
I would love to know if there is a more efficient method.
Err, unless I'm missing something. This seems rather inefficient - suppose several lines are added to the file at once - this version will read them a line at a time; pausing for a second between each.
I'm doing more or less the same, but seeking to EOF then using readlines: infile,seek(0,2) while 1: lines=infile.readlines if not lines: time.sleep(1) else
print the line, or pattern match in it, etc.
Better? (New to Python, so I could be way off the mark!)
A simple addition... A nice addition to this is to use "yield" to make the code generic. That is,
Which then allows you to write code like:
Sign in to comment