这是我的代码:
import time as t
print('hello', end=' ')
t.sleep(1)
print('hello', end=' ')
t.sleep(1)
print('hello', end=' ')
t.sleep(1)
我的问题是所有打印命令都在sleep命令之后执行,而这不是我的预期输出。
答案 0 :(得分:5)
这是由于输出缓冲。直到打印换行符,缓冲区才会刷新。由于您使用了end=' '
,因此每个单词后都没有换行符,因此在脚本结束之前不会刷新缓冲区。
您可以使用flush=True
选项强制其立即刷新。
import time as t
import sys
print('hello', end=' ', flush=True)
t.sleep(1)
print('hello', end=' ', flush=True)
t.sleep(1)
print('hello', end=' ', flush=True)
t.sleep(1)