2

Suppose I have a Python script called my_script.py with a one function called my_func() inside. I import this script into a Jupyter Notebook so I can run my_func() in the cells.

My question is, in the definition of my_func(), how to find which cell number it is called from, so that I can log the cell number? Any API that I could use?

Something like

# 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
Jinsong Li
  • 5,087
  • 1
  • 20
  • 19
  • 1
    It's not exactly the same, but there are some instructions to find the identity of the caller [here](https://stackoverflow.com/q/2654113/11301900). – AMC Jan 08 '20 at 22:25
  • @AMC Thanks for your tip. It is working! – Jinsong Li Jan 09 '20 at 19:13
  • Does this answer your question? [How to write a cell magic that knows the input number of the cell?](https://stackoverflow.com/questions/60694633/how-to-write-a-cell-magic-that-knows-the-input-number-of-the-cell) – Georgy Apr 20 '20 at 11:21

1 Answers1

1

The following javascript snippet in your Jupyter Notebook's cell will give you that cell's index:

%%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)
Rajanya Dhar
  • 156
  • 6