安装Sphinx
pip install sphinx
使用
1. 假设存在如下test.py
def say_hello(name='world'):
"""say hello to someone
Say hello to the people who have the name you given.
Args:
name (str): The people's name you want to greet. world by default.
"""
print(f"Hello {name}!")
假设我们在docs目录下存放文档,source目录下存放源码。存在目录结构如下:
work
├─docs
└─source
└─test.py
2. 在docs目录下执行sphinx-quikstart
:
sphinx-quickstart
根据提示输入完成配置
注:zh_CN代表简体中文
λ sphinx-quickstart.exe
Welcome to the Sphinx 3.4.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
The project name will occur in several places in the built documentation.
> Project name: test
> Author name(s): hui
> Project release []: 0.1
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
https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-language.
> Project language [en]: zh_CN
...
此时,sphinx帮我们在docs目录下创建了一些文件,目录结构如下:
work
├─docs
│ │ make.bat
│ │ Makefile
│ │
│ ├─build
│ └─source
│ │ conf.py
│ │ index.rst
│ │
│ ├─_static
│ └─_templates
└─source
test.py
3. 配置conf.py
3.1 修改源码位置:
将如上图所示的代码注释去掉,修改成自己的源文件所在目录:
import os
import sys
sys.path.insert(0, os.path.abspath('../../source'))
3.2 添加napoleon扩展
在extensions
列表中添加sphinx.ext.napoleon
extensions = [
'sphinx.ext.napoleon',
]
保存。
更多设置参考:
https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html?highlight=google
3.3 生成rst文件
在work目录下执行sphinx-apidoc -f -o docs/source projectdir
λ sphinx-apidoc.exe -f -o docs/source source
Creating file docs/source\test.rst.
Creating file docs/source\modules.rst.
3.4 进入docs目录,执行make html
生成html文档到build目录
λ cd docs
λ make html
Running Sphinx v3.4.1
loading translations [zh_CN]... done
making output directory... done
...
省略输出信息
...
Running Sphinx v3.4.1
loading translations [zh_CN]... done
making output directory... done
进入build/html文件夹,打开index.html,点进去索引或模块索引就能看到我们之前创建的函数的文档了:
需要注意的是,sphinx在make html或其他文件时,是根据之前生成的rst文件去生成的,所以要保证前面生成的rst文件可以被找到。在make.bat中,默认是从source目录中去获取rst文件,生成到build目录中。