Sphinx文档技能Skill sphinx-docs

Sphinx文档技能是用于自动化生成和管理技术文档的专业工具。它支持Python API自动文档生成、跨项目链接、多格式输出(HTML/PDF/ePub)和主题定制。关键词:Sphinx文档,Python API文档,技术文档生成,自动文档,reStructuredText,交叉引用,文档构建,开源文档工具。

其他 0 次安装 0 次浏览 更新于 2/26/2026

name: sphinx-docs description: Sphinx文档系统专业技能,用于技术文档和API文档编写。配置项目、为Python API生成自动文档、设置跨项目链接的交叉引用、管理扩展以及生成多种输出格式。 allowed-tools: Read, Write, Edit, Bash, Glob, Grep backlog-id: SK-004 metadata: author: babysitter-sdk version: “1.0.0”

Sphinx文档技能

Sphinx文档系统专业技能,用于技术文档和API文档编写。

能力

  • 为各类项目配置conf.py
  • 编写和管理reStructuredText(RST)内容
  • 为Python API文档配置自动文档生成(autodoc)
  • 设置跨项目链接的交叉引用(intersphinx)
  • 创建和管理Sphinx扩展
  • 生成多种输出格式(HTML、PDF、ePub)
  • 主题配置(Read the Docs、Furo)
  • LaTeX和PDF定制

使用场景

在以下情况下调用此技能:

  • 为Python项目设置Sphinx文档
  • 从代码注释(docstrings)生成API文档
  • 配置跨项目引用
  • 创建自定义扩展
  • 生成PDF文档

输入参数

参数 类型 是否必需 描述
action string 初始化、配置、自动文档、构建
projectPath string Sphinx项目路径
outputFormat string html、pdf、epub(默认:html)
theme string sphinx_rtd_theme、furo、alabaster
extensions array 要启用的Sphinx扩展

输入示例

{
  "action": "configure",
  "projectPath": "./docs",
  "theme": "furo",
  "extensions": ["autodoc", "napoleon", "intersphinx"]
}

项目配置

conf.py

# Sphinx文档构建器的配置文件。

import os
import sys

# 为autodoc添加项目根目录到路径
sys.path.insert(0, os.path.abspath('..'))

# -- 项目信息 -----------------------------------------------------

project = '我的项目'
copyright = '2026, 我的组织'
author = '我的团队'
version = '1.0'
release = '1.0.0'

# -- 通用配置 ---------------------------------------------------

extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
    'sphinx.ext.napoleon',
    'sphinx.ext.viewcode',
    'sphinx.ext.intersphinx',
    'sphinx.ext.todo',
    'sphinx.ext.coverage',
    'sphinx.ext.mathjax',
    'sphinx_copybutton',
    'myst_parser',
]

templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

# 源文件后缀
source_suffix = {
    '.rst': 'restructuredtext',
    '.md': 'markdown',
}

# 主文档
master_doc = 'index'

# -- HTML输出选项 -------------------------------------------------

html_theme = 'furo'
html_static_path = ['_static']
html_css_files = ['custom.css']

html_theme_options = {
    'light_css_variables': {
        'color-brand-primary': '#2980b9',
        'color-brand-content': '#2980b9',
    },
    'dark_css_variables': {
        'color-brand-primary': '#3498db',
        'color-brand-content': '#3498db',
    },
    'sidebar_hide_name': False,
    'navigation_with_keys': True,
}

# -- autodoc选项 -----------------------------------------------------

autodoc_default_options = {
    'members': True,
    'member-order': 'bysource',
    'special-members': '__init__',
    'undoc-members': True,
    'exclude-members': '__weakref__',
    'show-inheritance': True,
}

autodoc_typehints = 'description'
autodoc_typehints_format = 'short'

# -- Napoleon选项(Google/NumPy文档字符串风格) --------------------------

napoleon_google_docstring = True
napoleon_numpy_docstring = True
napoleon_include_init_with_doc = True
napoleon_include_private_with_doc = False
napoleon_include_special_with_doc = True
napoleon_use_admonition_for_examples = True
napoleon_use_admonition_for_notes = True
napoleon_use_admonition_for_references = True
napoleon_use_ivar = False
napoleon_use_param = True
napoleon_use_rtype = True
napoleon_use_keyword = True
napoleon_attr_annotations = True

# -- intersphinx选项 -------------------------------------------------

intersphinx_mapping = {
    'python': ('https://docs.python.org/3', None),
    'numpy': ('https://numpy.org/doc/stable/', None),
    'pandas': ('https://pandas.pydata.org/docs/', None),
    'requests': ('https://requests.readthedocs.io/en/latest/', None),
}

# -- autosummary选项 -------------------------------------------------

autosummary_generate = True
autosummary_imported_members = True

# -- todo选项 --------------------------------------------------------

todo_include_todos = True

# -- LaTeX/PDF输出选项 --------------------------------------------

latex_elements = {
    'papersize': 'letterpaper',
    'pointsize': '11pt',
    'preamble': r'''
        \usepackage{charter}
        \usepackage[defaultsans]{lato}
        \usepackage{inconsolata}
    ''',
}

