Sphinx Documentation Generator

9.1.0 · active · verified Sat Mar 28

Sphinx is a powerful Python documentation generator that creates intelligent and beautiful documentation from reStructuredText or Markdown sources. It is currently at version 9.1.0, with major releases typically annually and patch releases occurring frequently. It leverages Docutils for parsing and processing text, and is highly extensible.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically build Sphinx documentation for a Python project. It creates a minimal project structure including `conf.py` (configuration), `index.rst` (main document), `my_module.py` (Python code), and `modules.rst` (autodoc entry), then invokes Sphinx to generate HTML output.

import os
import shutil
from sphinx.application import Sphinx
from sphinx.util.docutils import docutils_namespace

# Define paths
source_dir = "docs_src"
build_dir = os.path.join(source_dir, "_build")
output_html_dir = os.path.join(build_dir, "html")
doctrees_dir = os.path.join(build_dir, ".doctrees")

# Clean up previous build if exists
if os.path.exists(source_dir):
    shutil.rmtree(source_dir)

# Create source directories
os.makedirs(source_dir)
os.makedirs(os.path.join(source_dir, "_static"))
os.makedirs(os.path.join(source_dir, "_templates"))

# Create a simple Python module to document
module_path = os.path.join(source_dir, "my_module.py")
with open(module_path, "w") as f:
    f.write("""
def greet(name: str) -> str:
    """Greets the given name.

    :param name: The name to greet.
    :type name: str
    :returns: A greeting string.
    :rtype: str
    """
    return f"Hello, {name}!"

class Greeter:
    """A simple greeter class.

    :param greeting_word: The word to use for greeting.
    :type greeting_word: str
    """
    def __init__(self, greeting_word: str = "Hello"):
        self.greeting_word = greeting_word

    def wave(self, name: str) -> str:
        """Waves to the given name.

        :param name: The name to wave to.
        :type name: str
        :returns: A waving greeting.
        :rtype: str
        """
        return f"{self.greeting_word}, {name}! *waves*"
""")

# Create conf.py
conf_path = os.path.join(source_dir, "conf.py")
with open(conf_path, "w") as f:
    f.write("""
import os
import sys
sys.path.insert(0, os.path.abspath('.'))

project = 'My Sphinx Project'
copyright = '2026, My Name'
author = 'My Name'
release = '0.1'

extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.napoleon', # for Google/NumPy style docstrings
]

html_theme = 'alabaster'
""")

# Create index.rst
index_path = os.path.join(source_dir, "index.rst")
with open(index_path, "w") as f:
    f.write("""
.. _index:

Welcome to My Sphinx Project!
================================

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   modules

This is a sample project to demonstrate Sphinx documentation.
""")

# Create modules.rst for autodoc
modules_path = os.path.join(source_dir, "modules.rst")
with open(modules_path, "w") as f:
    f.write("""
Module Documentation
====================

.. automodule:: my_module
   :members:
   :undoc-members:
   :show-inheritance:
""")

try:
    # Initialize and build the Sphinx application
    # Use docutils_namespace to ensure clean Docutils state
    with docutils_namespace():
        app = Sphinx(
            sourcedir=source_dir,
            confdir=source_dir,
            outdir=output_html_dir,
            doctreedir=doctrees_dir,
            buildername="html",
            freshenv=True,  # Re-read all files
            warningiserror=False,
            # status=sys.stdout, # Uncomment to see build status in console
            # warning=sys.stderr, # Uncomment to see warnings in console
        )
        app.build(force_all=True)
    print(f"Documentation built successfully in {output_html_dir}")
    print(f"Open file://{os.path.abspath(output_html_dir)}/index.html in your browser.")
except Exception as e:
    print(f"Error building documentation: {e}")
    import traceback
    traceback.print_exc()
finally:
    # Optional: Clean up created files and directories
    # if os.path.exists(source_dir):
    #     shutil.rmtree(source_dir)
    pass

view raw JSON →