利用Sphinx创建Python文档

程序猿最喜欢的就是写代码,最不喜欢的莫过于写文档。项目刚开始的时候,可能还写一些文档,但是到了项目紧急的时候能把代码写完就不错了,文档的事情就等不忙的时候再慢慢写,然后这个慢慢写的过程基本也是不具有操作性的;而且就算写了,文档和代码的同步工作又是一个让人无比头疼的事情。话说回来,我们每次写代码都会写注释,有什么是比代码注释更好的文档呢。
Sphinx是一个自动化生成Python文档的工具,其可以提取Python代码中的文档注释自动生成文档,方便我们快速生成帮助文件,包括Python的官方文档都是用该工具生成的,下面我就向大家介绍下Sphinx的基础使用方式用。

基础资料

我将用如下代码生成文档
run.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class run():
'''
用于测试的类
'''
def start(self):
'''
无参数 打印Hello Word
:return:
'''
print("Hello Word")

def vae(self, info:str):
"""
有参数 打印参数内容
:param info:
:return:
"""
print(info)

stop.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class stop():
'''
用于测试的类
'''
def end(self):
'''
无参数 打印Hello Word
:return:
'''
print("Hello Word")

def vae(self, info:str):
"""
有参数 打印参数内容
:param info:
:return:
"""
print(info)

生成后的效果如图所示

安装

当前目录为demo,包含run.pystop.py两个文件。

1
2
3
4
➜  Demo tree -L 2 ./
./
├── run.py
├── stop.py

创建虚拟环境并进入

1
2
➜  Demo virtualenv venv
➜ Demo source venv/bin/activate

安装 Sphinx

1
(venv) ➜  Demo pip install sphinx

使用

Sphinx提供默认的快速配置方案,通过命令行交互即可完成全部的配置
我的配置方案如下

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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
(venv) ➜  Demo sphinx-quickstart
Welcome to the Sphinx 1.8.1 quickstart utility.

Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).

Selected root path: .

You have two options for placing the build directory for Sphinx output.
Either, you use a directory "_build" within the root path, or you separate
"source" and "build" directories within the root path.
> Separate source and build directories (y/n) [n]: y

Inside the root directory, two more directories will be created; "_templates"
for custom HTML templates and "_static" for custom stylesheets and other static
files. You can enter another prefix (such as ".") to replace the underscore.
> Name prefix for templates and static dir [_]:

The project name will occur in several places in the built documentation.
> Project name: Demo
> Author name(s): vae
> Project release []: 1.0.0

If the documents are to be written in a language other than English,
you can select a language here by its language code. Sphinx will then
translate text that it generates into that language.

For a list of supported codes, see
http://sphinx-doc.org/config.html#confval-language.
> Project language [en]: zh_cn

The file name suffix for source files. Commonly, this is either ".txt"
or ".rst". Only files with this suffix are considered documents.
> Source file suffix [.rst]:

One document is special in that it is considered the top node of the
"contents tree", that is, it is the root of the hierarchical structure
of the documents. Normally, this is "index", but if your "index"
document is a custom template, you can also set this to another filename.
> Name of your master document (without suffix) [index]:
Indicate which of the following Sphinx extensions should be enabled:
> autodoc: automatically insert docstrings from modules (y/n) [n]: y
> doctest: automatically test code snippets in doctest blocks (y/n) [n]: y
> intersphinx: link between Sphinx documentation of different projects (y/n) [n]: y
> todo: write "todo" entries that can be shown or hidden on build (y/n) [n]: y
> coverage: checks for documentation coverage (y/n) [n]: y
> imgmath: include math, rendered as PNG or SVG images (y/n) [n]: y
> mathjax: include math, rendered in the browser by MathJax (y/n) [n]: y
> ifconfig: conditional inclusion of content based on config values (y/n) [n]: y
> viewcode: include links to the source code of documented Python objects (y/n) [n]: y
> githubpages: create .nojekyll file to publish the document on GitHub pages (y/n) [n]: y
Note: imgmath and mathjax cannot be enabled at the same time. imgmath has been deselected.

A Makefile and a Windows command file can be generated for you so that you
only have to run e.g. `make html' instead of invoking sphinx-build
directly.
> Create Makefile? (y/n) [y]:
> Create Windows command file? (y/n) [y]: n

Creating file ./source/conf.py.
Creating file ./source/index.rst.
Creating file ./Makefile.

Finished: An initial directory structure has been created.

You should now populate your master file ./source/index.rst and create other documentation
source files. Use the Makefile to build the docs, like so:
make builder
where "builder" is one of the supported builders, e.g. html, latex or linkcheck.

配置完后,会形成如下目录结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
venv) ➜  Demo tree -L 2
.
├── Makefile
├── build
├── run.py
├── source
│ ├── _static
│ ├── _templates
│ ├── conf.py
│ └── index.rst
├── stop.py
└── venv
├── bin
├── include
├── lib
└── pip-selfcheck.json

8 directories, 6 files

修改source/conf.py,增加如下内容(或者修改该文件的 15~17行)

1
2
3
import os
import sys
sys.path.insert(0, os.path.abspath('../'))

该配置规定了源文件的路径,我的Sphinx配置在所有源文件的第二层,所以源文件的路径是../

执行生成api文档的操作

1
2
3
4
(venv) ➜  Demo sphinx-apidoc -o source ./
File source/run.rst already exists, skipping.
File source/stop.rst already exists, skipping.
File source/modules.rst already exists, skipping.

其中-o参数为输出的文档配置的路径,这个需要和Sphinx的配置文件路径路径保持一致;最后一个参数为源文件的根目录。

执行make html生成文档

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
(venv) ➜  Demo make html 
正在运行的是 Sphinx v1.8.1
正在加载翻译 [zh_cn]... 完成
创建输出目录…
loading intersphinx inventory from https://docs.python.org/objects.inv...
intersphinx inventory has moved: https://docs.python.org/objects.inv -> https://docs.python.org/3/objects.inv
构建 [mo]:0 个 po 文件的目标文件已过期
构建 [html]: 4 个源文件的目标文件已过期
updating environment: 4 added, 0 changed, 0 removed
reading sources... [100%] stop
查找当前已过期的文件……没有找到
Pickle 序列化环境……完成
检查一致性……/Users/vae/work/build/Python/Demo/source/modules.rst: WARNING: document isn't included in any toctree
完成
准备文档……完成
写入输出……[ 25%] index 写入输出……[ 50%] modules 写入输出……[ 75%] run 写入输出……[100%] stop
生成索引…… genindex py-modindex
highlighting module code... [100%] stop
写入附加页面…… search
复制静态文件……done
复制额外文件……完成
导出 Chinese (code: zh) 的搜索索引……完成
导出对象清单……完成
build 成功, 1 warning.

HTML 页面保存在 build/html 目录。

通过浏览器打开 build/html/index.html既为我们的文档界面。
默认界面

浏览

默认的文档不是那么美观。我们改用sphinx_rtd_theme主题

1
(venv) ➜  Demo pip install sphinx_rtd_theme

修改source/conf.py中的html_theme = 'alabaster'html_theme = 'sphinx_rtd_theme'

重新执行make html,生成新的配置文件。
sphinx_rtd_theme皮肤的帮助文档