本文介绍了Jupyter:内核就绪时,以编程方式清除所有单元的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,关于如何在笔记本完成加载后(内核准备就绪时)并且在用户本人手动执行代码之前,如何以编程方式清除/清除Jupyter笔记本中所有Cell的输出.基本上,我希望笔记本计算机在完成加载后看起来很干净,并且我希望自动进行.

I have a question on how to programmatically clear\clean the output from all the Cells in my Jupyter notebook after notebook is done loading (when Kernel is ready), and prior to the user, myself, manually executing code. Basically, I would like the notebook to look clean when it is done loading, and I would like to do it automatically.

如何从单个初始化单元格向笔记本计算机的所有其他单元格添加类似clear_output()的命令?

How can I impose a command like clear_output() from a single initialization cell on to all other cells in the notebook?

谢谢.

推荐答案

对于受信任的笔记本(请参阅 http://jupyter-notebook.readthedocs.io/en/stable/security.html#Our-security-model 了解有关受信任/不受信任笔记本的详细信息,但在简短地说,为此目的,相关的一点是您在计算机上创建的任何 应该都已经被信任),您可以在开头使用javascript单元格,例如:

For a trusted notebook (see http://jupyter-notebook.readthedocs.io/en/stable/security.html#Our-security-model for details on trusted/untrusted notebooks, but in brief, for this purpose, the relevant bit is that anything you have created on your machine should be trusted already), you could use a javascript cell at the beginning with something like:

require(['base/js/namespace', 'base/js/events'],
function (Jupyter, events) {
    // save a reference to the cell we're currently executing inside of,
    // to avoid clearing it later (which would remove this js)
    var this_cell = $(element).closest('.cell').data('cell');
    function clear_other_cells () {
        Jupyter.notebook.get_cells().forEach(function (cell) {
            if (cell.cell_type === 'code' && cell !== this_cell) {
                cell.clear_output();
            }
            Jupyter.notebook.set_dirty(true);
        });
    }

    if (Jupyter.notebook._fully_loaded) {
        // notebook has already been fully loaded, so clear now
        clear_other_cells();
    }
    // Also clear on any future load
    // (e.g. when notebook finishes loading, or when a checkpoint is reloaded)
    events.on('notebook_loaded.Notebook', clear_other_cells);
});

这在无法信任的笔记本电脑上无法正常运行,对于该笔记本电脑,将清除javascript输出,但是如果您正在创建笔记本电脑,则它应该可以正常运行.如果您不想在每个笔记本中都装一个单元,甚至可以将整个内容包装成一个nbextension.

This won't function in a non-trusted notebook, for which javascript outputs are sanitized, but if you're creating the notebook, it should function ok. You could even wrap the whole thing up into an nbextension if you'd rather not have the cell in every notebook.

<shameless plug>有关nbextensions的示例,请参见 https://github.com/ipython-contrib/jupyter_contrib_nbextensions ,或在那里提出一个问题,建议添加这样的东西</shameless plug>

<shameless plug>See https://github.com/ipython-contrib/jupyter_contrib_nbextensions for examples of nbextensions, or file an issue there to suggest adding something like this</shameless plug>

这篇关于Jupyter:内核就绪时,以编程方式清除所有单元的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 11:47