sphinx-exec-directive
allows you to write code blocks in reStructuredText files, execute them during Sphinx compilation, and display the output directly within the generated documentation.
The 'default' code language is Python, but there is some limited support for other languages right now (see the extension documentation for more info). If you want a particular language to be added, please feel free to raise an issue!
This is based very strongly on matplotlib's plot_directive
extension, but is used for running code instead of generating plots.
pip install sphinx-exec-directive
Then, inside your Sphinx conf.py
, add sphinx_exec_directive
to your list of extensions (note: underscores not hyphens).
extensions = [
sphinx_exec_directive,
# other extensions...
]
.. exec::
print(1 + 1)
Place the above into your RST file and Sphinx will generate two literal blocks when compiling, one with the 'input' source code, and one with the captured stdout:
For further details and usage examples, please see the documentation. It contains quite a few exec directives, so you get to see some in the wild!