问题描述
这段代码:
import time
for i in range(10):
print(i)
time.sleep(.5)
导致我的计算机挂起 5 秒,然后打印出 0-9,而不是每半秒打印一个数字.我做错了吗?
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 默认打印到 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
flushkeyword 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.
这篇关于为什么在循环中使用睡眠时 Python 中的打印不会暂停?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)