Monday, December 4, 2023

How to execute python code in a sphinx document

This is a note for myself but others might find useful.  I needed to execute python in a sphinx document at build time. 

The package that comes up in a search doesn't work with Python 3.x. 

Instead I found 


which does work with Python 3.11. (I'm running Windows 10)

Install it by typing the following on the command line

pip install sphinx-execute-code-python3 

To use it don't forget to add this line to your sphinx conf.py file:

extensions.append('sphinx_execute_code')

Here is an example in a rst file:

.. execute_code::

    a = [1,2,3]
    b = [4,5,6]
    print ('Printing a list: ', a + b)

The docs have various options you can use.

No comments: