Creating an IPython Notebook programatically

In [24]:
import IPython.nbformat as nbf

Let's create the new notebook object first:

In [27]:
nb = nbf.v4.new_notebook()

For this example, we populate it with a simple text cell and one with code. Empty notebooks are OK too, this is just for illustration purposes:

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

nb['cells'] = [nbf.v4.new_markdown_cell(text),
               nbf.v4.new_code_cell(code) ]

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. We're fixing that.

In [28]:
filename = 'test.ipynb'

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

This notebook can be run at the command line with:

ipython -c '%run test.ipynb'

Or you can open it as a live notebook.