How can I execute a .ipynb notebook file in a Python script?

Viewed 2770

I have a notebook that I need to call in a Python file. I know that calling a notebook in another notebook is done using %run ./NotebookName, and calling a Python module in a notebook can be done using import. So how can a notebook be called in a Python file?

3 Answers

You can use the nbconvert package to execute ipython/jupyter notebooks from within python. Instructions are available within the nbconvert documentation: Executing notebooks.

Here is a short example

import nbformat
from nbconvert.preprocessors import ExecutePreprocessor

filename = 'NotebookName.ipynb'
with open(filename) as ff:
    nb_in = nbformat.read(ff, nbformat.NO_CONVERT)
    
ep = ExecutePreprocessor(timeout=600, kernel_name='python3')

nb_out = ep.preprocess(nb_in)

The output is an ipython/jupyter notebook including the output of all cells.

Ipython/Jupyter *.ipynb notebooks are actually just JSON files with a particular structure. To execute the cells of a notebook in a python script one can read the file using the python json library, extract the code from the notebook cells, and then execute the code using exec().

Here is an example that also includes removal of any ipython magic commands:

from json import load

filename = 'NotebookName.ipynb'
with open(filename) as fp:
    nb = load(fp)

for cell in nb['cells']:
    if cell['cell_type'] == 'code':
        source = ''.join(line for line in cell['source'] if not line.startswith('%'))
        exec(source, globals(), locals())

You can just download de notebook as a file.pyenter image description here

Related