为什么包含 'end=' 参数的 python 打印语句在 while 循环中的行为不同? [英] Why do python print statements that contain 'end=' arguments behave differently in while-loops?
问题描述
我在 MacOSX 上运行 Python 2.7.3 版.
I'm running python version 2.7.3 on MacOSX.
考虑这个代码块:
from __future__ import print_function
import time
x = 0
while x < 5:
print(x)
x += 1
time.sleep(1)
如果我运行这个脚本,我会观察到我期望的输出:从 0
到 4
的数字,每个数字都附加了一个 \n
字符数字.此外,每个数字会在停顿一秒后显示.
If I run this script, I observe the output I expect: The numbers 0
through 4
with a \n
character appended to each number. Futhermore, each number displays after a one second pause.
0
1
2
3
4
现在考虑这个代码块:
from __future__ import print_function
import time
x = 0
while x < 5:
print(x, end='')
x += 1
time.sleep(1)
输出是我所期望的,01234
没有 \n
,但是 timing 出乎意料.该过程不是在暂停一秒钟后显示每个数字,而是等待四秒钟,然后显示所有五个数字.
The output is what I expect, 01234
without the \n
's, but the timing is unexpected. Rather than displaying each digit after a one-second pause, the process waits four seconds, then displays all five numbers.
为什么 print('string')
与 print('string', end='')
在 while 循环中的行为不同?有没有办法一次一秒地显示没有换行符的字符?我尝试了 sys.stdout.write(str(x))
,但它的行为方式与 print(end='')
相同.
Why does print('string')
behave differently from print('string', end='')
in while-loops? Is there any way to display the characters without newlines, one second at a time? I tried sys.stdout.write(str(x))
, but it behaves the same way as print(end='')
.
推荐答案
因为输出流是行缓冲的——因为它没有在打印语句之间明确地被刷新,它会等到它看到一个换行符来刷新输出.
Because the output stream is line-buffered - since it's not explicitly being flushed in between print statements, it waits until it sees a newline to flush the output.
您可以通过 sys.stdout.flush()
强制刷新.
You can force flushing via sys.stdout.flush()
.
或者,如果您使用 -u
标志运行 Python,它将禁用行缓冲.
Alternatively if you run Python with the -u
flag, it will disable line buffering.
这篇关于为什么包含 'end=' 参数的 python 打印语句在 while 循环中的行为不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!