在Jupyter笔记本中刷新for循环输出

tit*_*ata 6 python flush jupyter-notebook

我想i在我的Jupyter笔记本上打印出来并将其冲洗掉.在下一次迭代之后,我将打印下一次i.我尝试了这个问题这个问题的解决方案,然而,它只打印出来0123...9而没有为我刷新输出.这是我的工作代码:

import sys
import time

for i in range(10):
    sys.stdout.write(str(i)) # or print(i, flush=True) ?
    time.sleep(0.5)
    sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)

这些是我的设置:ipython 5.1,python 3.6.也许,我错过了以前的解决方案?

âńō*_*oůŜ 10

#Try this:
import sys
import time

for i in range (10):  
    sys.stdout.write('\r'+str(i))
    time.sleep(0.5)
Run Code Online (Sandbox Code Playgroud)

'\ r'将在该行的开头打印


Alp*_*ren 7

The first answer is correct but you don't need sys package. You can use the end parameter of the print function. It specifies what to print at the end, and its default value is \n(newline) (docs1, docs2). Use \r(carriage return) instead.

import time

for i in range (10):  
    print(i, end="\r")
    time.sleep(0.5) # This line is to see if it's working or not
Run Code Online (Sandbox Code Playgroud)