【问题标题】:Jupyter Notebook: how to find the cell number from which python script function is called?Jupyter Notebook:如何找到调用python脚本函数的单元格号?
【发布时间】:2020-01-09 06:55:53
【问题描述】:

假设我有一个名为 my_script.py 的 Python 脚本,其中包含一个名为 my_func() 的函数。我将此脚本导入 Jupyter Notebook,以便在单元格中运行 my_func()。

我的问题是,在my_func()的定义中,如何找到调用它的单元号,以便我可以记录单元号?我可以使用任何 API 吗?

类似

# my_script.py

def my_func():
    # find which cell this is called from
    cell_number_called_from = some_IPython_history_class_api.get_current_cell()

    # log the cell number and do the rest of my things

【问题讨论】:

标签: python jupyter-notebook ipython


【解决方案1】:

Jupyter Notebook 单元格中的以下 javascript sn-p 将为您提供该单元格的索引:

%%javascript
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);
console.log(cell_idx)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-19
    • 2018-09-04
    • 2021-05-03
    • 1970-01-01
    • 2021-09-12
    • 2020-10-23
    • 2017-11-16
    • 2021-03-08
    相关资源
    最近更新 更多