Search code examples
pythonjupyter-notebookjupyter

Upon restarting a Jupyter notebook, automatically run 1st/nth cell only (to load modules and other variables), ideally using a keyboard shortcut


In addition to loading required modules, in the first cell of the jupyter notebook, I usually load variables (e.g. metadata, tables etc.). So every time when I restart a jupyter notebook, I need to run the 1st cell of the notebook. I know this is not a big issue, but sometimes can be an annoyance. For example, if I would be working at the end of the notebook and need to restart it, I would have to scroll all the way up, run the first cell, and then scroll all the way back to resume the work.

I hope there is a way to automatically run 1st (or any n'th) cell of a jupyter notebook when it is restarted. I wonder if anybody knows if such a functionality exists.


Solution

    1. Install jupyter notebook extensions (see here how it is done: https://jupyter-contrib-nbextensions.readthedocs.io/en/latest/install.html ).
    2. Use the Initialization cells extension (https://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/init_cell/README.html ).

    It allows you to mark one or more cells as 'Initialisation cells' that will run when the notebook is opened or on clicking the (then added) 'initialization button' in the main toolbar.

    The cell toolbar selector can be found under View > Cell Toolbar > Initialization Cell.

    Not 100% what you are looking for as you need to click an extra button after restarting the notebook. On the other hand, scrolling up and down is avoided and it is an easy fix.