【问题标题】:end argument to print leads to different behavior with time.sleepprint 的 end 参数导致 time.sleep 的不同行为
【发布时间】:2017-08-22 22:56:09
【问题描述】:

我尝试编写这个脚本,它只是在同一行上以一秒的延迟依次打印数字,但它不起作用。

这可行:

from time import sleep

for n in range(1, 11):
    print(n)
    sleep(1)

但这并没有,程序只是冻结:

from time import sleep

for n in range(1, 11):
    print(n, end="")
    sleep(1)

谁能解释这是为什么?

【问题讨论】:

  • ops,我现在添加了 end=""

标签: python python-3.x for-loop time printing


【解决方案1】:

程序不会冻结,你只需要通过flush=True来刷新流:

print(n, end="", flush=True)

sys.stdoutprint 默认使用的流,是行缓冲的(在交互模式下),如the documentation 中所述:

  • 交互时,标准流是行缓冲的

这意味着当遇到用于end (\n) 的默认 字符串时,将调用flush。使用其他字符串(即'')不会触发flushing,因此您必须使用flush=True 强制它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-03
    • 2019-03-23
    • 1970-01-01
    • 2021-04-19
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多