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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With