How to write a file generator

bruno.desthuilliers at gmail.com bruno.desthuilliers at gmail.com
Tue Jul 12 11:34:36 EDT 2011


On Jul 12, 4:46 pm, Billy Mays <no... at nohow.com> wrote:
> I want to make a generator that will return lines from the tail of
> /var/log/syslog if there are any

Err... I must have missed something, but python files are their own
iterators.

Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
pythonrc start
pythonrc done
>>> f = open("/var/log/syslog")
>>> for line in f:
...     print line
...
(snip unintersting syslog stuff))

>, but my function is reopening the file
> each call:

How do you know, and how do you call your function ?

> def getLines():
>      with open('/var/log/syslog', 'rb') as f:
>          while True:
>              line = f.readline()
>              if line:
>                  yield line
>              else:
>                  raise StopIteration
>
> I know the problem lies with the StopIteration, but I'm not sure how to
> tell the caller that there are no more lines for now.

If you want the generator to wait until new content is available, just
remove the raise part - but you'll have a blocking call... Else, I
don't see what behaviour you are expecting exactly.







More information about the Python-list mailing list