1

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:

  1. Is there an example to convert notebooks to html in native Python?
  2. Is there a compelling reason not to do it?

1 Answer 1

8

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...

Sign up to request clarification or add additional context in comments.

1 Comment

I had to set the encoding of the HTML-file to UTF-8: "with open("output/MEB_SKI_26_analysis.html", "w", encoding="utf") as f:"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.