7

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?

1
  • IPython has a format like xml. You can parse it and run the cell you want. Commented Jul 27, 2016 at 20:41

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Is there anything I could do if say the cell had a jupyter/ipython specific magic in it, such as %run?
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?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.