Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #9355

Re: How to write a file generator

From Thomas Rachel <nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915@spamschutz.glglgl.de>
Newsgroups comp.lang.python
Subject Re: How to write a file generator
Date 2011-07-13 01:26 +0200
Organization A newly installed InterNetNews server
Message-ID <ivil6a$omr$1@r03.glglgl.eu> (permalink)
References <ivhmoc$6t3$1@speranza.aioe.org>

Show all headers | View raw


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

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


Thomas

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

How to write a file generator Billy Mays <noway@nohow.com> - 2011-07-12 10:46 -0400
  Re: How to write a file generator "bruno.desthuilliers@gmail.com" <bruno.desthuilliers@gmail.com> - 2011-07-12 08:34 -0700
  Re: How to write a file generator Thomas Jollans <t@jollybox.de> - 2011-07-12 17:52 +0200
    Re: How to write a file generator Billy Mays <noway@nohow.com> - 2011-07-12 12:42 -0400
      Re: How to write a file generator Thomas Jollans <t@jollybox.de> - 2011-07-12 21:04 +0200
      Re: How to write a file generator Thomas Jollans <t@jollybox.de> - 2011-07-12 21:05 +0200
  Re: How to write a file generator sturlamolden <sturlamolden@yahoo.no> - 2011-07-12 09:53 -0700
  Re: How to write a file generator Thomas Rachel <nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915@spamschutz.glglgl.de> - 2011-07-13 01:26 +0200

csiph-web