Writing a Tail -f Script in Python – Generator Version

Yet another one of David Beazley code samples from his Generator Tricks For Systems Programmers.  This one acts like a tail -f, reading any new lines added to a file.  More information on this can be found at http://www.dabeaz.com/.

Here is the source code, pretty small but extremely useful when working with log files.

import time

def monitor(file):
    file.seek(0,2)
    while True:
        line = file.readline()
        if not line:
            time.sleep(0.1)
            continue
        yield line
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s