Creating templates

Programmatically creating new cells - first take

Trying to use IPython functionallity to make new cells


In [ ]:
import IPython

In [ ]:
def create_new_cell(contents):
    # https://stackoverflow.com/questions/54987129/
    # how-to-programmatically-create-several-new-cells-in-a-jupyter-notebook
    
    from IPython.core.getipython import get_ipython
    shell = get_ipython()

    payload = dict(
        source='set_next_input',
        text=contents,
        replace=False,
    )
    shell.payload_manager.write_payload(payload, single=False)

In [ ]:
for j in range(3):
    r = create_new_cell(f"print('hello {j}')")

In [ ]:
shell = IPython.core.getipython.get_ipython()

In [ ]:
shell.starting_dir

In [ ]:
# %notebook "new.ipynb"

Result:

Works only within jupyter, not jupyterlab. However, it could be used for loading just a single cell.

Testing PaperMill


In [ ]:
in_nb = '/users/jepe/scripting/cellpy/dev_utils/papermill/pm_input_test.ipynb'
out_nb = '/users/jepe/scripting/cellpy/dev_utils/papermill/pm_output_test.ipynb'

In [ ]:
import papermill as pm
from pathlib import Path

In [ ]:
def create_template(template_name, autorun=False):
    datestamp = '20190810'
    name = 'test'
    out_dir = '/users/jepe/scripting/cellpy/dev_utils/papermill'
    in_nb = input_notebook(template_name)
    out_nb = output_notebook(template_name, out_dir=out_dir, datestamp=datestamp, name=name)
    print(in_nb)
    print(out_nb)
    nb_node = pm.execute_notebook(
        str(in_nb.resolve()),
        str(out_nb.resolve()),
        prepare_only=not autorun,
        parameters=dict(a=3, b='anna')
    )
    
    return nb_node

In [ ]:
def output_notebook(template, out_dir=None, datestamp='20190810', name='test'):
    if out_dir is None:
        out_dir = Path()
    fname = f'{datestamp}_{name}_{template}.ipynb'
    path = Path(out_dir) / fname
    return path

In [ ]:
def input_notebook(template='pm_input_test'):
    in_dir = '/users/jepe/scripting/cellpy/dev_utils/papermill'
    fname = f'{template}.ipynb'
    path = Path(in_dir) / fname
    return path

In [ ]:
nb_node = create_template('pm_input_test', autorun=False)

Conclussion

This is promising


In [ ]: