weird behavior in 'for line in sys.stdin'

Jeff Epler jepler at unpythonic.net
Wed Apr 30 15:50:03 EDT 2003


The way that xreadlines works is something like this (but expressed as a
generator):
    def xreadlines(f):
        while 1:
            lines = f.readlines(500) # I'm not sure what number
            if not lines: break
            for l in lines:
                yield l
so you only exit when 'f.readlines()' returns zero lines.  As you
discover, this means hitting ^D twice---the first one ends the lines
returned by readlines prematurely (dropping into the 'yield' loop) 
and the second makes readlines return an empty list.

Unfortunately, since the parameter to readlines is only a *hint*,
reading fewer lines can't be treated as an EOF condition.  If that were
true you could write
    def xreadlines2(f):
        while 1:
            lines = f.readlines(500)
            for l in lines:
                yield l
            if len(lines) != 500: break
or so.  Other times that readlines will return fewer lines than expected
would be if the file is a socket or a pipe, for instance.

Jeff





More information about the Python-list mailing list