2

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.

2
  • Can you remove the request for a tutorial on IPython via Javascript? If you leave that your question will very likely be closed as you are not supposed to ask for tutorials on this site. Commented Aug 11, 2017 at 15:33
  • Removed - thank you. Commented Aug 11, 2017 at 15:41

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.