Creating an IPython Notebook programatically

In [3]:
from IPython.nbformat import current as nbf
In [13]:
nb = nbf.new_notebook()

This notebook will simply have three cells that read print 0, print 1, etc:

In [14]:
text = "This is an auto-generated notebook."
code = "1+2"

cells = [nbf.new_text_cell('markdown', text),
         nbf.new_code_cell(code) ]

Now that we have the cells, we can make a worksheet with them and add it to the notebook:

In [15]:

Next, we write it to a file on disk that we can then open as a new notebook.

Note: This should be as easy as: nbf.write(nb, fname), but the current api is a little more verbose and needs a real file-like object.

In [16]:
fname = 'test.ipynb'

with open(fname, 'w') as f:
    nbf.write(nb, f, 'ipynb')

This notebook can be run at the command line with:

ipython -c '%run test.ipynb'

Or you can open it as a live notebook.