latex_documents = [
    (master_doc, 'myproject.tex', '我的项目文档',
     '我的团队', 'manual'),
]

reStructuredText模式

文档结构

我的项目文档
========================

欢迎来到我的项目文档。

.. toctree::
   :maxdepth: 2
   :caption: 目录:

   installation
   quickstart
   api/index
   changelog

介绍
------------

这是我的项目介绍。

.. note::

   这是一个重要的提示。

.. warning::

   这是一个警告信息。

.. code-block:: python

   from myproject import Client

   client = Client(api_key="your-key")
   result = client.query("Hello")

API文档

API参考
=============

客户端模块
-------------

.. automodule:: myproject.client
   :members:
   :undoc-members:
   :show-inheritance:

.. autoclass:: myproject.Client
   :members:
   :special-members: __init__

.. autofunction:: myproject.utils.helper

自动摘要
-----------

.. autosummary::
   :toctree: generated

   myproject.Client
   myproject.Config
   myproject.utils

交叉引用

交叉引用
----------------

有关设置说明,请参阅 :doc:`installation`。

引用 :ref:`custom-label`。

链接到 :class:`myproject.Client`。

链接到 :meth:`myproject.Client.query`。

链接到 :func:`myproject.utils.helper`。

外部链接到 :py:class:`requests.Session`。

.. _custom-label:

自定义章节
--------------

此章节有一个自定义标签。

Autodoc配置

Python文档字符串(Google风格)

class Client:
    """My Service的API客户端。

    该客户端提供与My Service API交互的方法。

    参数:
        api_key: 用于身份验证的API密钥。
        base_url: API请求的基础URL。默认为生产环境。
        timeout: 请求超时时间(秒)。

    属性:
        session: 底层的HTTP会话。

    示例:
        >>> client = Client(api_key="your-key")
        >>> result = client.query("Hello")
        >>> print(result.text)
        'Hello, World!'

    注意:
        客户端自动处理速率限制。

    异常:
        AuthenticationError: 如果API密钥无效。
    """

    def __init__(
        self,
        api_key: str,
        base_url: str = "https://api.example.com",
        timeout: int = 30
    ):
        self.api_key = api_key
        self.base_url = base_url
        self.timeout = timeout

    def query(self, text: str) -> Response:
        """向API发送查询。

        参数:
            text: 要发送的查询文本。

        返回:
            包含API响应的Response对象。

        异常:
            APIError: 如果API返回错误。
            TimeoutError: 如果请求超时。

        示例:
            >>> response = client.query("天气如何?")
            >>> print(response.status)
            'success'
        """
        pass

主题

Read the Docs主题

# conf.py
html_theme = 'sphinx_rtd_theme'

html_theme_options = {
    'navigation_depth': 4,
    'collapse_navigation': False,
    'sticky_navigation': True,
    'includehidden': True,
    'titles_only': False,
}

Furo主题

# conf.py
html_theme = 'furo'

html_theme_options = {
    'light_logo': 'logo-light.png',
    'dark_logo': 'logo-dark.png',
    'sidebar_hide_name': True,
    'top_of_page_button': 'edit',
}

MyST解析器(Markdown支持)

conf.py配置

extensions = [
    'myst_parser',
]

myst_enable_extensions = [
    'colon_fence',
    'deflist',
    'dollarmath',
    'fieldlist',
    'html_admonition',
    'html_image',
    'replacements',
    'smartquotes',
    'substitution',
    'tasklist',
]

myst_heading_anchors = 3

MyST Markdown

# 我的文档

:::{note}
这是使用MyST语法的提示。
:::

:::{warning}
这是一个警告。
:::

```{code-block} python
:linenos:
:emphasize-lines: 2

def hello():
    print("Hello, World!")

{ref}custom-label


## 工作流程

1. **初始化项目** - 运行sphinx-quickstart
2. **配置** - 编辑conf.py
3. **编写内容** - 创建RST/MD文件
4. **设置autodoc** - 配置API文档
5. **构建** - 生成输出
6. **部署** - 发布文档

## 依赖项

```text
# requirements-docs.txt
sphinx>=7.0.0
sphinx-rtd-theme>=2.0.0
furo>=2024.1.0
sphinx-copybutton>=0.5.0
sphinx-autodoc-typehints>=2.0.0
myst-parser>=2.0.0

CLI命令

# 初始化项目
sphinx-quickstart docs

# 构建HTML
sphinx-build -b html docs docs/_build/html

# 构建PDF(通过LaTeX)
sphinx-build -b latex docs docs/_build/latex
cd docs/_build/latex && make

# 构建并自动重载
sphinx-autobuild docs docs/_build/html

# 检查损坏的链接
sphinx-build -b linkcheck docs docs/_build/linkcheck

应用的最佳实践

  • 使用Napoleon处理Google/NumPy文档字符串
  • 启用intersphinx进行交叉引用
  • 配置autodoc类型提示
  • 添加viewcode用于源代码链接
  • 使用MyST支持Markdown
  • 为API文档生成自动摘要

参考

目标流程

  • api-doc-generation.js
  • sdk-doc-generation.js
  • docs-versioning.js