覆盖Jupyter Notebook中的先前输出 [英] Overwrite previous output in jupyter notebook
问题描述
让我们假设我有一部分代码运行了特定的时间,并且每1秒输出如下内容:iteration X, score Y
.我将用黑盒函数代替此函数:
Let's assume I have a part of code that runs for some specific amount of time and each 1 second outputs something like this: iteration X, score Y
. I will substitute this function with my black box function:
from random import uniform
import time
def black_box():
i = 1
while True:
print 'Iteration', i, 'Score:', uniform(0, 1)
time.sleep(1)
i += 1
现在,当我在 Jupyter笔记本中运行它时,它会在每行之后输出新行第二:
Now when I run it in Jupyter notebook, it output a new line after each second:
Iteration 1 Score: 0.664167449844
Iteration 2 Score: 0.514757592404
...
是的,当输出变得太大之后,html变得可滚动,但事实是,除了当前的最后一行之外,我不需要任何这些行.因此,我希望只显示1
行(最后一行),而不是在n
秒后显示n
行.
Yes, after when the output becomes too big, the html becomes scrollable, but the thing is that I do not need any of these lines except of currently the last one. So instead of having n
lines after n
seconds, I want to have only 1
line (the last one) shown.
我没有在文档中找到任何类似的东西,也没有从魔术中寻找任何东西. 一个问题,标题几乎相同,但不相关的.
I have not found anything like this in documentation or looking through magic. A question with almost the same title but irrelevant.
推荐答案
@cel is right: ipython notebook clear cell output in code
使用clear_output()会使您的笔记本电脑产生抖动.我建议也使用display()函数,就像这样(Python 2.7):
Using the clear_output() gives makes your Notebook have the jitters, though. I recommend using the display() function as well, like this (Python 2.7):
from random import uniform
import time
from IPython.display import display, clear_output
def black_box():
i = 1
while True:
clear_output(wait=True)
display('Iteration '+str(i)+' Score: '+str(uniform(0, 1)))
time.sleep(1)
i += 1
这篇关于覆盖Jupyter Notebook中的先前输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!