Reading from stdin

George Sakkis george.sakkis at gmail.com
Tue Oct 7 23:27:19 EDT 2008


On Oct 7, 8:13 pm, Luis Zarrabeitia <ky... at uh.cu> wrote:
> On Tuesday 07 October 2008 05:33:18 pm George Sakkis wrote:
>
> > Not an answer to your actual question, but you can keep the 'for' loop
> > instead of rewriting it with 'while' using the iter(function,
> > sentinel) idiom:
>
> > for line in iter(sys.stdin.readline, ""):
> >     print "You said!", line
>
> You're right, it's not an answer to my actual question, but I had completely
> forgotten about the 'sentinel' idiom. Many thanks... I was trying to do it
> with 'itertools', obviously with no luck.
>
> The question still stands (how to turn off the buffering), but this is a nice
> workaround until it gets answered.

The closest answer I found comes from the docs (http://docs.python.org/
library/stdtypes.html#file-objects):

"""
In order to make a for loop the most efficient way of looping over the
lines of a file (a very common operation), the next() method uses a
hidden read-ahead buffer. As a consequence of using a read-ahead
buffer, combining next() with other file methods (like readline())
does not work right.
"""

I guess the phrasing "hidden read-ahead buffer" implies that buffering
cannot be turned off (or at least it is not intended to even if it's
somehow possible).

George



More information about the Python-list mailing list