Search code examples
jupyter-notebookgoto

Is there any GOTO ability in Jupyter notebook/lab or contrib extensions?


I have a jupyter notebook for a machine learning project. It has, say, 20 cells. What I'd like to automate is, run the first 19 cells, change a global variable at the last cell, then run all the cell from 2 onward over again with this global variable change.

If there was some kind of GOTO functionality where I could tell a cell to go to another after completing this would be perfect, but workarounds could be useful as well.

What I'm trying to avoid is having to either:
- duplicate all cells after global variable change or
- require manually performing this so that I can't just select 'run all'


Solution

  • You can execute cells programmatically by running some Javascript in the notebook. Put the following in the 21st cell in the notebook:

    %%javascript
    // run the first 19 cells
    var i;
    for(i=0; i<19; i++) {
        Jupyter.notebook.execute_cells([i]);
    }
    
    // set the global in the 20th cell:
    Jupyter.notebook.execute_cells([19]);
    
    // run 2nd through 19th cells again:
    for(i=1; i<19; i++) {
        Jupyter.notebook.execute_cells([i]);
    }