Reading from stdin

George Sakkis george.sakkis at gmail.com
Tue Oct 7 23:33:18 CEST 2008


Luis Zarrabeitia wrote:
> I have a problem with this piece of code:
>
> ====
> import sys
> for line in sys.stdin:
>     print "You said!", line
> ====
>
> Namely, it seems that the stdin buffers the input, so there is no reply until
> a huge amount of text has bin written. The iterator returned by xreadlines
> has the same behavior.
>
> The stdin.readline() function doesn't share that behaviour (it returns as soon
> as I hit 'enter').
>
> ??Is there any way to tell stdin's iterator not to buffer the input? Is it
> part of the standard file protocol?

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

George



More information about the Python-list mailing list