Sphinx
Generating Sphinx Docs for Python
Step-by-step guide:
-
Install Sphinx: Install Sphinx in your Python environment using pip.
pip install sphinx -
Initialize the docs directory: Run
sphinx-quickstartin your project directory to generate the base files for the documentation.mkdir docs cd docs sphinx-quickstartWhen prompted, you can press enter to accept the default values for most options. Make sure to say yes (
y) to the "autodoc" extension, which is used to generate documentation from docstrings. -
Configure Sphinx: In the
conf.pyfile generated bysphinx-quickstart, add the path to your project to the system path.import os import sys sys.path.insert(0, os.path.abspath('../src'))Also, add
'sphinx.ext.autodoc'to the list of extensions. -
Install and Configure the MyST parser: If you want to use Markdown for some or all of your documentation, you'll need to install the MyST parser and add it to your list of extensions:
pip install myst-parserThen add it to the
extensionslist inconf.py:extensions = [ 'sphinx.ext.autodoc', 'myst_parser', ] -
Write reStructuredText and Markdown files: Create
.rstand/or.mdfiles for each of your modules to tell Sphinx what to document. These files should be in the same directory as yourconf.pyfile. For a module namedmy_module, the contents ofmy_module.rstcould be:my_package.my_module module ========================== .. automodule:: my_package.my_module :members:Update the
index.rstfile to include your module in the table of contents tree (toctree).To link to other documentation files, use the
:doc:role in reStructuredText files and standard Markdown links in Markdown files. -
Install and configure a theme: To use the "Read the Docs" theme, first install it with pip:
pip install sphinx_rtd_themeThen, add it to the list of extensions and set it as the theme in
conf.py:extensions = [ 'sphinx.ext.autodoc', 'sphinx_rtd_theme', 'myst_parser', # if you're using Markdown ] html_theme = 'sphinx_rtd_theme' -
Generate the HTML documentation: Now you can generate the HTML documentation with the
make htmlcommand.make htmlIf everything is set up correctly, Sphinx should generate the documentation in the
_build/htmldirectory. Open theindex.htmlfile in a web browser to view your documentation.
Remember that every time you update your code or .rst/.md files, you should re-run make html to update the HTML documentation.
Additional Notes and Gotchas
- Standard practice is to keep docs outside of
src. - You must cd to docs dir to make html
cd docsthenmake html.make docs/htmldoes not work. - You can use the VsCode Extension live server on the
index.rstto preview the docs.
Backlinks