6

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?

Alex
  • 3,946
  • 11
  • 38
  • 66

1 Answers1

5

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.

Community
  • 1
  • 1
keiv.fly
  • 3,343
  • 4
  • 26
  • 45
  • Thanks. Is there anything I could do if say the cell had a jupyter/ipython specific magic in it, such as %run? – Alex Jul 28 '16 at 21:39
  • Hii, I have a notebook which plots the graph, and when I execute that cell using this method I am not getting any output. Is there any work around? – Eternal Mar 27 '19 at 14:00
  • Things to check: is there plt.show() at the end, is a compatible matplotlib backend used. Interactive backend used in Jupyter is not compatible with plain python. – keiv.fly Mar 27 '19 at 19:55