tail -f with python
Erik Max Francis
max at alcyone.com
Sat Aug 3 21:16:27 CEST 2002
Roy Marteen wrote:
> How can I write in Python something like 'tail -f filename'? I mean,
> there is an append to the file, it will be displayed real time.
> I tried this:
> while 1:
> line = open('test', 'r').readline()
> print line
> But it keeps looping, eventhough there is no change (append) in file
> 'test'. Please help, and thanks very much.
You probably want to emulate the behavior of tail -f itself.
Disregarding the initial display of the last few lines of the file, seek
to the end of the file (you may have to open the file in binary format
for this), get the current file pointer position, try to read lines. If
you get end of file errors, wait a little bit, seek back to that current
file pointer position, and try to read again.
Try something like this (note this will cat the whole file to start
where = file.tell()
line = file.readline()
if not line: # EOF reached
time.sleep(1) # or however long
file.seek(where) # defaults to absolute positioning
print line, # already has newline
Obviously this must work on a file object which supports .seek and .tell
Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/ \ See the son in your bad day / Smell the flowers in the valley
\__/ Chante Moore
Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/
A personal guide to Aliens vs. Predator 2.
More information about the Python-list