SuperAPI AI 工具集

sphinx

写作与研究

查看项目

更新于 10-16 04:16

技能介绍

该技能围绕 Sphinx 为 Python 项目生成完整文档。

用途

当需要构建 Python 库或包文档、从文档字符串自动生成 API 参考、输出 PDF 或 ePub、使用 Google 或 NumPy 风格文档字符串、在多个文档项目之间建立交叉引用、部署到 Read the Docs、构建科学或学术文档、制作带版本的 API 文档、处理大型 Python 代码库或需要国际化文档时使用。不适用于:不含 API 文档的简单项目文档(用 MkDocs)、非 Python 项目(用 MkDocs 或 Docusaurus)、文档中需要 React 组件(用 Docusaurus)、仅做快速格式转换(用 Pandoc)、制作演示幻灯片(用 Marp)或协作式 wiki 文档(用 GitBook)。

环境要求与安装

需要 Python 3.8 或更高版本、pip 或 uv 包管理器;PDF 输出需要 LaTeX 发行版;图表可选 Graphviz。安装命令:

pip install sphinx

含常用扩展:

pip install sphinx \
    sphinx-rtd-theme \
    sphinx-autodoc-typehints \
    sphinx-copybutton \
    myst-parser \
    sphinxcontrib-mermaid

使用 uv:

uv pip install sphinx sphinx-rtd-theme sphinx-autodoc-typehints

PDF 输出:

pip install sphinx latexmk

另需 LaTeX 发行版(Ubuntu 上为 texlive-full,macOS 上为 MacTeX)。验证安装:

sphinx-build --version

主要能力

  1. 项目初始化:使用 sphinx-quickstart docs 生成项目结构(source/conf.py、index.rst、_static、_templates 以及 build 输出目录),也可手动创建 docs/source 与 docs/build。
  2. 基础配置(conf.py):可配置项目信息、extensions(包括 autodoc、napoleon、viewcode、intersphinx、todo、coverage、mathjax、githubpages、sphinx_rtd_theme、sphinx_copybutton、myst_parser)、source_suffix、master_doc、HTML 主题(sphinx_rtd_theme)及主题选项、autodoc 选项、napoleon 选项、intersphinx 映射、LaTeX/PDF 与 EPUB 输出选项。
  3. 索引与目录:通过 index.rst 使用 toctree 组织 Getting Started、User Guide、API Reference、Development 等章节,并提供 genindex、modindex、search 入口。
  4. Autodoc 自动 API 文档:从模块、类与方法文档字符串中提取 API,示例文档包含 DataProcessor 类(init、load、process、save)与 calculate_metrics 函数,支持 Example、Raises、Returns、See Also、Note、Warning 等字段。
  5. 生成 API 文档:使用 sphinx-apidoc -o docs/source/api src/mypackage -f -e -M 自动生成桩文件(-o 输出目录,-f 强制覆盖,-e 每模块独立页面,-M 模块优先排序,-d 2 目录深度);构建 HTML 使用 sphinx-build -b html docs/source docs/build/html,可加 -v 输出详细日志。
  6. MyST Markdown 支持:启用 myst_parser 并配置 myst_enable_extensions(amsmath、colon_fence、deflist、dollarmath、fieldlist、html_admonition、html_image、replacements、smartquotes、strikethrough、substitution、tasklist)、myst_heading_anchors、myst_footnote_transition;支持代码块、提示框、交叉引用、数学公式、任务列表与定义列表。
  7. Intersphinx 交叉引用:配置 intersphinx_mapping 映射 python、numpy、pandas、scipy、matplotlib、sklearn 等文档站点,并设置 intersphinx_timeout,可在文档中通过 :class:、:func:、:meth: 等角色引用外部对象。
  8. 多输出格式:构建 HTML、PDF(sphinx-build -b latex 后 make)以及 ePub。

使用方式

按上述步骤安装依赖、初始化项目、编写 conf.py 与 index,编写带文档字符串的源码,使用 sphinx-apidoc 生成 API 桩文件,再通过 sphinx-build 生成目标格式文档。

适用场景

适用于需要从文档字符串自动生成 API 参考、输出多格式、跨项目引用、部署到 Read the Docs、带版本管理、面向科学计算或大型代码库的 Python 项目文档。

限制

不适用于无 API 文档的简单项目、非 Python 项目、需要 React 组件的文档、仅做格式转换、演示幻灯片或协作式 wiki。PDF 输出依赖 LaTeX 发行版。关于收费、价格与具体平台效果,资料暂未提供。