Jupyter Notebook Tools for Sphinx - a Sphinx extension that provides a source parser for .ipynb files with custom directives
—
Core functionality for converting Jupyter notebooks to reStructuredText with support for execution, custom templates, and resource management. This module handles the parsing and transformation of notebook content for Sphinx documentation generation.
Converts Jupyter notebooks to reStructuredText using nbconvert with custom templates and execution support.
class Exporter(nbconvert.RSTExporter):
"""
Convert Jupyter notebooks to reStructuredText.
Uses nbconvert to convert Jupyter notebooks to a reStructuredText
string with custom reST directives for input and output cells.
Notebooks without output cells are automatically executed before conversion.
"""
def __init__(self, execute='auto', kernel_name='', execute_arguments=[],
allow_errors=False, timeout=None, codecell_lexer='none'):
"""
Initialize the Exporter.
Parameters:
- execute: str, execution mode ('auto', 'always', 'never')
- kernel_name: str, Jupyter kernel name for execution
- execute_arguments: list, arguments for kernel execution
- allow_errors: bool, allow errors during execution
- timeout: int, execution timeout in seconds
- codecell_lexer: str, syntax highlighter for code cells
"""
def from_notebook_node(self, nb, resources=None, **kw):
"""
Convert notebook node to RST string with resources.
Parameters:
- nb: NotebookNode, notebook to convert
- resources: dict, conversion resources and metadata
- **kw: additional keyword arguments
Returns:
tuple: (rststring, resources) - converted RST and updated resources
"""Usage example:
from nbsphinx import Exporter
import nbformat
# Load notebook
with open('example.ipynb', 'r') as f:
nb = nbformat.read(f, as_version=4)
# Create exporter with custom settings
exporter = Exporter(
execute='auto',
allow_errors=False,
timeout=30,
codecell_lexer='python'
)
# Convert notebook
rststring, resources = exporter.from_notebook_node(nb)
print(rststring) # Converted reStructuredTextSphinx source parser that integrates notebooks into the Sphinx build system with custom format support.
class NotebookParser(rst.Parser):
"""
Sphinx source parser for Jupyter notebooks.
Uses nbsphinx.Exporter to convert notebook content to a
reStructuredText string, which is then parsed by Sphinx's built-in
reST parser.
"""
supported = ('jupyter_notebook',)
def get_transforms(self):
"""List of transforms for documents parsed by this parser."""
def parse(self, inputstring, document):
"""
Parse *inputstring*, write results to *document*.
Parameters:
- inputstring: str, JSON representation of notebook or text from translation
- document: docutils document node to populate
Notes:
- If nbsphinx_custom_formats is specified, input is converted to notebook format
- Supports custom conversion functions for different file formats
- Automatically executes notebooks based on configuration
- Handles resource management for output files and images
"""Usage is automatic when files with .ipynb extension are processed by Sphinx.
Functionality for extracting and managing thumbnail images from notebook outputs for gallery displays.
def _extract_thumbnail(cell, output_index):
"""
Extract thumbnail from notebook cell output.
Parameters:
- cell: NotebookNode, notebook cell with outputs
- output_index: int, index of output to extract from
Returns:
str: File extension for extracted thumbnail
Raises:
_ExtractThumbnailException: If thumbnail cannot be extracted
"""
class _ExtractThumbnailException(Exception):
"""
Internal exception thrown by _extract_thumbnail().
Raised when thumbnail extraction fails due to missing or
incompatible output data in notebook cells.
"""Usage example:
# Thumbnail extraction is handled automatically during conversion
# Can be controlled via notebook metadata:
# In notebook cell metadata:
{
"nbsphinx-thumbnail": {
"output-index": 0,
"tooltip": "Custom tooltip text"
}
}
# Or via cell tags:
{
"tags": ["nbsphinx-thumbnail"]
}Custom exception types for notebook processing errors.
class NotebookError(sphinx.errors.SphinxError):
"""
Error during notebook parsing.
Attributes:
- category: str, error category ('Notebook error')
"""Usage example:
try:
# Notebook processing code
rststring, resources = exporter.from_notebook_node(nb)
except NotebookError as e:
print(f"Notebook processing failed: {e}")
# Handle error appropriatelyThe notebook conversion uses a custom RST template that defines how different notebook elements are rendered:
nbinput directives with syntax highlightingnboutput directives with format-specific handlingThe template system allows customization of the conversion process while maintaining compatibility with Sphinx's RST processing pipeline.
Install with Tessl CLI
npx tessl i tessl/pypi-nbsphinx