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

Chr*_*her 6 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)
Run Code Online (Sandbox Code Playgroud)

如果我运行这个脚本,我会观察到我期望的输出:数字0通过附加到每个数字4\n字符.此外,每暂停一秒后显示每个数字.

0
1
2
3
4
Run Code Online (Sandbox Code Playgroud)

现在考虑这个代码块:

from __future__ import print_function
import time
x = 0
while x < 5:
    print(x, end='')
    x += 1
    time.sleep(1)
Run Code Online (Sandbox Code Playgroud)

输出是我所期望的,01234没有\n's,但时间是出乎意料的.该过程不是在一秒钟暂停后显示每个数字,而是等待四秒钟,然后显示所有五个数字.

为什么print('string')表现与print('string', end='')while循环不同?有没有办法显示没有换行符的字符,一次一秒?我尝试过sys.stdout.write(str(x)),但它的行为方式与之相同print(end='').

Amb*_*ber 19

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

你可以强行冲洗sys.stdout.flush().

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


And*_*ett 7

这只是python缓冲标准输出.这个答案有更多的信息.

你可以像这样冲洗它:

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)
Run Code Online (Sandbox Code Playgroud)

或者启动python python -u,它不会被缓冲.