python 的stdout.flush

python的stdout是有缓冲区的,给你个例子你就知道了

import time
import sys

for i in range(5):
    print i,
    #sys.stdout.flush()
    time.sleep(1)

这个程序本意是每隔一秒输出一个数字,但是如果把这句话sys.stdout.flush()注释的话,你就只能等到程序执行完毕,屏幕上会一次性输出0,1,2,3,4。

如果你加上sys.stdout.flush(),刷新stdout,这样就能每隔一秒输出一个数字了。

flush会及时刷新,不缓存

可以用在网络程序中多线程程序,多个线程后台运行,同时要能在屏幕上实时看到输出信息。

猜你喜欢

转载自blog.csdn.net/lucyxu107/article/details/83863898