Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python 3.x - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...