使用 Sphinx 生成代码文档
初始配置
-
安装依赖:
pip install sphinx -
创建文档项目:
sphinx-quickstart docs- Separate source and build directories: y
-
编辑首页:
docs/source/index.rst:Welcome to Lumache's documentation! =================================== **Lumache** (/lu'make/) is a Python library for cooks and food lovers that creates recipes mixing random ingredients. It pulls data from the `Open Food Facts database <https://world.openfoodfacts.org/>`_ and offers a *simple* and *intuitive* API. .. note:: This project is under active development.===:一级标题---:二级标题**emph**:加粗*ital*:斜体``code``:代码块<https://example.com>:链接.. note:::使用 note 指令..:注释
-
编辑配置文件:
docs/source/conf.py:html_theme = 'furo' # 修改 HTML 主题pip install furo # 安装主题 -
编译文档:
make -C docs html -
查看文档:
open docs/build/html/index.html
添加文档
-
创建新文档:
docs/source/usage.rstUsage ===== Installation ------------ To use Lumache, first install it using pip: .. code-block:: console (.venv) $ pip install lumache -
将新文档插入到文档目录树:
docs/source/index.rst:Contents -------- .. toctree:: usage -
编译文档:
make -C docs html
从代码生成文档
-
编辑配置:
docs/source/conf.py:import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[2])) # 引入项目根目录 # 添加扩展 extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary' ] -
编辑源代码:
lumache.py:def get_random_ingredients(kind=None): """ Return a list of random ingredients as strings. :param kind: Optional "kind" of ingredients. :type kind: list[str] or None :raise lumache.InvalidKindError: If the kind is invalid. :return: The ingredients list. :rtype: list[str] """ return ["shells", "gorgonzola", "parsley"] class InvalidKindError(Exception): """Raised if the kind is invalid.""" pass -
编辑文档:
docs/source/api.rst:API === .. autosummary:: :toctree: generated lumachedocs/source/index.rst:Contents -------- .. toctree:: usage apidocs/source/usage.rstCreating recipes ---------------- To retrieve a list of random ingredients, you can use the ``lumache.get_random_ingredients()`` function: .. autofunction:: lumache.get_random_ingredients The ``kind`` parameter should be either ``"meat"``, ``"fish"``, or ``"veggies"``. Otherwise, :py:func:`lumache.get_random_ingredients` will raise an exception. .. autoexception:: lumache.InvalidKindError -
编译文档:
make -C docs html

浙公网安备 33010602011771号