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

问题描述 投票:4回答:2

我想在我的Jupyter笔记本上打印出i并将其冲洗掉。在下一次迭代之后,我将打印下一个i。我试过这个questionthis question的解决方案,然而,它只打印出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()

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

python jupyter-notebook flush
2个回答
9
投票
#Try this:
import sys
import time

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

'\r' will print at the beginning of the line


2
投票

答案是正确的,但我们不需要sys包。您可以在end中使用print参数。

import time

for i in range (10):  
    print(i, end="\r")
    time.sleep(0.5)
© www.soinside.com 2019 - 2024. All rights reserved.