Flush output in for loop in Jupyter notebook

[亡魂溺海] 提交于 2019-12-07 03:55:56

问题


I want to print out i in my iteration on Jupyter notebook and flush it out. After the next iteration, I'll print the next i. I tried solutions from this question and this question, however, it just print out 0123...9 without flushing the output for me. Here is my working code:

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()

these are my setup: ipython 5.1, python 3.6. Maybe, I missed something in the previous solution?


回答1:


#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:


The answer is correct but we don't need sys package. You can use end parameter in print.

import time

for i in range (10):  
    print(i, end="\r")
    time.sleep(0.5)


来源:https://stackoverflow.com/questions/43150097/flush-output-in-for-loop-in-jupyter-notebook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!