tail -f with python

holger krekel pyth at devel.trillke.net
Sat Aug 3 15:08:18 EDT 2002


Skip Montanaro wrote:
>     Roy> How can I write in Python something like 'tail -f filename'? I
>     Roy> mean, when there is an append to the file, it will be displayed
>     Roy> real time.
> 
> Try something like this (only very lightly tested):
> 
>     #!/usr/bin/env python
> 
>     import os
>     import sys
>     import time
> 
>     offset = 0
>     fname = sys.argv[1]
>     try:
>         while 1:
>             size = os.path.getsize(fname)
>             if size > offset:
>                 f = open(fname, 'r')
>                 f.seek(offset)
>                 sys.stdout.write(f.read())
>                 f.close()
>                 offset = size
>                 time.sleep(0.1)

typo alarm!

you probably want time.sleep(0.1) to be indented here:

              time.sleep(0.1)

otherwise you consume 100% CPU-time if the file doesn't
change.

>     except KeyboardInterrupt:
>         pass

that's for additional educational purposes, right? 

regards,

    holger




More information about the Python-list mailing list