Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute a Jupyter Notebook cell programmatically

Is it possible for a Jupyter Notebook cell to execute another cell programmatically? (i.e. using Python)

And if so, is it possible to specify the cell number to execute?

like image 930
RumbleFish Avatar asked Nov 30 '17 07:11

RumbleFish


People also ask

How do I run a Jupyter notebook as a script?

When you open a new Jupyter notebook, you'll notice that it contains a cell. Cells are how notebooks are structured and are the areas where you write your code. To run a piece of code, click on the cell to select it, then press SHIFT+ENTER or press the play button in the toolbar above.

How do you run a cell in Python?

You can also run code cells using (Ctrl+Enter) or the Python: Run Selection/Line in Python Terminal command (Shift+Enter). After using this command, the Python extension automatically moves the cursor to the next cell.


2 Answers

There is a javascript function called execute_cells (see it on Github) that when given an list of cell indices runs those cells.

%%javascript
Jupyter.notebook.execute_cells([0]) # 0 to run first cell in notebook etc.

If you need to run it specifically in a Python code cell, one can use the Javascript function in the IPython.display module to execute javascript

from IPython.display import Javascript
Javascript("Jupyter.notebook.execute_cells([2])")

Note that this will move the cursor to executed cells. If you wish to get back to the cursor position, you may get the number of the next cell in order to execute it (code adapted from this answer) :

%%javascript
Jupyter.notebook.execute_cells([0]) # 0 to run first cell in notebook etc.

var output_area = this;
// find my cell element
var cell_element = output_area.element.parents('.cell');
// which cell is it?
var cell_idx = Jupyter.notebook.get_cell_elements().index(cell_element);
Jupyter.notebook.execute_cells([cell_idx+1]) # execute next cell
like image 100
Louise Davies Avatar answered Oct 22 '22 07:10

Louise Davies


I would like to add to the answer @Louise Davies. If you want to execute a range of cells, use:

from IPython.display import Javascript
Javascript("Jupyter.notebook.execute_cell_range(10,20)") 
like image 23
Phoenix Avatar answered Oct 22 '22 08:10

Phoenix