gpt4 book ai didi

python - 在同一行打印,一步一步

转载 作者:太空宇宙 更新时间:2023-11-03 12:33:05 25 4
gpt4 key购买 nike

我开发了一个 Python 脚本,可以连续执行多个任务(主要是连接到服务器和检索信息)。

有很多步骤,我想为每个步骤显示一个点,以便用户知道正在发生的事情。

在每个步骤结束时,我会:

print('.', end='')

在最后一步,我写:

print('Done!')

它可以工作,除了在执行最终打印之前什么都不显示,所以它有点违背了它的初衷:)

基本上,屏幕上什么都没有显示,在最后一刻,弹出了这个:

.......Done!

如何强制 Python 在同一行一步步打印?

最佳答案

默认情况下,stdout 是行缓冲的,这意味着在您编写换行符之前不会刷新缓冲区。

每次打印 '.' 时显式刷新缓冲区:

print('.', end='', flush=True)

flush 关键字是在 Python 3.3 中加入的;对于旧版本,使用 sys.stdout.flush()

来自print() function documentation :

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

来自sys.stdout documentation (print() 函数的 file 参数的默认值):

When interactive, standard streams are line-buffered. Otherwise, they are block-buffered like regular text files.

关于python - 在同一行打印,一步一步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24257303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com