tail -f with python

Skip Montanaro skip at pobox.com
Sat Aug 3 21:01:47 CEST 2002


    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)
    except KeyboardInterrupt:
        pass

-- 
Skip Montanaro
skip at pobox.com
consulting: http://manatee.mojam.com/~skip/resume.html




More information about the Python-list mailing list