0

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

Community
  • 1
  • 1
Nate Glenn
  • 6,455
  • 8
  • 52
  • 95

1 Answers1

3

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.

Community
  • 1
  • 1
Eduard Ilyasov
  • 3,268
  • 2
  • 20
  • 18
  • Thank you! That was a very vexing problem. Also, there's an official mention of it is in the documentation on the `-u` command line switch. – Nate Glenn Aug 26 '16 at 09:55
  • If output buffering is disabled, the last line does not do anything, does it? – guidot Aug 26 '16 at 10:06
  • This snippet of code works well without last line. No need to use sys.stdout.flush() in this situation, because output buffering is disabled. Thank's for remark, @guidot. – Eduard Ilyasov Aug 26 '16 at 10:15