Search code examples
pythongeneratoryieldtailseek

Replicating "tail -f" with Python


According to David Beazley's talk on generators, the following code should replicate the UNIX tail -f command:

import time
def follow(thefile):
    thefile.seek(0,2)
    while True:
        line = thefile.readline()
        if not line:
            time.sleep(0.1)
            continue
        yield line

f = open('followed.txt')
lines = follow(f)

for i in lines:
    print i

If I run this in a shell, it's doing "something", and indeed it locks up the IPython notebook, but it ain't printing out the contents of followed.txt. Why so?


Solution

  • I tried the script, it works.

    You have to make sure your input file is a growing file. If not it is hanging and expecting new growing lines.

    Here's a script keep writing line with timestamp into sample.csv every 5 seconds.

    import os
    import time
    import datetime
    
    while True:
        os.system("echo " + "sample line with timestamp:{0}".format(datetime.datetime.now()) + " >> " + " sample.csv")
        time.sleep(5)
    

    Use your tail -f script to read it and you will see the output.