How to write a file generator

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at
Wed Jul 13 01:26:01 CEST 2011

Am 12.07.2011 16:46 schrieb Billy Mays:
> I want to make a generator that will return lines from the tail of
> /var/log/syslog if there are any, but my function is reopening the file
> each call


I have another solution: an object which is not an iterator, but an 

class Follower(object):
     def __init__(self, file):
         self.file = file
     def __iter__(self):
         while True:
             l = self.file.readline()
             if not l: return
             yield l

if __name__ == '__main__':
     f = Follower(open("/var/log/messages"))
     while True:
         for i in f: print i,
         print "foo"
         import time

Here, you iterate over the object until it is exhausted, but you can 
iterate again to get the next entries.


More information about the Python-list mailing list