python 2 stdin 无法读取个别行

python 2 stdin can't read individual lines

我有以下看起来非常简单的代码:

from __future__ import print_function
import sys

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

当我 运行 它时,我希望输入一行然后立即看到 hello! 打印出来,之后我可以输入另一行。

当我 运行 它与 py -3 我得到预期的结果:

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

当我 运行 它与 py -2 时,它不会打印 hello! 除非我发送 ctrl-Z:

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

I 运行 此测试在 Windows 上使用 Python 2.7.12,在 Linux 上(使用 ctrl-D 而不是 ctrl-Z)使用 Python 2.6.6.

如何让 Python 2 的行为与 Python3 的行为相匹配?

编辑:

在 repl.it 上工作 Python 3 个示例:https://repl.it/Cs6n/0

损坏 Python repl.it 上的 2 个示例:https://repl.it/Cs7C/0

您的问题的答案在这里 Disable output buffering。 (已接受答案的第 4 条评论)。你的工作代码应该是这样的:

from __future__ import print_function
import sys

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

在 python 2.7.11

中完美运行

编辑: 最后一行 sys.stdout.flush() 已被删除。这种情况就没必要用了。