ipython notebook 在代码中清除单元格输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24816237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:16:55  来源:igfitidea点击:

ipython notebook clear cell output in code

pythonipythonipython-notebook

提问by aha

In a iPython notebook, I have a while loop that listens to a Serial port and printthe received data in real time.

在 iPython 笔记本中,我有一个 while 循环,它print实时侦听串行端口和接收到的数据。

What I want to achieve to only show the latest received data (i.e only one line showing the most recent data. no scrolling in the cell output area)

我想要实现的仅显示最新接收到的数据(即只有一行显示最新数据。在单元格输出区域中没有滚动)

What I need(i think) is to clear the old cell output when I receives new data, and then prints the new data. I am wondering how can I clear old data programmatically ?

我需要(我认为)是在收到新数据时清除旧单元格输出,然后打印新数据。我想知道如何以编程方式清除旧数据?

采纳答案by cel

You can use IPython.display.clear_outputto clear the output of a cell.

您可以使用IPython.display.clear_output清除单元格的输出。

from IPython.display import clear_output

for i in range(10):
    clear_output(wait=True)
    print("Hello World!")

At the end of this loop you will only see one Hello World!.

在此循环结束时,您只会看到一个Hello World!.

Without a code example it's not easy to give you working code. Probably buffering the latest n events is a good strategy. Whenever the buffer changes you can clear the cell's output and print the buffer again.

如果没有代码示例,就不容易为您提供工作代码。可能缓冲最近的 n 个事件是一个很好的策略。每当缓冲区发生变化时,您都可以清除单元格的输出并再次打印缓冲区。

回答by marzetti

And in case you come here, like I did, looking to do the same thing for plots in a Julia notebook in Jupyter, using Plots, you can use:

如果您像我一样来到这里,希望在 Jupyter 的 Julia 笔记本中使用 Plots 对绘图执行相同的操作,您可以使用:

    IJulia.clear_output(true)

so for a kind of animated plot of multiple runs

所以对于一种多次运行的动画情节

    if nrun==1  
      display(plot(x,y))         # first plot
    else 
      IJulia.clear_output(true)  # clear the window (as above)
      display(plot!(x,y))        # plot! overlays the plot
    end

Without the clear_output call, all plots appear separately.

如果没有 clear_output 调用,所有图都单独显示。

回答by hof.and.or

You can use the IPython.display.clear_outputto clear the output as mentioned in cel's answer. I would add that for me the best solution was to use this combination of parameters to print without any "shakiness" of the notebook:

您可以使用IPython.display.clear_output清除 cel 回答中提到的输出。我想补充一点,对我来说最好的解决方案是使用这种参数组合进行打印,而不会出现笔记本的任何“抖动”:

from IPython.display import clear_output

for i in range(10):
    clear_output(wait=True)
    print(i, flush=True)