数据缓存是指一个物理内存区域,当数据从一个地方移动到另外一个地方的时候,用于暂时存储数据。当在一台电脑上进行数据移动时,存储在数据缓存中的数据会被输入设备或者输出设备取出。python的标准输出也是被缓存起来的,这意味着该缓存会先收集数据,等缓存满了之后才会写入标准输出,然后这些数据会被写到终端或者其他输出流。
实验一
import sys
import time
for i in range(10):
print(i)
time.sleep(1)
该实验会每隔一秒打印一个数字
输出会自动的刷新缓存,因为print默认时以‘\n’结尾,
实验二
# Python3 program demonstrating working
# of flush during output
import sys
import time
for i in range(10):
print(i, end =' ')
time.sleep(1)
该实验在前9秒不会打印数据,只会在第10秒的时候把之前的数据一并打印出来,因为用空格作为print的分隔符,不会触发缓存刷新
实验三
# Python3 program demonstrating working
# of flush during output and usage of
# sys.stdout.flush() function
import sys
import time
for i in range(10):
print(i, end =' ')
sys.stdout.flush()
time.sleep(1)
该输出就会每隔一秒打印一个数字,因为代码主动刷新了缓存
实验四
# Python3 program demonstrating working
# of flush during output and usage of
# flush parameter of print statement
import sys
import time
for i in range(10):
print(i, end =' ', flush = True)
time.sleep(1)
当然了print本身也提供了flush参数,通过设置也可以主动刷新