【问题标题】:python 2 stdin can't read individual linespython 2 stdin 无法读取单行
【发布时间】: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


    【解决方案1】:

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

    from __future__ import print_function
    import sys
    
    while True:
        line = sys.stdin.readline()
        print("hello!")
    

    在 python 2.7.11 中完美运行

    编辑: 最后一行sys.stdout.flush() 已被删除。在这种情况下不需要使用它。

    【讨论】:

    • 谢谢!那是一个非常令人头疼的问题。此外,在-u 命令行开关的文档中也有官方提及。
    • 如果禁用了输出缓冲,最后一行什么都不做,是吗?
    • 这个 sn-p 代码在没有最后一行的情况下运行良好。在这种情况下不需要使用 sys.stdout.flush(),因为输出缓冲被禁用。谢谢你的评论,@guidot。
    猜你喜欢
    • 2014-09-07
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 2012-08-11
    • 2016-06-05
    • 2014-01-15
    • 2012-08-28
    相关资源
    最近更新 更多