python 2 stdin can't read individual lines
<p>I have the following very simple-looking code:</p>

<pre><code>from __future__ import print_function
import sys

for line in sys.stdin:
    print("hello!")
    sys.stdout.flush()
</code></pre>

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

<p>When I run it with <code>py -3</code> I get expected results:</p>

<pre><code>py -3 test.py
asdf
hello!
asdf
hello!
asdf
hello!
^C
</code></pre>

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

<pre><code>py -2 test.py
asdf
asdf
asdf
^Z
hello!
hello!
hello!
asdf
^Z
hello!
^Z
</code></pre>

<p>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.</p>

<p>How can I get the Python 2 behavior to match that of Python3?</p>

<h3>EDIT:</h3>

<p>Working Python 3 example on repl.it: <a href="https://repl.it/Cs6n/0" rel="nofollow">https://repl.it/Cs6n/0</a></p>

<p>Broken Python 2 example on repl.it: <a href="https://repl.it/Cs7C/0" rel="nofollow">https://repl.it/Cs7C/0</a></p>

<p>Answer to your question is here <a href="http://stackoverflow.com/questions/107705/disable-output-buffering">Disable output buffering</a>. (4th comment of accepted answer). Your working code should be like this:</p>

<pre><code>from __future__ import print_function
import sys

while True:
    line = sys.stdin.readline()
    print("hello!")
</code></pre>

<p>Works perfect in python 2.7.11</p>

<p><strong>EDIT</strong>:
last line <code>sys.stdout.flush()</code> has been removed. There is no need to use it in this situation.</p>

python io buffer stdin python-2.x