为什么“打印”内容不会立即在终端中显示?

2024-04-25 15:11:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用于模拟的python脚本,它需要相当长的时间来运行一个for循环,每个循环都需要不同的时间来运行,因此我在每个循环之后打印一个.,以此来监视它运行的速度和脚本运行时通过for语句的距离。

for something:
    do something
    print '.',

然而,当我在终端的iPython中运行脚本时,这些点并不是一个一个地打印出来的,而是在循环结束时一次全部打印出来,这使得整个过程毫无意义。如何在运行时在线打印点?


Tags: 脚本终端距离for过程ipython时间语句
1条回答
网友
1楼 · 发布于 2024-04-25 15:11:24

How can I print the dots inline as it runs?

尝试刷新输出,如下所示:

for _ in range(10):
    print '.',
    sys.stdout.flush()
    time.sleep(.2)  # or other time-consuming work

或者对于Python 3.x:

for _ in range(10):
    print('.', end=' ', flush=True)
    time.sleep(.2)  # or other time-consuming work

相关问题 更多 >