问题:iPython Notebook清除代码中的单元格输出

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

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

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

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

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 ?


回答 0

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

from IPython.display import clear_output

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

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

没有代码示例,给您工作代码并不容易。最好缓冲最近的n个事件是一个好策略。每当缓冲区更改时,您都可以清除单元格的输出并再次打印缓冲区。

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

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!.

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.


回答 1

如果您像我一样来到这里,希望使用Jupitter在Jupyter的Julia笔记本中对地块做同样的事情,则可以使用:

    IJulia.clear_output(true)

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

    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

没有clear_output调用,所有图将单独显示。

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:

    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.


回答 2

您可以使用IPython.display.clear_output清除输出,如cel的答案所述。我要补充一点,对我而言,最好的解决方案是使用以下参数组合进行打印,而不会出现笔记本的“晃动”:

from IPython.display import clear_output

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

You can use the IPython.display.clear_output to 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:

from IPython.display import clear_output

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。