sphinx官方文档:https://zh-sphinx-doc.readthedocs.io/en/latest/intro.html
sphinx需要安装:sudo pip3 install sphinx
sphinx的使用:
1、创建目录:
mkdir pro/doc/doc_file -p
mkdir pro/mypro -p
cd pro/mypro
touch aa.py
touch bb.py
注意:这时注释文档和项目目录时平级的, 如果将doc放在项目目录下,之后修改doc_file/soucre/conf.py时需要将项目目录的父目录也加入到sys.path中。
目录结构为: pro为存放项目的父目录, mypro为项目目录, doc_files是存放所有注释文档的目录。
pro
├── doc
│ └── doc_file
└── mypro
├── aa.py
└── bb.py
aa.py和bb.py是两种不同的注释方式。sphinx会分辨这两种注释方式并生成不同注释文档。
aa.py内容为:aa_api中的注释必须使用空行隔开
"""aa模块的文档注释"""
class Aa(object):
"""
Aa类的注释
"""
@staticmethod
def aa_api(x, y):
"""
求商
:param x: 整数
:param y: 不能为零的整数
:return: 两数之商
"""
return x / y
bb.py内容为:bb_api中注释可以不使用空行隔开
"""Bb模块的文档注释"""
class Bb(object):
"""
Bb类的注释
"""
@staticmethod
def bb_api(x, y):
"""
求商
>>> Bb.bb_api(2, 4)
0.5
>>> Bb.bb_api(4, 2)
2.0
"""
return x / y
2、进入pro/doc/doc_file目录 cd pro/doc/doc_file
执行命令: sphinx-quickstart
如下:
myubuntu@ubuntu:~/pro/doc/doc_file$ sphinx-quickstart
欢迎使用 Sphinx 2.1.1 快速配置工具。
请输入接下来各项设置的值(如果方括号中指定了默认值,直接
按回车即可使用默认值)。
已选择根路径:.
布置用于保存 Sphinx 输出的构建目录,有两种选择。
一是在根路径下创建“_build”目录,二是在根路径下创建“source”
和“build”两个独立的目录。
> 独立的源文件和构建目录(y/n) [n]: y
项目名称会出现在文档的许多地方。
> 项目名称: mypro
> 作者名称: mypro
> 项目发行版本 []: 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
https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-language.
> 项目语种 [en]: zh_CN
创建文件 ./source/conf.py。
创建文件 ./source/index.rst。
创建文件 ./Makefile。
创建文件 ./make.bat。
完成:已创建初始目录结构。
你现在可以填写主文档文件 ./source/index.rst 并创建其他文档源文件了。用 Makefile 构建文档,像这样:
make builder
此处的“builder”是支持的构建器名,比如 html、latex 或 linkcheck。
3、 修改配置文件
vi ./source/conf.py
01:将13到15行注释放开, 将15行修改为sys.path.insert(0, os.path.abspath('/home/myubuntu/pro/mypro'))
/home/myubuntu/pro/mypro是项目的绝对路径, 写成相对路径也可以。(这个路径一定要写对,否则会报“no modle named ...”) 的错误
02: 在15行前面将项目的父目录添加到sys.path
sys.path.append('/home/myubuntu/pro')
02:修改第33行为
通过设置conf.py
中的extensions,可以为sphinx添加额外的扩展,如果想要将html文档转换为PDF,只需要先安装扩展,
然后再此处添加即可使用。由于我们的注释代码主要同时支持google style和numpy style,所以我们需要添加一个扩展来支持。
extensions = ['sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.mathjax', 'sphinx.ext.napoleon']
1 # Configuration file for the Sphinx documentation builder.
2 #
3 # This file only contains a selection of the most common options. For a full
4 # list see the documentation:
5 # http://www.sphinx-doc.org/en/master/config
6
7 # -- Path setup ------------------------------------------------------------ --
8
9 # If extensions (or modules to document with autodoc) are in another directo ry,
10 # add these directories to sys.path here. If the directory is relative to th e
11 # documentation root, use os.path.abspath to make it absolute, like shown he re.
12 #
13 # import os
14 # import sys
15 # sys.path.insert(0, os.path.abspath('.'))
16
17
18 # -- Project information --------------------------------------------------- --
--
19
20 project = 'mypro'
21 copyright = '2019, mypro'
22 author = 'mypro'
23
24 # The full version, including alpha/beta/rc tags
25 release = '1.0.0'
26
27
28 # -- General configuration ------------------------------------------------- --
29
30 # Add any Sphinx extension module names here, as strings. They can be
31 # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
32 # ones.
33 extensions = [
34 ]
35
36 # Add any paths that contain templates here, relative to this directory.
37 templates_path = ['_templates']
38
39 # The language for content autogenerated by Sphinx. Refer to documentation
40 # for a list of supported languages.
41 #
42 # This is also used if you do content translation via gettext catalogs.
43 # Usually you set "language" from the command line for these cases.
44 language = 'zh_CN'
45
46 # List of patterns, relative to source directory, that match files and
47 # directories to ignore when looking for source files.
48 # This pattern also affects html_static_path and html_extra_path.
49 exclude_patterns = []
50
51
52 # -- Options for HTML output ----------------------------------------------- --
53
54 # The theme to use for HTML and HTML Help pages. See the documentation for
55 # a list of builtin themes.
56 #
57 html_theme = 'alabaster'
58
59 # Add any paths that contain custom static files (such as style sheets) here ,
60 # relative to this directory. They are copied after the builtin static files ,
61 # so a file named "default.css" will overwrite the builtin "default.css".
62 html_static_path = ['_static']
修改后的conf.py内容如下:
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.append('/home/myubuntu/pro')
sys.path.insert(0, os.path.abspath('/home/myubuntu/pro/mypro'))
# -- Project information -----------------------------------------------------
project = 'mypro'
copyright = '2019, mypro'
author = 'mypro'
# The full version, including alpha/beta/rc tags
release = '1.0.0'
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.mathjax', 'sphinx.ext.napoleon']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = 'zh_CN'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
4、提取项目的目录结构并生成rst文件: source为生成rst文件存放的目录, /home/myubuntu/pro/mypro是项目的绝对路径
sphinx-apidoc -o ./source /home/myubuntu/pro/mypro
myubuntu@ubuntu:~/pro/doc/doc_file$ sphinx-apidoc -o ./source /home/myubuntu/pro/mypro
创建文件 ./source/aa.rst。
创建文件 ./source/bb.rst。
创建文件 ./source/modules.rst。
myubuntu@ubuntu:~/pro/doc/doc_file$
5、设置目录树:主要是将doc_file/source/modules.rst 文件添加到 index.rst中
maxdepth把index.html页中目录的标题显示深度限制设为5。之后空一行,在下面列出各子文档,可以不加文件后缀。
注意:这里同样要注意代码对齐。
修改后index.rst的内容为:
1 .. mypro documentation master file, created by
2 sphinx-quickstart on Sun Jun 16 01:08:28 2019.
3 You can adapt this file completely to your liking, but it should at least
4 contain the root `toctree` directive.
5
6 Welcome to mypro's documentation!
7 =================================
8
9 .. toctree::
10 :maxdepth: 10
11 :caption: Contents:
12
13 modules.rst
14
15
16 Indices and tables
17 ==================
18
19 * :ref:`genindex`
20 * :ref:`modindex`
21 * :ref:`search`
6、生成html注释文档:在doc_file目录下执行以下两个命令
make clean
删除doc_file/build 下面的所有内容。已经生成注释文档后,如果配置文件或项目源码注释有改动, 需要先执行make clean, 再执行make html
make html
myubuntu@ubuntu:~/pro/doc/doc_file$ make clean
Removing everything under 'build'...
myubuntu@ubuntu:~/pro/doc/doc_file$ make html
正在运行 Sphinx v2.1.1
正在加载翻译 [zh_CN]... 完成
making output directory... 完成
构建 [mo]:0 个 po 文件的目标文件已过期
构建 [html]中: 4 个源文件的目标文件已过期
updating environment: 4 added, 0 changed, 0 removed
reading sources... [100%] modules
查找当前已过期的文件……没有找到
pickling environment... 完成
checking consistency... 完成
preparing documents... 完成
写入输出……[ 25%] aa
写入输出……[ 50%] bb
写入输出……[ 75%] index
写入输出……[100%] modules
生成索引…… genindex py-modindex
写入附加页面…… search
复制静态文件……完成
复制额外文件……完成
导出 Chinese (code: zh) 的搜索索引……完成
导出对象清单……完成
构建 成功.
HTML 页面保存在 build/html 目录。
myubuntu@ubuntu:~/pro/doc/doc_file$
7、注释文档效果展示
8、主题设置
sphinx自带的主题classic、nature、default、sphinxdoc, 修改配置文件html_theme字段为以下内容:
html_theme = 'classic'
html_theme_options = {
"rightsidebar": "false",
"relbarbgcolor": "black"
}
sphinx自带的主题并不好用,可以参照官方文档设置主题:http://www.sphinx-doc.org/en/master/theming.html
9、问题1:
如果自定义生成的注释文档的目录结构(分层结构, 也就是如何自定义make html时生成的html的结构)?
如何将源码添加到文档中?
当项目目录结构复杂时,如:
生成的导航中会多出一些节点, 如: Submodules Subpackages Module contents, 如何不生成这些节点?
解决: 没有找到修改源码的方法,图中的目录结构是由make html命令生成的, make html是根据sphinx-apidoc -o命令生成的rst文件生成目录结构的, 哪个就修改rst文件也可以。使用如下方法:
import os
import re
def modify_doc_title_dir(abspath_rstfiles_dir):
"""
rst文件中:有‘========’和‘----------’行的表示其行上一行的文字是标题,‘=’和‘-’要大于等于标题的长度。
使用sphinx-apidoc -o ./source/rst_files /home/myubuntu/pro/mypro命令将生成rst文件放在./source/rst_files目录下。 生成rst文件后将rst_files/modules.rst文件中的标题去掉,并修改maxdepth字段。
删除和修改使用sphinx-apidoc -o 命令的生成的rst文件中的标题
:param abspath_rstfiles_dir: rst文件所在的文件夹的绝对路径
:return:
"""
rst_files = os.listdir(abspath_rstfiles_dir)
# 要删除的节点(标题目录的节点)
del_nodes = ['Submodules', 'Module contents', 'Subpackages']
# 要删除的标题中的字符串
del_str = [' module', ' package']
for rst_file in rst_files:
f = open(os.path.join(abspath_rstfiles_dir, rst_file), 'r')
file_lines = f.readlines()
f.close()
write_con = []
flag = 0
for file_line in file_lines:
if file_line.strip() in del_nodes:
flag = 1
continue
if flag:
flag = 0
continue
if re.search(del_str[0], file_line):
modify_line = file_line.split('.')[-1].replace(del_str[0], '.py')
write_con.append(modify_line)
continue
if re.search(del_str[1], file_line):
modify_line = file_line.split('.')[-1].replace(del_str[1], '')
write_con.append(modify_line)
continue
write_con.append(file_line)
f = open(os.path.join(abspath_rstfiles_dir, rst_file), 'w')
f.writelines(write_con)
f.close()
if __name__ == '__main__':
modify_doc_title_dir('/home/myubuntu/pro/doc/doc_file/source/rst_files')
修改后生成文件的目录结构为:
总结: 这个方法可以修改rst文件中的标题, 并不能修改automodule和toctree字段的内容。可以不将rstfiles/modules.rst文件加入到index.rst的toctree字段下, 也就不用使用这个方法, 查看整个目录使用模块索引即可。
10:文档首页设置:
复制生成分bulit/html/index.html文件到pro目录下,然后修改pro/index.html中标签的路径即可(路径需要是相对路径)
如:
参考:
https://blog.csdn.net/sinat_29957455/article/details/83657029
https://www.cnblogs.com/zzqcn/p/5096876.html