[英]Why print in Python doesn't pause when using sleep in a loop?
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. 使我的计算机挂起5秒钟,然后打印出0-9,而不是每半秒打印一次数字。 Am I doing something wrong?
难道我做错了什么?
print
, by default, prints to sys.stdout
and that buffers the output to be printed, internally. print
,默认情况下,打印到sys.stdout
和缓冲器要打印的输出,在内部。
Whether output is buffered is usually determined by file, but if the
flush
keyword argument is true, the stream is forcibly flushed.通常是否由文件决定是否对输出进行缓冲,但是如果
flush
关键字参数为true,则将强制刷新流。Changed in version 3.3: Added the
flush
keyword argument.在版本3.3中更改:添加了
flush
关键字参数。
Quoting sys.stdout
's documentation , 引用
sys.stdout
的文档 ,
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. 首先,如果您在终端中尝试该程序,则默认情况下它们会进行行缓冲 (这基本上意味着,每当遇到换行符时,都将缓冲的数据发送到
stdout
)。 So, you can reproduce this problem in Python 2.7, like this 因此,您可以像这样在Python 2.7中重现此问题
>>> import time
>>> for i in range(10):
... print i,
... time.sleep(.5)
...
And in Python 3.x, 在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 , 我们传递
end=''
,因为根据print
文档 ,默认的end
值为\\n
,
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. 由于默认
end
中断了行缓冲,因此数据将立即发送到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. 重现此问题的另一种方法是将OP给出的实际程序存储在一个文件中,并使用Python 3.x解释器执行,您将看到
stdout
内部缓冲数据并等待程序完成打印。
Try this: 尝试这个:
for i in range(10):
sys.stdout.write('\r' + str(i))
time.sleep(.5)
here '/r'
is carriage return, it brings the cursor first place again. 这里的
'/r'
是回车符,它将光标再次带到第一位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.