3. Sphinx 使用笔记#
目录
- sphinx 环境搭建:
- 创建虚拟环境:
pdm venv create --force --with venv --with-pip D:\Python\Python310\python.exe --prompt=venv_sphinx
- 安装依赖库:
pdm install --group sphinx
[project.optional-dependencies] sphinx = [ "sphinx>=7.2.6", "sphinx-rtd-theme>=2.0.0", "sphinx-design>=0.5.0", "sphinx-copybutton>=0.5.2", "myst-nb>=1.0.0", "sphinx-book-theme>=1.1.2", "sphinxcontrib-mermaid>=0.9.2", "esbonio>=0.16.4", ]
- 创建虚拟环境:
D:\Python\Python310\python.exe -m venv .venv
- 安装依赖库:
pip install -r requirements_sphinx.txt
3.1. sphinx-quickstart#
安装了 Sphinx 后,使用命令行工具: sphinx-quickstart 就可以快速创建 sphinx 工程。
工程创建后,会在源文件目录下创建: conf.py 配置文件。根目录下创建: Makefile 和 make.bat 文件。
可以通过以下两种方式编译工程生成 html 文件:
根目录下运行: ./make.bat html
根目录下运行: mingw32-make html
3.2. Sphinx 插件#
插件名 |
主工功能 |
|
页面布局设计 |
||
Markdown 文件解析器 |
||
Jupyter notebooks 解析器和 Markdown 解析器 |
构建于 myst-parser 基础之上 |
|
Jupyter notebooks 解析器 |
需要安装 pandoc 软件 |
|
sphinx-copybutton |
给源代码添加复制按钮 |
|
sphinxcontrib-mermaid |
mermaid 绘图支持 |
|
sphinx-rtd-theme |
readthedocs 主题 |
|
sphinx-book-theme |
主题 |
|
esbonio |
VsCode 预览用 |
|
jieba |
Sphinx 中文内容搜索 |
注意
myst-parser 跟 myst-nb 插件同时开启时会报 .md 已注册
的错误,所以个人建议只按 myst-nb 即可
3.3. VsCode 编辑环境#
插件名 |
备注 |
---|---|
|
|
|
上面2个插件可以任选其一安装。对比后个人觉得安装 Esbonio 预览更为好一些
3.4. sphinx.ext.autodoc#
该扩展插件主要用于从 python 源文件中提取文本文档。 autodoc官方参考文档
- 如果在 conf.py 文件的上级目录的src目录下有如下 python 源文件:
class Foo: """Docstring for class Foo.""" #: Doc comment for class attribute Foo.bar. #: It can have multiple lines. bar = 1 flox = 1.5 #: Doc comment for Foo.flox. One line only. baz = 2 """Docstring for class attribute Foo.baz.""" def __init__(self): #: Doc comment for instance attribute qux. self.qux = 3 self.spam = 4 """Docstring for instance attribute spam.""" def func(arg1, arg2): """Summary line. Extended description of function. Args: arg1 (int): Description of arg1 arg2 (str): Description of arg2 Returns: bool: Description of return value """ return True
- 在 conf.py 文件中添加如下配置:
sphinx-autodoc 搜索 python 源文件的目录
import sys,os sys.path.append(os.path.abspath('../src'))
开启 autodoc 相关插件
extensions = [ 'sphinx.ext.autodoc', # 从源文件中提取文档内容 'sphinx.ext.napoleon', # google 风格的文档注释 'sphinx.ext.viewcode', # 显示源代码 ]
- 在 index.rst 中添加如下内容:
.. automodule:: Foo :members: :member-order: bysource
- index 页面将会多出如下内容来:
3.4.1. sphinx-apidoc#
sphinx-apidoc 是一个快速从源文件中提取文档的终端工具。
它是上面 sphinx.ext.autodoc 的一个补充,用于将源代码中的文档转换成 .rst
文件。
还是上面的例子,我们在终端执行如下命令:
pdm run sphinx-apidoc -o ./doc/api ./src */pick*
将会在 doc 目录下创建一个 api 目录, 该目录下包含了我们指定的模块对应的 .rst 文件
命令运行后的目录树:
.
├── doc
│ ├── _build
│ │ ├── doctrees
│ │ └── html
│ ├── api
│ │ ├── Foo.rst
│ │ └── modules.rst
│ ├── conf.py
│ ├── index.rst
│ ├── make.bat
│ ├── Makefile
│ └── Tools.rst
├── pdm.lock
├── pdm.toml
├── pyproject.toml
├── README.md
├── requirements-gui.txt
├── requirements-sphinx.txt
├── src
│ ├── __pycache__
│ │ ├── Foo.cpython-310.pyc
│ │ └── pick_records.cpython-310.pyc
│ ├── Foo.py
│ ├── pick_records.py
│ └── SerialNumber.csv
└── tests
└── __init__.py
此时我们只需要在 index.rst 的目录下添加了 api/modules 即可完成所有模块文件档的引入。
注意
该命令同样需要 conf.py 的配置正确才能正常生对 .rst 文件内容
3.5. sphinx.ext.autosummary#
该插件用于生成 函数/方法/属性 的简要说明列表。 autosummary官方参考文档
.. currentmodule:: pick_records
.. autosummary::
:nosignatures:
pick_records.test_123
pick_records.query_fast
此时只是列出了函数的简要说明,鼠标在函数上并没不有点击跳转的效果。文件目录也不会多生成文件
.. currentmodule:: pick_records
.. autosummary::
:nosignatures:
:toctree: Fuctions
pick_records.test_123
pick_records.query_fast
- 函数列表中的函数是还链接的:
- 文件目录同时会生成新的文件:
3.5.1. sphinx-autogen#
sphinx-autogen 是一个通过扫描文件中的 autosummary 指令来生成对应 函数/方法/属性 页面的 rst 文件的命令行工具。
- 示例:
- 工程目录结构
. ├── doc │ ├── _build │ │ ├── doctrees │ │ └── html │ ├── _static │ ├── conf.py │ ├── index.rst │ ├── make.bat │ └── Makefile ├── pdm.lock ├── pdm.toml ├── pyproject.toml ├── README.md ├── requirements-gui.txt ├── requirements-sphinx.txt ├── src │ ├── pick_records.py │ └── SerialNumber.csv └── tests └── __init__.py
./doc/index.rst 内容.. autosummary:: :nosignatures: :toctree: Functions pick_records.query_fast
toctree 选项生成的文件将放到 Fuctions 目录下
在工程根目录下执行
pdm run sphinx-auto ./doc/index.rst
命令, 本应该在./doc/Fuctions/目录下生成 pick_records.query_fast文件。 但现会报错.ext.autosummary.ImportExceptionGroup: no module named pick_records
意思是没找到对应的库。但实际该 python 源文件在 ./src 目录下。似乎 conf.py 的 sys.path.append 没起作用样。 但此时pdm run ./doc/make html
是能成功执行的。- 解决办法:
添加环境变量 PYTHONPATH 再执行命令
> $Env:PYTHONPATH='./src' > pdm run sphinx-autogen .\doc\index.rst
修改 VsCode 配置文件 settings.json
{ "esbonio.sphinx.confDir": "${workspaceFolder}/doc", "esbonio.sphinx.buildDir": "${workspaceFolder}/doc/_build", "terminal.integrated.env.windows": { "pythonPath":"${workspaceFolder};${workspaceFolder}/src;", } }
重启终端再执行
pdm run sphinx-autogen ./doc/index.rst
3.6. Roles#
3.6.1. docutils Roles#
解释性文本(Interpreted text)是由 “ `
“ 包裹的一段文本。
在解释性文本 前/后 可以明确的给出角色标记(role marker), 角色标记由” :
“ 来划分界线。
- 示例:
This is `interpreted text` using the default role. This is :title:`interpreted text` using an explicit role(title). This is `interpreted text`:title: using an explicit role(title).
当没有明确的给出角色标记(:role:)时,将使用默认角色标记( :title-ref: )
可以通过 default-role 指令 来修改默认角色值
- Standard Roles:
-
别名:
:abbr:
示例:
:abbr:`LIFO (last-in, first-out)`
显示为: LIFO
:acronym:
-
示例
:code:`print('Hello world')`
显示为:print('Hello world')
该角色指示器通常用来创建新的自定义角色, 示例如下:
.. role:: python-code(code) :language: python :python-code:`print("Hello World")`
显示效果:
print("Hello World")
-
跟内联标记
*
作用一样显示斜体*text*
显示为: text ,:emphasis:`text`
也显示为: text -
备注
跟内联标记
``
作用一致,但略有不同``text \ and \ backslashes``
显示为text \ and \ backslashes
而
:literal:`text \ and \ backslashes`
显示 为text and backslashes
:math:
:pep-reference:
:rfc-reference:
:strong:
:subscript:
:superscript:
:title-reference:
-
- Specialized Roles:
:raw:
- Custom Roles:
通过
role
指令来自定义 raw-html 如下:.. role:: raw-html(raw) :format: html 这是 `raw-html` :raw-html:`<mark> 自定义角色 </mark>` 修饰的内容,
这是 raw-html 自定义角色 修饰的内容,
3.7. sphinx.ext.intersphinx#
PyGC_Enable()
sphinx-hoverxref
is a Sphinx extension to show a floating window (tooltips or modal dialogues) on the cross references of the documentation embedding the content of the linked section on them. With sphinx-hoverxref
, you don’t need to click a link to see what’s in there.
待处理
intersphinx 使用场景还没怎么搞清楚
3.8. 使用心得#
3.8.1. 带复选框的任务列表#
.. raw:: html
<ol>
<li> <input type="checkbox" disabled="disabled" checked="checked"> 任务1 </li>
<li> <input type="checkbox" disabled="disabled" > 任务2 </li>
</ol>
<hr/>
<ul>
<li> <input type="checkbox" disabled="disabled" checked="checked"> 任务1 </li>
<li> <input type="checkbox" disabled="disabled" > 任务2 </li>
</ul>
- 任务1
- 任务2
- 任务1
- 任务2
跟 Markdown 的任务复选框写法 [1] 更为复杂些。
另一种办法就是直接用使用 emoji ✔️ 和 ❌ 定写:
👉✔️任务1💯✌️
👉❌任务2⁉️⚠️
✔️ 任务1
❌ 任务2
|:heavy_check_mark:| ✔️
|:x:| ❌ ⚠️
3.8.2. raw-html 应用#
基本思路是采用 自定义 Roles 来实现:
我们将 raw-html Role 定义放在一个公共文件 global.rst [2] 中,
在文件开头我们使用 .. include:: ../global.rst
。
这样 我们就可以直接使用 raw-html Role 了。
- 示例:
- 源内容:
- 示例 :raw-html:`<mark style="background:lightgreen;">浅绿底色` 文本 - 示例 :raw-html:`<span style="background:None;text-decoration:line-through double red;border:solid blue 2px;border-radius:5px">添加外框及双删除线` 文本 - 示例 :raw-html:`<del> 只加删除线` 的文本 - 示例 :raw-html:`<u> 带下划线 </u>` 的文本
显示效果:示例 浅绿底色 文本
示例 添加外框及双删除线 文本
示例
只加删除线的文本示例 带下划线 的文本
3.8.3. raw 指令应用#
.. raw:: html
<details>
<summary> 点击查看详情 </summary>
此处可以写 :raw-html:`<mark>详细` 描述
.. raw:: html
</details>
点击查看详情
此处可以写 详细 描述
小技巧
<details open=”open”> 可常态为展开状态
本页开头 目录 也是一个应用实例
脚注: