weird behavior in 'for line in sys.stdin'

Michael McFarland sidlonDoesntLikeSpam at yahoo.com
Thu May 1 21:37:47 EDT 2003


      Thank you for the clear explanation of where the double-^D behavior
come from.  However, I would still tend to consider it a bug that the basic
idiom 'for line in sys.stdin' doesn't terminate from a single '^D'.  Correct
me if I'm wrong, but is there any reason why the 'file' class's xreadlines
method (as opposed to the socket class's) *can't* interpret a read of less
than 500 lines as an EOF?

   - Michael

"Jeff Epler" <jepler at unpythonic.net> wrote in message
news:mailman.1051732384.21374.python-list at python.org...
> 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