【发布时间】:2017-01-02 20:23:29
【问题描述】:
我有以下看起来非常简单的代码:
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
我在使用 Python 2.7.12 的 Windows 和使用 Python 2.6.6 的 Linux(使用 ctrl-D 而不是 ctrl-Z)上运行了这个测试。
如何让 Python 2 的行为与 Python3 的行为相匹配?
编辑:
repl.it 上的 Python 3 示例:https://repl.it/Cs6n/0
repl.it 上损坏的 Python 2 示例:https://repl.it/Cs7C/0
【问题讨论】:
标签: python io buffer stdin python-2.x