Skip to content

Instantly share code, notes, and snippets.

@jaimergp
Forked from fperez/ProgrammaticNotebook.ipynb
Last active May 28, 2016 19:52
Show Gist options
  • Save jaimergp/96666c3ddd0cdd52e3056d92d1cbf1ec to your computer and use it in GitHub Desktop.
Save jaimergp/96666c3ddd0cdd52e3056d92d1cbf1ec to your computer and use it in GitHub Desktop.
Creating an IPython Notebook programatically
Display the source blob
Display the rendered blob
Raw
{
"metadata": {
"name": "",
"signature": "sha256:de19c92dacc550f16a6a28a06419f10830ed780a132b6b565758a6a675565fe5"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"Creating an IPython Notebook programatically"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from IPython.nbformat import current as nbf # deprecated\n",
"from IPython.nbformat import v4 as nbf # import version directly\n"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 3
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"nb = nbf.new_notebook()"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 13
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This notebook will simply have three cells that read `print 0`, `print 1`, etc:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"text = \"This is an auto-generated notebook.\"\n",
"code = \"1+2\"\n",
"\n",
"cells = [nbf.new_text_cell('markdown', text),\n",
" nbf.new_code_cell(code) ]"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 14
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now that we have the cells, we can make a worksheet with them and add it to the notebook:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"nb['cells'].extend(cells)"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 15
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, we write it to a file on disk that we can then open as a new notebook.\n",
"\n",
"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\n",
"object."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"fname = 'test.ipynb'\n",
"\n",
"with open(fname, 'w') as f:\n",
" nbf.write(nb, f, 'ipynb')"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 16
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This notebook can be run at the command line with:\n",
"\n",
" ipython -c '%run test.ipynb'\n",
"\n",
"Or you can open it [as a live notebook](test.ipynb)."
]
}
],
"metadata": {}
}
]
}
@jaimergp
Copy link
Author

v4 notebooks have no 'worksheets', but directly 'cells'. Also the module version must be imported explicitly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment