为什么包含'end ='参数的python print语句在while循环中表现不同?

时间:2012-12-26 23:02:58

标签: python while-loop

我在MacOSX上运行python版本2.7.3。

考虑这段代码:

from __future__ import print_function
import time
x = 0
while x < 5:
    print(x)
    x += 1
    time.sleep(1)

如果我运行此脚本,我会观察到我期望的输出:数字04,每个数字附加\n个字符。此外,每暂停一次后会显示每个号码。

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,但计时是意料之外的。不是在一秒钟暂停后显示每个数字,而是等待四秒钟,然后显示所有五个数字。

为什么print('string')在while-loops中的行为与print('string', end='')不同?有没有办法显示没有换行符的字符,一次一秒?我尝试了sys.stdout.write(str(x)),但其行为与print(end='')相同。

2 个答案:

答案 0 :(得分:19)

因为输出流是行缓冲的 - 因为它没有在print语句之间显式刷新,所以它会等到它看到一个刷新输出的换行符。

您可以通过sys.stdout.flush()强制刷新。

或者,如果您使用-u标志运行Python,它将禁用行缓冲。

答案 1 :(得分:7)

这只是python缓冲标准输出。 This answer有更多信息。

你可以像这样冲洗它:

import sys
from __future__ import print_function
import time
x = 0
while x < 5:
    print(x, end='')
    x += 1
    sys.stdout.flush()
    time.sleep(1)

或者启动python python -u并且它不会被缓冲。