python 使用sphinx 快速生成说明文档
以Linux环境使用为例,没有linux环境的可以安装虚拟机
1.安装sphinx
pip3 install sphinx
2.文件结构
在项目的同级目录下创建doc文件夹,进入doc文件夹,运行如下指令:
sphinx-quickstart
接着要填写一些项目信息
ubuntu18@ubuntu18:~/weiquan/sphnix-demo/doc$ sphinx-quickstart
Welcome to the Sphinx 4.5.0 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: myproject // 输入项目名称
> Author name(s): bob // 作者
> Project release []: 0.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]: // 生成文档的语言
Creating file /home/ubuntu18/weiquan/sphnix-demo/doc/source/conf.py.
Creating file /home/ubuntu18/weiquan/sphnix-demo/doc/source/index.rst.
Creating file /home/ubuntu18/weiquan/sphnix-demo/doc/Makefile.
Creating file /home/ubuntu18/weiquan/sphnix-demo/doc/make.bat.
Finished: An initial directory structure has been created.
...
3.修改配置文件
修改doc/source下的conf.py文件:
...
import os
import sys
sys.path.insert(0, os.path.abspath('../../myproject')) ## 项目相对conf.py的路径
...
# sphinx.ext.napoleon: 表示支持numpy和google风格的注释
extensions = ['sphinx.ext.autodoc','sphinx.ext.napoleon']
...
# google风格的代码注释
class MyProject:
"""This is my project"""
def is_in_position(self, data, id=0):
"""Judge whether in the position.
Args:
id: 1 - coords, 0 - angles
data: A data list, angles or coords, length 6.
Return:
1 : True
0 : False
-1: Error
"""
...
4.生成html文档
在doc目录下执行命令生成html文档:
make html
生成的文档会保存在doc/build/html文件夹下
生成markdown文档
1.安装依赖
pip3 install sphinx-markdown-builder
2.修改配置文件
修改doc/source下的conf.py文件:
import sphinx_markdown_builder
...
# sphinx.ext.napoleon: 表示支持numpy和google风格的注释
extensions = ['sphinx.ext.autodoc','sphinx.ext.napoleon','sphinx_markdown_builder']
...
exclude_patterns = [
'build/*'
]
3.生成markdown文档
执行指令
sphinx-apidoc -o source ../myproject
在doc目录下运行命令:
make markdown
生成的markdown文档保存在build/markdown下面
使用Google风格的注释生成的markdown文档:
在编写代码的过程中顺手写上代码注释,方便维护以及后续的说明文档的生成,一举两得。