3

I've been using some very nice code from this example to run one ipython notebook from another, which I (basically) copy below. This turns out to be a very nice way to organize my code.

But now, I want to compare some sympy expressions that I've coded up with roughly equivalent sympy expressions that someone else has coded up. And since there are some name clashes, I'd like to be able to execute the two notebooks in their own namespaces, so that if Bob and I both define a sympy expression x, I can just evaluate

Bob.x - Me.x

to see if they are the same (or find their differences). [Note that it's easy to change a namespace dictionary into a "dottable" namespace using something like this Bunch object.]

Here's the function:

def exec_nb(nbfile):
    from io import open
    from IPython.nbformat import current
    with open(nbfile) as f:
        nb = current.read(f, 'json')
    ip = get_ipython()
    for cell in nb.worksheets[0].cells:
        if cell.cell_type != 'code':
            continue
        ip.run_cell(cell.input)

The basic problem is the get_ipython gets the currently running ipython instance, and then run_cell executes the cells from the other notebook in the current namespace of that instance.

I can't figure out how to change this. For example, running the whole command in exec with a different namespace still finds the current ipython instance, and uses that namespace.

Also, both notebooks actually need to be run in ipython; I can't export them to a script and execute the scripts in a namespace.

Community
  • 1
  • 1
Mike
  • 19,114
  • 12
  • 59
  • 91
  • 1
    You may have a look at this notebook as well http://nbviewer.ipython.org/urls/github.com/ipython/ipython/raw/master/examples/notebooks/Importing%2520Notebooks.ipynb – Jakob Oct 28 '13 at 20:45
  • Thank you! That looks like exactly what I want. – Mike Oct 29 '13 at 01:29

1 Answers1

3

For the record, the link Jakob pointed to has now moved here, and answered my question perfectly.

dhj
  • 512
  • 5
  • 16
Mike
  • 19,114
  • 12
  • 59
  • 91