以编程方式执行 Jupyter Notebook 单元 [英] execute a Jupyter Notebook cell programmatically
问题描述
Jupyter Notebook 单元是否可以以编程方式执行另一个单元?(即使用 Python)
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?
推荐答案
有一个 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
这篇关于以编程方式执行 Jupyter Notebook 单元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!