Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include a commented Python script into a Sphinx-generated documentation

I work on a Python project whose html-online-documentation I generate using Sphinx. The project also contains several Python scripts showing examples about how to use the tools contained, while all of these files are commented extensively to explain what it going on.

I would now like to include these example scripts in my documentation as well so that I can reuse them as a tutorial, and do not have to alter both the examples and the tutorial when I apply changes to the code, but can have both things directly together and always up-to-date.

I imagine Sphinx to parse the scripts from top to bottom, and generate an html file out of it, while the comments are shown as text on the page and the code is depicted within code blocks.

Does anyone of you know how this could be achieved?

Thank your very much for your help!

like image 806
mindm49907 Avatar asked Jun 21 '15 12:06

mindm49907


1 Answers

You can use the viewcode sphinx extension for your purpose.

For example:

Say you have a module - BeautifulSoup.py

and you create a file BeautifulSoup.rst with the following content (to generate the documentation for the module)

.. automodule:: BeautifulSoup
    :members:

Once you enable this extension in conf.py, like below, and build html:

extensions = ['sphinx.ext.autodoc', 
    'sphinx.ext.pngmath',
    'sphinx.ext.viewcode',
    ]

You will see a link called [source] next to the class and members, like this:

enter image description here

Clicking on the [source] takes you to the html of your source. Sphinx essentially generates a HTML of your code in the following directory

_build/html/_modules/BeautifulSoup.html

So you can even put an explicit link to this page in your tutorials.

The only thing this will not do is split the doc strings into regular text and code into code blocks. But it should solve your problem of not having to update the tutorial and the code every time.

like image 185
Subbdue Avatar answered Oct 13 '22 12:10

Subbdue