Silly question re: 'for i in sys.stdin'?

T

Tom Eastman

I'm not new to Python, but I didn't realise that sys.stdin could be called
as an iterator, very cool!

However, when I use the following idiom:

for line in sys.stdin:
doSomethingWith(line)

and then type stuff into the program interactively, nothing actually happens
until I hit CTRL-D. I expected that 'doSomethingWith(line)' would execute
after every line I input into the program, just like what used to happen
with:

while True:
line = sys.stdin.readline()
if line == '': break
doSomethingWith(line)

What is the difference?

Thanks for your help!

Tom
 
D

David Trudgett

I'm not a Python expert by any means, but you're describing the
classic symptoms of buffering. There is a '-u' command line switch for
python to turn off buffering but that does not affect file iterators.
See http://www.hmug.org/man/1/python.html for instance.

Tom Eastman said:
I'm not new to Python, but I didn't realise that sys.stdin could be called
as an iterator, very cool!

However, when I use the following idiom:

for line in sys.stdin:
doSomethingWith(line)

Guess what the suggested work-around on the man page was? Use
sys.stdin.readline() in a "while 1:" loop, as you have below:
while True:
line = sys.stdin.readline()
if line == '': break
doSomethingWith(line)

David

--

David Trudgett
http://www.zeta.org.au/~wpower/

Reality is 20% real and 80% made up stuff in your head.
But I'm not sure about the 20%.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,821
Latest member
AleidaSchi

Latest Threads

Top