A simple implementation of the standard UNIX utility tail -f in 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
|
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).
Tags: files
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:
The original code will not sleep on each line, only if there are no lines to be had
if I attempt to insert the output into Qlistbox using
I get "QListBox.insertItem() has an invalid type" do I need to somehow format it?
@ Ed Pascoe code. HI Iam tried using your code for the same requirement at my side. It is working fine and but I have some doughts I actually not understood the logic properly. I tried modifying your code and just removed some lines like " if file.tell()" condition block and "avgcharsperline" statement but I do get 10 lines some times, but some times it prints 8 or 6 or 3 etc... lines. I am little confused actually those above statements what they do could you please elaborate about that thank you.
@Shashidhar: The statements you removed from Ed Pascoe’s code using using
file.tell()
and adjusting theavgcharsperline
value is there to make sure that enough data has been from the end of the file to hold the desired number of lines. Eliminating the logic means that a different number of lines will most likely be printed (as you're apparently finding out).