Nate Glenn Nate Glenn - 3 months ago 10
Python Question

python 2 stdin can't read individual lines

I have the following very simple-looking code:

from __future__ import print_function
import sys

for line in sys.stdin:
print("hello!")
sys.stdout.flush()


When I run it, I expect to type in a line and then immediately see
hello!
printed out after it, after which I can type in another line.

When I run it with
py -3
I get expected results:

py -3 test.py
asdf
hello!
asdf
hello!
asdf
hello!
^C


When I run it with
py -2
, it won't print
hello!
unless I send ctrl-Z:

py -2 test.py
asdf
asdf
asdf
^Z
hello!
hello!
hello!
asdf
^Z
hello!
^Z


I ran this test on Windows with Python 2.7.12 and on Linux (using ctrl-D instead of ctrl-Z) with Python 2.6.6.

How can I get the Python 2 behavior to match that of Python3?

EDIT:



Working Python 3 example on repl.it: https://repl.it/Cs6n/0

Broken Python 2 example on repl.it: https://repl.it/Cs7C/0

Answer

Answer to your question is here Disable output buffering. (4th comment of accepted answer). Your working code should be like this:

from __future__ import print_function
import sys

while True:
    line = sys.stdin.readline()
    print("hello!")

Works perfect in python 2.7.11

EDIT: last line sys.stdout.flush() has been removed. There is no need to use it in this situation.