I found two ways to do this:
The way that most faithfully reproduces $ jupyter nbconvert nb.ipynb --template toc2
involves setting the HTMLExporter().template_file
attribute with the toc2.tpl
template file.
- The main trick is to find where this file lives on your system. For me it was
<base filepath>/Anaconda3/Lib/site-packages/jupyter_contrib_nbextensions/templates/toc2.tpl
- Full code below:
from nbconvert import HTMLExporter
from nbconvert.writers import FilesWriter
import nbformat
from pathlib import Path
input_notebook = "My_notebook.ipynb"
output_html ="My_notebook"
toc2_tpl_path = "<base filepath>/Anaconda3/Lib/site-packages/jupyter_contrib_nbextensions/templates/toc2.tpl"
notebook_node = nbformat.read(input_notebook, as_version=4)
exporter = HTMLExporter()
exporter.template_file = toc2_tpl_path # THIS IS THE CRITICAL LINE
(body, resources) = exporter.from_notebook_node(notebook_node)
write_file = FilesWriter()
write_file.write(
output=body,
resources=resources,
notebook_name=output_html
)
An alternative approach is to use the TocExporter
class in the nbconvert_support
module, instead of HTMLExporter
.
- However, this mimics the command line expression
jupyter nbconvert --to html_toc nb.ipynb
rather than instead setting the template of the standard HTML export method
- The main issue with this approach is that there does not seem to be a way to embed figures with this method, which is the default for the template-based method above
- However, if figure embedding doesn't matter, this solution is more flexible across different systems since you don't have to track down different file paths for
toc2.tpl
- Here is an example below:
from nbconvert import HTMLExporter
from nbconvert.writers import FilesWriter
import nbformat
from pathlib import Path
from jupyter_contrib_nbextensions.nbconvert_support import TocExporter # CRITICAL MODULE
input_notebook = "My_notebook.ipynb"
output_html ="My_notebook"
notebook_node = nbformat.read(input_notebook, as_version=4)
exporter = TocExporter() # CRITICAL LINE
(body, resources) = exporter.from_notebook_node(notebook_node)
write_file = FilesWriter()
write_file.write(
output=body,
resources=resources,
notebook_name=output_html
)
As a final note, I wanted to mention my motivation for doing this to anyone else who comes across this answer. One of the machines I work on uses Windows, so to get the command prompt to run jupyter commands requires some messing with the Windows PATH environment, which was turning in to a headache. I could get around this by using the Anaconda prompt, but this requires opening up the prompt and typing in the full command every time. I could try to write a script with os.system()
, but this calls the default command line (Windows command prompt) not the Anaconda prompt. The methods above allow me to convert Jupyter notebooks to HTML with TOCs and embedded figures by running a simple python script from within any notebook.