简体   繁体   中英

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?

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.py 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM