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?
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With