Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ipython Notebook: programmatically read and execute cells

In the ipython notebook, I would like to programmatically read and execute code cells from within a code cell itself.

Something like

if condition:
  # run input cell no. 3

I found a solution here, the function execute_notebook reads an ipynb file cell by cell and executes code cells using get_ipython().run_cell().

Is there a way to do the same, i.e. without reading the cells from the an external ipynb file first? Is there a way to write macros, to reference and access code cells from within an ipython notebook?

like image 798
Roland Fabio Avatar asked Mar 11 '14 14:03

Roland Fabio


2 Answers

hi the exact answer to your question is :

import io
from IPython.nbformat import current

with io.open("Name_of_your_notebook.ipynb") as f:
nb = current.read(f, 'json')

ip = get_ipython()

for cell in nb.worksheets[0].cells:
  if cell.cell_type != 'code':
    continue
  if cell.prompt_number==4186:
    ip.run_cell(cell.input)

but keep in mid please, the cell will be run under this code, not like as function in py does

like image 95
Mehran Sahandi Far Avatar answered Nov 13 '22 20:11

Mehran Sahandi Far


I'm not sure if I understand your question correctly. Would you like to be able to manipulate the exact same notebook that you are currently working in? While this may be possible, it honestly sounds like a recipe for disaster because it will most likely leave your currently running notebook in an undefined state (or at the very least it would make it hard to follow what's going on).

A cleaner solution may be to programmatically generate a separate notebook in which you include precisely the code cells you need for your use case, and then execute it. (Alternatively, you can have a "template" .ipynb file with dummy code cells which you then programmatically replace with the actual code that you want to run).

I needed to do a similar thing recently and have written up a detailed example which shows how to do this. It programmatically generates a new notebook, adds a few markdown and code cells (which in this case produce a sine wave plot where the frequency is injected on-the-fly), then executes this notebook and saves the result for further postprocessing.

I hope this helps. Let me know if I completely misunderstood what you are trying to do.

like image 30
cilix Avatar answered Nov 13 '22 19:11

cilix