-
-
Save dmmfll/e7317e099f323283d31174f9d02820d0 to your computer and use it in GitHub Desktop.
Creating an IPython Notebook programatically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"cells": [ | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"# Creating an IPython Notebook programatically" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 1, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [], | |
"source": [ | |
"import nbformat as nbf" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 2, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [], | |
"source": [ | |
"nb = nbf.v4.new_notebook()" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"This notebook will simply have three cells that read `print 0`, `print 1`, etc:" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 3, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [], | |
"source": [ | |
"text = \"This is an auto-generated notebook.\"\n", | |
"code = \"1+2\"\n", | |
"\n", | |
"nb['cells'] = [nbf.v4.new_markdown_cell(text),\n", | |
" nbf.v4.new_code_cell(code) ]" | |
] | |
}, | |
{ | |
"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", | |
"execution_count": 4, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [], | |
"source": [ | |
"fname = 'test.ipynb'\n", | |
"\n", | |
"with open(fname, 'w') as f:\n", | |
" nbf.write(nb, f)" | |
] | |
}, | |
{ | |
"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": { | |
"kernelspec": { | |
"display_name": "IPython (Python 3)", | |
"language": "python", | |
"name": "python3" | |
}, | |
"language_info": { | |
"codemirror_mode": { | |
"name": "ipython", | |
"version": 3 | |
}, | |
"file_extension": ".py", | |
"mimetype": "text/x-python", | |
"name": "python", | |
"nbconvert_exporter": "python", | |
"pygments_lexer": "ipython3", | |
"version": "3.5.1" | |
}, | |
"widgets": { | |
"state": {}, | |
"version": "1.1.1" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment