【问题标题】:Python printing character-by-character in OSX TerminalPython在OSX终端中逐个字符打印
【发布时间】:2014-12-23 13:24:54
【问题描述】:

我正在尝试让 Python 将 .txt 文件的内容复制到 OS X (10.10) 上的 bash 终端中,但在该行的每个字符都打印到该行之前,该行不会打印。有没有办法让Python逐个字符而不是逐行打印每一行?我的代码设计为在字符之间等待,但每一行都需要很长时间才能打印出来:

while True:
    character = text_file.read(1)
    if not character: break
    else:
        sys.stdout.write(character)
        time.sleep(0.050)

当我在 IDLE 中运行此代码时,字符一次打印一个。在终端中,打印行需要几秒钟,并且每行一次打印。有什么方法可以重现我在终端 IDLE 中看到的行为?

【问题讨论】:

    标签: python terminal osx-yosemite


    【解决方案1】:

    在sys.stdout.write(character)之后添加sys.stdout.flush()

    原因应该是stdout的输出被缓冲了。

    【讨论】:

    • 完美。我没有想到这一点。我猜IDLE只是没有标准输出的缓冲区,那么。谢谢你的解释!
    • @user2569332 很高兴为您提供帮助:)
    【解决方案2】:

    如果你想在行尾删除新行。

    你可以简单

    print character,
    

    将删除新行(\n)。

    【讨论】:

      猜你喜欢
      • 2013-02-28
      • 2012-06-27
      • 2021-04-19
      • 2011-10-17
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      相关资源
      最近更新 更多