目前内部建设需要进行sphinx的自动化文档生成,

本文将从 环境搭建,自动化文档,托管,三个地方进行讲解。其他部分的语法请自行查阅。

仅仅只描述 linux平台 or wsl2 平台

1. 环境安装

(git_action) ➜  HelloWorld git:(main) ✗ pip install Sphinx

(git_action) ➜  HelloWorld git:(main) ✗ mkdir docs

(git_action) ➜  HelloWorld git:(main) ✗ cd docs 

(git_action) ➜  docs git:(main) ✗ sphinx-quickstart

其中最核心的文件就是 source 中的 conf.py文件了 贴一下我的这个文件

# for using Read the Docs theme
import sphinx_rtd_theme
import os
import sys

sys.path.insert(0, os.path.abspath("../../src/"))

# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))


# -- Project information -----------------------------------------------------

project = 'sphinx test'
copyright = '2024, heitong'
author = 'heitong'

# The full version, including alpha/beta/rc tags
release = '0.1'


# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = 'zh_CN'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []


# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
# html_theme = 'alabaster'
html_theme = 'sphinx_rtd_theme'

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]


# -- Options for LaTeX output ---------------------------------------------
# 添加如下代码, 使得程序自动在latex文件的导言区加入包引用
latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    #'papersize': 'letterpaper',
    # The font size ('10pt', '11pt' or '12pt').
    #'pointsize': '10pt',
    # Additional stuff for the LaTeX preamble.
    #'preamble': '',
    # Latex figure (float) alignment
    #'figure_align': 'htbp',
    # Using Package for ZH
    "preamble": r"""
\usepackage{ctex}
""",
}


extensions = [
    "sphinx.ext.autodoc",
    "sphinx.ext.napoleon",
]

修改完毕后 , 可以运行生成HTML

(git_action) ➜  docs git:(main) ✗ make html     

得到如下的目录结构,直接在浏览器打开index.html 即可。

2. 自动化文档生成

其中的文档字符串需要用reStructureText语法

reStructureText语法类似于这样:

"""[Summary]

:param [ParamName]: [ParamDescription], defaults to [DefaultParamVal]
:type [ParamName]: [ParamType](, optional)
...
:raises [ErrorType]: [ErrorDescription]
...
:return: [ReturnDescription]
:rtype: [ReturnType]
"""
# src/my_module.py


# def add(a, b):
#     """Return the sum of a and b."""
#     return a + b


# def subtract(a, b):
#     """Return the difference between a and b."""
#     return a - b


def add(a, b):
    """
    Add two numbers.

    :param a: The first number.
    :type a: int or float
    :param b: The second number.
    :type b: int or float
    :return: The sum of `a` and `b`.
    :rtype: int or float

    :Example:

    >>> add(1, 2)
    3
    >>> add(1.5, 2.5)
    4.0
    """
    return a + b


def multiply(a, b):
    """
    Multiply two numbers.

    :param a: The first number.
    :type a: int or float
    :param b: The second number.
    :type b: int or float
    :return: The product of `a` and `b`.
    :rtype: int or float

    :Example:

    >>> multiply(2, 3)
    6
    >>> multiply(1.5, 2)
    3.0
    """
    return a * b

效果展示:

确保在执行代码的时候 在docs目录中。

(git_action) ➜  docs git:(main) ✗ sphinx-apidoc -o ./source ../src
(git_action) ➜  docs git:(main) ✗ make html   

注意事项 确保代码的环境都是正确的,不然错误的部分是不会生成文档的。 主要是image_processing的代码中没有安装torch。

(git_action) ➜  docs git:(main) ✗ make html                       
Running Sphinx v7.3.7
loading translations [zh_CN]... done
loading pickled environment... done
building [mo]: targets for 0 po files that are out of date
writing output... 
building [html]: targets for 0 source files that are out of date
updating environment: 1 added, 0 changed, 0 removed
reading sources... [100%] src.apis
WARNING: autodoc: failed to import module 'image_processing' from module 'src.apis'; the following exception was raised:
No module named 'torch'
looking for now-outdated files... none found
pickling environment... done
checking consistency... /root/hgln_project/HelloWorld/docs/source/modules.rst: WARNING: document isn't included in any toctree
/root/hgln_project/HelloWorld/docs/source/src.apis.rst: WARNING: document isn't included in any toctree
done
preparing documents... done
copying assets... copying static files... done
copying extra files... done
done
writing output... [100%] src.apis
generating indices... genindex py-modindex done
writing additional pages... search done
dumping search index in Chinese (code: zh)... done
dumping object inventory... done
build succeeded, 3 warnings.

The HTML pages are in build/html.

部署

参考资料

https://sphinx-rtd-tutorial.readthedocs.io/en/latest/sphinx-quickstart.html