且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么在循环中使用睡眠时 Python 中的打印不会暂停?

更新时间:2023-11-06 07:49:51

print 默认打印到 sys.stdout 并在内部缓冲要打印的输出.

print, by default, prints to sys.stdout and that buffers the output to be printed, internally.

输出是否缓冲通常由文件决定,但如果flush关键字参数为真,则流被强制刷新.

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

3.3 版更改:添加了 flush 关键字参数.

Changed in version 3.3: Added the flush keyword argument.

引用 sys.stdout 的文档,

Quoting sys.stdout's documentation,

交互时,标准流是行缓冲的.否则,它们会像常规文本文件一样被块缓冲.

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

因此,在您的情况下,您需要像这样显式刷新

So, in your case, you need to explicitly flush, like this

import time
for i in range(10):
    print(i, flush=True)
    time.sleep(.5)


好的,这个缓冲有很多混乱.让我尽可能解释.


Okay, there is a lot of confusion around this buffering. Let me explain as much as possible.

首先,如果您在终端中尝试此程序,它们会执行行缓冲(这基本上意味着,每当您遇到换行符时,将缓冲的数据发送到 stdout),默认情况下.所以,你可以在 Python 2.7 中重现这个问题,像这样

First of all, if you are trying this program in a terminal, they do line buffering (which basically means, whenever you encounter a newline character, send the buffered data to stdout), by default. So, you can reproduce this problem in Python 2.7, like this

>>> import time
>>> for i in range(10):
...     print i,
...     time.sleep(.5)
... 

在 Python 3.x 中,

And in Python 3.x,

>>> for i in range(10):
...     print(i, end='')
...     time.sleep(.5)

我们通过 end='' 因为,默认的 end 值是 ,根据 print的文档,

We pass end='' because, the default end value is , as per the print's documentation,

print(*objects, sep=' ', end='
', file=sys.stdout, flush=False)

由于默认的end打破了行缓冲,数据将立即发送到stdout.

Since the default end breaks the line buffering, the data will be sent to stdout immediately.

重现此问题的另一种方法是将 OP 给出的实际程序存储在文件中并使用 Python 3.x 解释器执行,您将看到 stdout 在内部缓冲数据并等待程序完成打印.

Another way to reproduce this problem is to store the actual program given by OP in a file and execute with Python 3.x interpreter, you will see that the stdout internally buffers the data and waits till the program finishes to print.