Sphinx 和 Read the Docs 文档托管

FreeGuideOnline 最新 2026-07-10

介绍

这是一个示例项目,展示如何使用 Sphinx 构建文档。

  • 特点一:易于上手
  • 特点二:支持 Markdown
  • 特点三:自动部署到 Read the Docs

**toctree** 会自动根据文件标题生成侧边导航栏,层级关系一目了然。

### 3.3 本地预览文档

```bash
# 在 docs/ 目录下执行
make html

构建完成后,打开 docs/build/html/index.html 即可看到与最终托管效果一致的页面。

4. 将项目推送到 Git 仓库

Read the Docs 需要从你的在线 Git 仓库拉取源码,因此确保你的项目托管在 GitHub、GitLab 或 Bitbucket。

git init
git add .
git commit -m "初始化 Sphinx 文档"
git remote add origin https://github.com/你的用户名/项目.git
git push -u origin main

注意:仓库中必须包含 docs/ 目录及 conf.py 文件,RTD 才能正确识别 Sphinx 项目。

5. 连接 Read the Docs 并自动构建

5.1 注册并登录 Read the Docs

访问 readthedocs.org ,使用你的 GitHub/GitLab/Bitbucket 账号授权登录。

5.2 导入项目

  1. 登录后点击右上角 “Import a Project”
  2. RTD 会列出你仓库中所有公开的项目,选择目标项目。
  3. 点击 “+” 图标完成导入。

5.3 配置项目(可选)

导入成功后,进入项目管理面板。你可以修改以下关键设置:

  • 文档语言:与 conf.py 保持一致。
  • Python 环境:如需额外依赖(例如 myst-parser),在 构建环境 中添加一个 requirements.txt 文件。
  • 自定义域名:在 “域名” 设置中绑定你的域名。

为保证构建顺利,建议在仓库根目录创建 .readthedocs.yaml 文件(RTD 新版配置):

# .readthedocs.yaml
version: 2

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

sphinx:
  configuration: docs/source/conf.py
  fail_on_warning: true

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

并在 docs/ 下创建 requirements.txt,列出文档构建所需依赖:

sphinx-rtd-theme
myst-parser