为什么`print`内容不能在终端中立即显示?

LWZ*_*LWZ 5 python macos terminal ipython

我有一个用于仿真的python脚本,一个for循环要花很长时间,每个循环要花不同的时间,因此我.在每个循环后打印一个,以监视它运行的速度和经过的时间。for脚本运行时的声明。

for something:
    do something
    print '.',
Run Code Online (Sandbox Code Playgroud)

但是,当我在终端中的iPython中运行脚本时,点并不会一一打印,而是在循环结束时一次打印所有点,这使整个过程变得毫无意义。如何在运行时内联打印点?

Rob*_*obᵩ 10

如何在运行时内联打印点?

尝试刷新您的输出,如下所示:

for _ in range(10):
    print '.',
    sys.stdout.flush()
    time.sleep(.2)  # or other time-consuming work
Run Code Online (Sandbox Code Playgroud)

或者对于 Python 3.x:

for _ in range(10):
    print('.', end=' ', flush=True)
    time.sleep(.2)  # or other time-consuming work
Run Code Online (Sandbox Code Playgroud)