Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 894
Nour Avatar asked May 22 '26 02:05

Nour


1 Answers

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())
like image 198
amicitas Avatar answered May 23 '26 16:05

amicitas