Skip to content Skip to sidebar Skip to footer

Jupyter: Programmatically Clear Output From All Cells When Kernel Is Ready

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 t

Solution 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');
    functionclear_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 nowclear_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>

Post a Comment for "Jupyter: Programmatically Clear Output From All Cells When Kernel Is Ready"