Creating an IPython Notebook programatically

The nbformat package gives us the necessary tools to create a new Jupyter Notebook without having to know the specifics of the file format, JSON schema, etc.

In [1]:
import nbformat as nbf

Now we create a new notebook object, that we can then populate with cells, metadata, etc:

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

Our simple text notebook will only have a text cell and a code cell:

In [3]:
text = """\
# My first automatic Jupyter Notebook
This is an auto-generated notebook."""

code = """\
%pylab inline
hist(normal(size=2000), bins=50);"""

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:

In [4]:
nbf.write(nb, 'test.ipynb')

This notebook can be run at the command line with:

jupyter nbconvert --execute --inplace test.ipynb

Or you can open it as a live notebook.