gvoysey
gvoysey

Reputation: 546

programmatic creation of jupyter 4 notebooks?

I would like to programmatically generate some *.ipnb as part of my modeling work, so that i can dump annotated figures and code with markdown annotation to a public git repo. Ideally, I will create a new notebook and publish it every time I run new models.

from this gist, i found a pattern for doing this that involves: from IPython.nbformat import current as nbf

However, IPython.nbformat.current has been deprecated since last spring, and in fact is not present in jupyter/ipython 4.0.1, so this won't work for me.

What's the right pattern for this now?

Upvotes: 4

Views: 971

Answers (2)

JMann
JMann

Reputation: 609

an updated version for v4

there are probably better versions, this worked for me.

from nbformat import v4 as nbf
import nbformat
from os import path



def make_notebook(outPath: str, description: str):
    nb = nbf.new_notebook()
    code = "1+2"
    cells = [nbf.new_markdown_cell( description), nbf.new_code_cell(code)]
    nb['cells'] = cells

    fname = 'test.ipynb'
    print(nb)
    with open(path.join(outPath,fname), 'w') as _:
        nbformat.write(nb, _)

Upvotes: 2

gvoysey
gvoysey

Reputation: 546

D'oh.

IPython.nbformat is deprecated.

nbformat is not...

this seems to work just fine:

from nbformat import current as nbf


def make_notebook(outPath: str, description: str):
    nb = nbf.new_notebook()
    code = "1+2"
    cells = [nbf.new_text_cell('markdown', description), nbf.new_code_cell(code)]
    nb['worksheets'].append(nbf.new_worksheet(cells=cells))

    fname = 'test.ipynb'

    with open(path.join(outPath,fname), 'w') as _:
        nbf.write(nb, _, 'ipynb')

Upvotes: 6

Related Questions