sphinxcontrib-run documentation

sphinxcontrib-run registers a new .. run:: directive to execute code dynamically while building a sphinx documentation. It can be used to generate documentation artifacts such as figures or to insert dynamic content.

Example

"""
.. run::

    from example import square_text_50

    lorem = (
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
        + " Pellentesque faucibus vestibulum est id consequat."
        + " Cras sed enim sed ex maximus blandit."
    )
"""


def square_text_50(text):
    """Wrap text to 40 columns.

    .. run::

        print("::")
        print("")
        for line in square_text_50(lorem):
            print("    " + line)
        print("")
    """
    for i in range(0, len(text), 50):
        yield text[i : i + 50]

renders as:

example.square_text_50(text)

Wrap text to 40 columns.

Lorem ipsum dolor sit amet, consectetur adipiscing
 elit. Pellentesque faucibus vestibulum est id con
sequat. Cras sed enim sed ex maximus blandit.

Installation

Install the package:

pip install sphinxcontrib-run
# or
uv add --dev sphinxcontrib-run

Then add the extension to the sphinx configuration:

extensions = [
   ...
   "sphinxcontrib.run"
]

Usage

.. run::

Directive to execute code.

The interpreter persists through the scope of a document, so imports and global variables can be reused across multiple directives. More specifically, the scope corresponds to a single .rst file (or its parent when included or generated by autodoc).

Note

When using autodoc, the :member-order: option will influence the order in which directives are execute.

The code can generate content to insert at the position of the directive by printing to the standard output.

Options

:group:

Specify a group name. The commands from each group are run in separate processes.

:hidden:

The content printed by the commands to the standard output will be ignored.