tail -f with python

holger krekel pyth at devel.trillke.net
Sat Aug 3 14:57:29 EDT 2002


Roy Marteen wrote:
> How can I write in Python something like 'tail -f filename'? I mean, when
> 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, ...

as it should. it reads the first line of 'test' and prints it, 
virtually forever. 

There are two possibilities. First is simply invoking 'tail -f'
in the background, basically:

import os
tailoutputfile = os.popen('tail -f syslog')
while 1:
    line = tailoutputfile.readline()
    if len(line)==0:   # change the termination condition 
        break
    process_line(line)


second is doing what 'tail -f' does itself. Basically:

lastsize=os.path.getsize('filename')
while 1:
    size=os.path.getsize('filename')
    if size>lastsize:
        f=open('filename')
        f.seek(lastsize)
        part = f.read(size-lastsize)  # reads chunks, not lines!
        f.close()
        process_next_part(part)
    elif size==lastsize:
        time.sleep(0.2) # seconds to wait
    elif size<lastsize:
        print >>sys.stderr, "file filename got truncated"
        lastsize=size


The code is hopefully self-explaining enough.  
If not, feel free to ask. 

regards,

    holger




More information about the Python-list mailing list