Jupyter: Programmatically Clear Output from all Cells when Kernel is Ready

ε祈祈猫儿з 提交于 2021-01-28 04:45:31

问题


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.

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

Thank you.


回答1:


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);
});

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



来源:https://stackoverflow.com/questions/45638720/jupyter-programmatically-clear-output-from-all-cells-when-kernel-is-ready

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