import sys
import time
for i in range(10):
print('hello world')
#sys.stdout.write('hello world' + '\n')
#sys.stdout.flush()
time.sleep(1)
看了sys.stdout.flush的用法,说是强制刷新缓冲区。但是试了上面的代码,哪怕不加sys.stdout.flush(),也是也是每隔一秒就打印一次。真是奇怪奇怪!?
import sys
import time
f = open('log','w')
__console__ = sys.stdout
sys.stdout = f
for i in range(10):
print('hello world')
#sys.stdout.write('hello world' + '\n')
sys.stdout.flush()
f.close()
sys.stdout = __console__
后来试了写文件,加和不加sys.stdout.flush。前者是每秒写一次文件,后者是10秒后才写文件。