# grepper.py
#
# An example of a Python coroutine function

import time

# This is a generator

def follow(f):
    f.seek(0,2)     # Seek to EOF
    while True:
        line = f.readline()
        if not line: 
            time.sleep(0.1)
            continue
        yield line

# This is a coroutine
def grepper(pat):
    while True:
        line = (yield)
        if pat in line:
           print line

# An example that reads lines like 'tail -f' and sends them into a
# a collection of grepper functions

greppers = [
    grepper('python'),
    grepper('ply'),
    grepper('swig'),
    grepper('index')
]

# Prime them all
for g in greppers:
    g.next()

for line in follow(open("access-log")):
    for g in greppers:
        g.send(line)
