Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute IPython notebook cell from python script

Tags:

python

ipython

In the IPython notebook, you can execute an outside script, say test.py, using the run magic:

%run test.py

Is there a way to do the opposite, i.e. given an IPython notebook, accessing and then running a particular cell inside it from a python script?

like image 316
Alex Avatar asked Aug 06 '26 21:08

Alex


1 Answers

The file with extention "ipynb" of Jupyter (or IPython) is a JSON file. And the cells are under the name "cells" ["cells"]. Then you choose the number of the cell [0] and to get the source choose "source" ["source"]. In return you get an array with one element so you need to get the first element [0].

>>> import json
>>> from pprint import pprint
>>> with open('so1.ipynb', 'r') as content_file:
...     content = content_file.read()
... 
>>> data=json.loads(content)
>>> data["cells"][0]["source"][0]
'1+1'
>>> eval(data["cells"][0]["source"][0])
2
>>> data["cells"][1]["source"][0]
'2+2'
>>> eval(data["cells"][1]["source"][0])
4

EDIT:

To run other python scripts in cells that have %run:

os.system(data["cells"][2]["source"][0].replace("%run ",""))

Or replace it with the following if you have -i option:

execfile(data["cells"][2]["source"][0].replace("%run -i ",""))

See Run a python script from another python script, passing in args for more info.

like image 102
keiv.fly Avatar answered Aug 08 '26 10:08

keiv.fly