Reputation: 247
I know I can call
jupyter nbconvert --execute --to html notebook.ipynb
from shell, or do a system call from Python:
import os
os.system('jupyter nbconvert --execute --to html notebook.ipynb')
But having to do this with a system call when an nbconvert
module is available in native Python seems very odd!
I want to write native python to execute and convert a iPython notebook to an html file. I studied the official documentation a little but couldn't piece things together. My questions are:
Upvotes: 1
Views: 3136
Reputation: 247
OK I figured out after some trial and error:
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
from nbconvert import HTMLExporter
# read source notebook
with open('report.ipynb') as f:
nb = nbformat.read(f, as_version=4)
# execute notebook
ep = ExecutePreprocessor(timeout=-1, kernel_name='python3')
ep.preprocess(nb)
# export to html
html_exporter = HTMLExporter()
html_exporter.exclude_input = True
html_data, resources = html_exporter.from_notebook_node(nb)
# write to output file
with open("notebook.html", "w") as f:
f.write(html_data)
Admittedly a lot more work than a single os.system
call, but I'm surprised there are so little native python examples out there...
Upvotes: 8