且构网

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

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

更新时间:2023-11-05 23:50:46

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

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

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

引用 sys.stdout 的文档

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

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

导入时间对于范围内的我(10):打印(我,冲洗=真)时间.睡眠(.5)


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

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

>>>导入时间>>>对于范围内的我(10):...打印我,... time.sleep(.5)...

在 Python 3.x 中,

>>>对于范围内的我(10):...打印(我,结束='')... time.sleep(.5)

我们传递 end='' 因为,默认 end 值为 \n,根据 print 的文档

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

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

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

This code:

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

Causes my computer to hang for 5 seconds, and then print out 0-9, as opposed to printing a digit every half second. Am I doing something wrong?

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

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

Changed in version 3.3: Added the flush keyword argument.

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.

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)
... 

And in Python 3.x,

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

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

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

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

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.