Sphinx 是一个强大的 Python 文档生成工具,支持 Markdown、自动 API 文档、多格式输出和 CI/CD 集成。本文从零开始介绍如何搭建一个现代化的技术文档站点。

一、Sphinx 是什么

Sphinx 由 Georg Brandl 为 Python 官方文档而开发,是目前 Python 生态中最主流的文档工具。它的核心优势:

  • 多格式输出 — HTML、PDF(LaTeX)、ePub、man page、TXT 等
  • 自动 API 文档 — 从 Python docstring 直接生成参考文档
  • 交叉引用系统 — 跨文档链接,保持结构一致性
  • 扩展生态丰富 — 100+ 社区扩展
  • 与 Read the Docs 无缝集成

二、项目初始化

安装依赖

1
pip install sphinx furo myst-parser sphinx-autobuild sphinx-copybutton

各包作用:

包名 用途
sphinx 核心引擎
furo 现代美观的主题(推荐)
myst-parser 让 Sphinx 支持 Markdown
sphinx-autobuild 本地开发自动刷新
sphinx-copybutton 代码块复制按钮

快速创建项目

1
2
mkdir myproject-docs && cd myproject-docs
sphinx-quickstart docs

回答一系列问题后生成标准结构:

1
2
3
4
5
docs/
├── conf.py # 核心配置
├── index.rst # 入口文件(可改为 .md)
├── Makefile # Linux/Mac 构建命令
└── _static/ # 自定义 CSS/JS

推荐的项目结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
myproject/
├── docs/ # 文档源文件
│ ├── conf.py
│ ├── index.md # Markdown 入口
│ ├── getting-started.md
│ ├── api/
│ │ └── reference.md
│ └── _static/
│ └── custom.css # 自定义样式
├── src/ # Python 源码
├── .github/workflows/
│ └── docs.yml # CI 配置
├── requirements-docs.txt # 文档依赖
└── Makefile # 根目录构建入口

三、使用 Markdown(MyST Parser)

这是最关键的一步。安装 myst-parser 后,Sphinx 可以直接处理 .md 文件。

conf.py 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# extensions
extensions = [
'sphinx.ext.autodoc', # Python docstring -> API 文档
'sphinx.ext.napoleon', # Google/NumPy 风格 docstring
'sphinx.ext.viewcode', # 源码链接
'myst_parser', # Markdown 支持(核心!)
'sphinx_copybutton', # 代码复制按钮
]

# 同时支持 .rst 和 .md
source_suffix = {
'.rst': 'restructuredtext',
'.md': 'markdown',
}

# MyST 扩展功能
myst_enable_extensions = [
"colon_fence", # ::: 语法(admonition)
"linkify", # 自动识别 URL 并生成链接
"substitution", # 变量替换
]

# 中文支持
language = 'zh'

Markdown 文件示例

docs/getting-started.md

1
2
3
4
5
6
# 快速开始

## 安装

```bash
pip install myproject

基本用法

1
2
3
from myproject import hello

hello() # prints "Hello, World!"

[!NOTE]
MyST 支持 GitHub 风格的 admonition(提示框)。

阅读更多

1
2
3
4
5
6
7
8
9
10
11
12
13

### toctree 引用 Markdown

在 `index.rst`(或 `.md`)中:

```rst
.. toctree::
:maxdepth: 2
:caption: 文档目录

getting-started.md
api/reference.md
advanced.md

四、美化 — 主题选择与自定义

主流主题对比

主题 pip 包名 特点
Furo(推荐) furo 现代简洁,深色模式,目前最流行
Read the Docs sphinx-rtd-theme 经典稳定,社区最大
BookTheme sphinx-book-theme Jupyter Book 风格,适合教程
PyData pydata-sphinx-theme PyData 生态标准主题

Furo 主题配置

1
2
3
4
5
6
7
8
# conf.py
html_theme = 'furo'
html_theme_options = {
"light_css_variables": {
"color-brand-primary": "#615cd0",
"color-brand-content": "#7571be",
},
}

自定义 CSS(中文优化)

docs/_static/custom.css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* 中文字体 */
body {
font-family: -apple-system, "Noto Sans SC", "PingFang SC", sans-serif;
}

/* 代码块圆角 */
pre {
border-radius: 8px;
line-height: 1.6;
}

/* 链接样式 */
a.reference.external {
text-decoration: underline;
}

conf.py 中引入:

1
html_css_files = ['custom.css']

五、Git 管理 + CI/CD 自动构建

核心工作流:写 Markdown -> push 到 Git -> CI 自动构建 -> 部署

requirements-docs.txt

1
2
3
4
5
sphinx>=7.0
furo>=2024.1
myst-parser>=2.0
sphinx-autobuild>=2024.0
sphinx-copybutton>=0.5

方案 A:GitHub Pages(推荐)

.github/workflows/docs.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
name: Build and Deploy Docs

