Possible File iteration bug

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Fri Jul 15 08:39:05 EDT 2011

Am 14.07.2011 21:46 schrieb Billy Mays:
> I noticed that if a file is being continuously written to, the file
> generator does not notice it:

Yes. That's why there were alternative suggestions in your last thread 
"How to write a file generator".

To repeat mine: an object which is not an iterator, but an iterable.

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__':
     import time
     f = Follower(open("/var/log/messages"))
     while True:
         for i in f: print i,
         print "all read, waiting..."

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

The difference to the file as iterator is, as you have noticed, that 
once an iterator is exhausted, it will be so forever.

But if you have an iterable, like the Follower above, you can reuse it 
as you want.

More information about the Python-list mailing list