且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

以编程方式执行 Jupyter Notebook 单元

更新时间:2023-02-20 21:48:04

有一个 javascript 函数叫做 execute_cells (在 Github 上查看),当给出一个单元格索引列表时会运行这些单元格.

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.

如果需要专门在Python代码单元中运行,可以使用IPython.display模块中的Javascript函数来执行javascript

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])")

请注意,这会将光标移动到已执行的单元格.如果您想回到光标位置,您可以获取下一个单元格的编号以执行它(代码改编自 this答案):

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