on:
push:
branches: [main]
paths:
- 'docs/**'
- '.github/workflows/docs.yml'
pull_request:
branches: [main]

permissions:
contents: read
pages: write
id-token: write

concurrency:
group: pages
cancel-in-progress: true

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.12'

- name: Install dependencies
run: pip install -r requirements-docs.txt

- name: Build Sphinx docs
run: cd docs && sphinx-build -b html . _build/html

- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: docs/_build/html

deploy:
needs: build
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4

方案 B:Read the Docs(最省心)

  1. readthedocs.org 用 GitHub 账号登录
  2. Import 你的仓库 — 自动检测 Sphinx 配置
  3. 每次 push 自动构建,免费获得 yourproject.readthedocs.io 域名

项目根目录添加 .readthedocs.yaml

1
2
3
4
5
6
7
8
9
10
11
12
13
version: 2

build:
os: ubuntu-22.04
tools:
python: "3.12"

sphinx:
configuration: docs/conf.py

python:
install:
- requirements: requirements-docs.txt

方案 C:自托管 Nginx

在 CI deploy 阶段添加 rsync 部署步骤:

1
2
3
4
5
6
7
8
9
- name: Deploy via rsync
uses: burnett01/rsync-deployments@v5
with:
switches: -avz --delete
path: docs/_build/html/
remote_path: /var/www/docs.yourdomain.com/
env:
RSYNC_SSH_KEY: ${{ secrets.DEPLOY_KEY }}
RSYNC_REPOSITORY: deploy@your-server.com

六、本地开发工作流

自动构建 + 热刷新

1
2
3
4
pip install sphinx-autobuild

# 修改 .md 文件后浏览器自动刷新
sphinx-autobuild docs docs/_build/html --open-browser

Makefile(项目根目录)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
SPHINXBUILD   = sphinx-build
SRCDIR = docs
BUILDDIR = docs/_build

.PHONY: clean html livehtml api

clean:
rm -rf $(BUILDDIR)/*

html:
$(SPHINXBUILD) -b html "$(SRCDIR)" "$(BUILDDIR)/html"

livehtml:
sphinx-autobuild "$(SRCDIR)" "$(BUILDDIR)/html" --open-browser

api:
sphinx-apidoc -o docs/api src/
$(SPHINXBUILD) -b html "$(SRCDIR)" "$(BUILDDIR)/html"

七、API 文档自动生成

Python docstring 示例

1
2
3
4
5
6
7
8
9
10
11
# src/myproject/__init__.py
def hello(name: str) -> str:
"""打招呼。

Args:
name: 名字

Returns:
问候语
"""
return f"Hello, {name}!"

conf.py 启用 autodoc + napoleon

1
2
3
4
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.napoleon', # Google/NumPy 风格 docstring
]

Markdown 中引用 API

1
2
3
## API Reference

```{autofunction} myproject.hello

“””

1
2
3

## 八、完整工作流总结

写 Markdown (.md)
|
v
git add docs/*.md && git commit -m “docs: update”
|
v
git push origin main
|
v
GitHub Actions / Read the Docs 自动触发构建
|
v
Sphinx (MyST parser) 将 .md -> HTML
|
v
部署到 GitHub Pages / RTD / Nginx
|
v
用户访问 https://docs.yourdomain.com

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

## 九、常见问题

### Q: reStructuredText 还是 Markdown?

**推荐 Markdown**。MyST Parser 让 Sphinx 原生支持 Markdown,同时保留了 reST 的交叉引用能力。对于团队协作和非 Python 背景的贡献者,Markdown 的学习成本更低。

### Q: 中文渲染有问题怎么办?

在 `conf.py` 设置 `language = 'zh'`,并在自定义 CSS 中指定中文字体(Noto Sans SC / PingFang SC)。Furo 主题对中文支持较好。

### Q: 如何生成 PDF?

```bash
pip install sphinxcontrib-latexdoc
make latexpdf

需要系统安装 LaTeX 发行版(TeX Live 或 MiKTeX)。

Q: 文档搜索怎么做?

Sphinx 内置 HTML 全文搜索(基于 JavaScript),无需额外配置。如果需要更强大的搜索,可以集成 Algolia DocSearch。

十、推荐扩展清单

扩展 用途
myst-parser Markdown 支持
sphinx.ext.autodoc Python API 自动文档
sphinx.ext.napoleon Google/NumPy docstring
sphinx_copybutton 代码块复制按钮
sphinx-togglebutton 可折叠代码块
sphinx-design Tab、Accordion 等 UI 组件
sphinxcontrib-mermaid Mermaid 图表支持
sphinx.ext.intersphinx 跨项目交叉引用
sphinx-autobuild 本地开发热刷新

总结:Sphinx + MyST Parser + Furo 主题 + GitHub Actions 是目前 Python 生态中最成熟的文档方案组合。Markdown 降低了写作门槛,CI/CD 实现了自动化部署,autodoc 让 API 文档与代码保持同步。