Welcome to sphinx_demo’s documentation!¶
1. 利用Sphinx生成项目文档¶
sphinx是一款简洁优雅的自动化文档工具,支持代码接口注释的自动化排版,markdown、jupyter notebook文件等,先看看上线后的最终效果:
安装Sphinx¶
pip install sphinx sphinx-autobuild sphinx_rtd_theme recommonmark
# 版本Sphinx 2.2.0
DEMO项目案例¶
项目结构如下:
├── README.md
├── docs
└── sphinx_demo
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-36.pyc
│ ├── say.cpython-36.pyc
│ └── some_action.cpython-36.pyc
├── intro.md
├── jupyter_demo.ipynb
├── say.py
├── some_action.py
└── tools
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-36.pyc
│ ├── run.cpython-36.pyc
│ └── sleep.cpython-36.pyc
├── run.py
└── sleep.py
初始化Sphinx¶
$ cd docs
$ sphinx-quickstart
Welcome to the Sphinx 2.2.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: your_project_name
> Author name(s): your_name
> Project release []:
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
Creating file ./source/conf.py.
Creating file ./source/index.rst.
Creating file ./Makefile.
Creating file ./make.bat.
Finished: An initial directory structure has been created.
初始化完成后,在docs路径下会生成如下文件树:
.
├── Makefile
├── build
├── make.bat
└── source
├── _static
├── _templates
├── conf.py
└── index.rst
生成项目模块文档的HTML文件¶
修改conf.py文件,将项目import路径添加进来,并增加扩展项:
import os import sys package_path = os.path.abspath("../../") sys.path.insert(0, package_path) extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.todo',]
在docs下执行命令
sphinx-apidoc -o ./source ../your_package_name/
在./source/index.rst添加模块索引文件modules
Welcome to sphinx_demo's documentation! ======================================= .. toctree:: :maxdepth: 2 :caption: Contents: modules #这里不需要加文件后缀
生成html文件
make html # 可以使用make clean清理之前生成的html文件
这时,点击./docs/build/html下会生成的index.html文件,可以在浏览器预览到:
修改主题¶
修改conf.py文件:
import sphinx_rtd_theme # 添加这行
# html_theme = 'alabaster' # 注释此行 # 注释这行
html_theme = "sphinx_rtd_theme" # 修改此行 # 添加这行
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # 添加这行
然后重新执行:
make clean
make html
打开./docs/build/html/index.html可以预览到:
Markdown支持¶
修改conf.py文件
import recommonmark
from recommonmark.transform import AutoStructify
source_parsers = {
'.md': 'recommonmark.parser.CommonMarkParser',
}
source_suffix = ['.rst', '.md']
Jupyter Notebook支持¶
安装nbsphinx
在conf.py添加’nbsphinx’
extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.todo', 'nbsphinx' # Jupyter Notebook支持 ]
在index.rst中添加*.ipynb文件和
Welcome to sphinx_demo's documentation! ======================================= .. toctree:: :maxdepth: 4 # 如果发现展示层级不对,可以展示深度 :caption: Contents: intro # 添加markdown介绍文件 jupyter_demo.ipynb # 添加Notebook文件 modules
效果
- bug解决
常见的bugWARNING: Pygments lexer name "ipython3" is not known
,解决方法:
Ref:https://github.com/spatialaudio/nbsphinx/issues/24
I had to add
'IPython.sphinxext.ipython_console_highlighting'
toextensions
in myconf.py
. Somehow the old IPython docs have this info but the new ones don’t.Adding
'**.ipynb_checkpoints'
toexclude_patterns
fixed the other problem.Thanks!
引用外部文件¶
添加./source/include.rst到index.rst,include内容:
.. include:: ../../README.rst
软连接
cd doc/source ln -s ../../somedir somedir .. toctree:: somedir/README
自动化托管文档到Readthedocs¶
一般的做法是将文档托管到版本控制系统比如github上面,push源码后自动构建发布到readthedoc上面, 这样既有版本控制好处,又能自动发布到readthedoc。先在之前项目.gitignore文件中添加build/
目录,推送到远程仓库。然后参考官方文档:
- 在Read the Docs上面注册一个账号
- 登陆后点击 “Import”.
- 给该文档项目填写一个名字, 并添加你在GitHub上面的工程HTTPS链接, 选择仓库类型为Git
- 其他项目根据自己的需要填写后点击 “Create”,创建完后会自动去激活Webhooks,不用再去GitHub设置
- 一切搞定,从此只要你往这个仓库push代码,readthedoc上面的文档就会自动更新.
some bug:
master file /home/docs/checkouts/readthedocs.org/user_builds/build-your-sphinx-docs/checkouts/latest/docs/source/contents.rst not found
解决办法:
Ref:https://github.com/readthedocs/readthedocs.org/issues/2569
I finally found it works by adding the following line in conf.py to explicitly assign the master document:
master_doc = ‘index’
I guess this issue is caused by the conflicts of the default sphinx version in readthedocs and the local environment.
I just record this solution here in case someone like me will be confused by this issue and have no idea about how to deal with it.
2.Jupyter Notebook案例¶
测试公式:\(\sum_{i=0}^{i=50}(i)\)
[1]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
[9]:
x = np.sin(range(100))
plt.plot(x)
[9]:
[<matplotlib.lines.Line2D at 0x11782c940>]

3.DEMO PROJECT API¶
4.代码规范¶
遵循pep8及Google 代码风格,详细请查看原文阅读,这里强调其中的重要内容:
命名¶
应该避免的名称
- 单字符名称, 除了计数器和迭代器.
- 包/模块名中的连字符(-)
- 双下划线开头并结尾的名称(Python保留, 例如__init__)
命名约定
- 所谓”内部(Internal)”表示仅模块内可用, 或者, 在类内是保护或私有的.
- 用单下划线(_)开头表示模块变量或函数是protected的(使用from module import *时不会包含).
- 用双下划线(__)开头的实例变量或方法表示类内私有.
- 将相关的类和顶级函数放在同一个模块里. 不像Java, 没必要限制一个类一个模块.
- 对类名使用大写字母开头的单词(如CapWords, 即Pascal风格), 但是模块名应该用小写加下划线的方式(如lower_with_under.py). 尽管已经有很多现存的模块使用类似于CapWords.py这样的命名, 但现在已经不鼓励这样做, 因为如果模块名碰巧和类名一致, 这会让人困扰.
注释¶
函数注释案例:
下文所指的函数,包括函数, 方法, 以及生成器.
一个函数必须要有文档字符串, 除非它满足以下条件:
- 外部不可见
- 非常短小
- 简单明了
文档字符串应该包含函数做什么, 以及输入和输出的详细描述. 通常, 不应该描述”怎么做”, 除非是一些复杂的算法. 文档字符串应该提供足够的信息, 当别人编写代码调用该函数时, 他不需要看一行代码, 只要看文档字符串就可以了. 对于复杂的代码, 在代码旁边加注释会比使用文档字符串更有意义.
def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
"""Fetches rows from a Bigtable.
Retrieves rows pertaining to the given keys from the Table instance
represented by big_table. Silly things may happen if
other_silly_variable is not None.
Args:
big_table: An open Bigtable Table instance.
keys: A sequence of strings representing the key of each table row
to fetch.
other_silly_variable: Another optional variable, that has a much
longer name than the other args, and which does nothing.
Returns:
A dict mapping keys to the corresponding table row data
fetched. Each row is represented as a tuple of strings. For
example:
{'Serak': ('Rigel VII', 'Preparer'),
'Zim': ('Irk', 'Invader'),
'Lrrr': ('Omicron Persei 8', 'Emperor')}
If a key from the keys argument is missing from the dictionary,
then that row was not found in the table.
Raises:
IOError: An error occurred accessing the bigtable.Table object.
"""
pass
类注释
类应该在其定义下有一个用于描述该类的文档字符串. 如果你的类有公共属性(Attributes), 那么文档中应该有一个属性(Attributes)段. 并且应该遵守和函数参数相同的格式.
class SampleClass(object):
"""Summary of class here.
Longer class information....
Longer class information....
Attributes:
likes_spam: A boolean indicating if we like SPAM or not.
eggs: An integer count of the eggs we have laid.
"""
def __init__(self, likes_spam=False):
"""Inits SampleClass with blah."""
self.likes_spam = likes_spam
self.eggs = 0
def public_method(self):
"""Performs operation blah."""
TODO注释¶
TODO注释应该在所有开头处包含”TODO”字符串, 紧跟着是用括号括起来的你的名字, email地址或其它标识符. 然后是一个可选的冒号. 接着必须有一行注释, 解释要做什么. 主要目的是为了有一个统一的TODO格式, 这样添加注释的人就可以搜索到(并可以按需提供更多细节). 写了TODO注释并不保证写的人会亲自解决问题. 当你写了一个TODO, 请注上你的名字.
# TODO(zhou zhirui): Use a "*" here for string repetition.
# TODO(huang zhifeng) Change this to use relations.
5.文档规范¶
自动化文档生成请参展文档(1.2.3)查看,这里约定团队文档应包含内容。
README¶
- 简介项目功能
- 安装方法
- 使用方法
模型及方法论证¶
- baseline方法
- State-of-the-art模型、方法调研
- 选型模型、方法介绍,选型理由
Review记录¶
- review前,汇总期间更新模块、上次TODO跟进情况;
- review后,本次TODO事项。
6. code review方案细则¶
流程¶
每月按固定时间表进行,由项目负责人统筹,项目组成员、review评审人参与:
- 项目负责人review材料准备
- 项目计划书
- 代码合并
- 文档准备(参考5. 文档规范,1.利用Sphix生成项目文档)
- 更新内容简介(文档、代码)
- 对上次TODO内容跟进情况评分
- 对代码、文档、研发进度review,填写评分并列出TODO事项;
- 发送纪要邮件(评分文件、TODO事项、Review纪要)
评分方法¶
单元测试¶
在项目根目录test下提供核心模块功能需要提供单元测试脚本,每项功能至少包含3个不同的测试案例。每缺少一项扣5分,满分100分。
代码规范¶
代码规范满分100,包含基本规范和可理解性:
- 基本规范(50/100)
利用自动化代码审查工具统计,无法给出合理原因的,每项扣2分;
```text
# 安装自动化审查工具 pip install pep8
# 检查文件或文件夹 pep8 file
# 检查并统计错误数量 pep8 –statistics file
# 某项目运行例子 13 E127 continuation line over-indented for visual indent 1 E128 continuation line under-indented for visual indent 2 E225 missing whitespace around operator 2 E261 at least two spaces before inline comment 3 E302 expected 2 blank lines, found 0 5 E402 module level import not at top of file 82 E501 line too long (89 > 79 characters) 7 W292 no newline at end of file 5 W391 blank line at end of file 2 W503 line break before binary operator
```
- 可理解性(50/100)
- 无意义/歧义变量名、函数名、类名每项扣2分
- 接口函数、外部类无参数类型、默认值、可选项、含义说明每项扣5分
- 接口函数、外部类无功能说明,每项扣5分
进度完成¶
满分100,对比项目任务书计划,评审人按完成比例打分。
跟进情况¶
逐条审查上次review 代码及文档 TODO事项解决情况,根据评估的解决比例\(\alpha\):
评分结果记录¶
每次review评分记录表格:
项目 | 模块 | 开发者 | review日期 | 单元测试 | 代码规范 | 文档规范 | 进度完成 | 跟进完成比例 |
---|---|---|---|---|---|---|---|---|
demo | run | zhou | 2019-09-03 | 90 | 90 | 90 | 90 | 0.9 |
绩效考核¶
绩效考核中,以模型研发为主的考核事项,其分值将以期间多次Review平均得分为基准,参照其他情况,在\(\pm 5\)浮动范围内进行打分。
Sphinx-DEMO¶
sphinx是一款简洁优雅的自动化文档工具,支持代码接口注释的自动化排版,markdown、jupyter notebook文件等,先看看上线后的最终效果:
安装Sphinx¶
pip install sphinx sphinx-autobuild sphinx_rtd_theme recommonmark
# 版本Sphinx 2.2.0
DEMO项目案例¶
项目结构如下:
├── README.md
├── docs
└── sphinx_demo
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-36.pyc
│ ├── say.cpython-36.pyc
│ └── some_action.cpython-36.pyc
├── intro.md
├── jupyter_demo.ipynb
├── say.py
├── some_action.py
└── tools
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-36.pyc
│ ├── run.cpython-36.pyc
│ └── sleep.cpython-36.pyc
├── run.py
└── sleep.py
初始化Sphinx¶
$ cd docs
$ sphinx-quickstart
Welcome to the Sphinx 2.2.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: your_project_name
> Author name(s): your_name
> Project release []:
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
Creating file ./source/conf.py.
Creating file ./source/index.rst.
Creating file ./Makefile.
Creating file ./make.bat.
Finished: An initial directory structure has been created.
初始化完成后,在docs路径下会生成如下文件树:
.
├── Makefile
├── build
├── make.bat
└── source
├── _static
├── _templates
├── conf.py
└── index.rst
生成项目模块文档的HTML文件¶
修改conf.py文件,将项目import路径添加进来,并增加扩展项:
import os import sys package_path = os.path.abspath("./../../sphinx_demo/") sys.path.insert(0, package_path) extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.todo',]
在docs下执行命令
sphinx-apidoc -o ./source ../your_package_name/
在./source/index.rst添加模块索引文件modules
Welcome to sphinx_demo's documentation! ======================================= .. toctree:: :maxdepth: 2 :caption: Contents: modules #这里不需要加文件后缀
生成html文件
make html # 可以使用make clean清理之前生成的html文件
这时,点击./docs/build/html下会生成的index.html文件,可以在浏览器预览到:
修改主题¶
修改conf.py文件:
import sphinx_rtd_theme # 添加这行
# html_theme = 'alabaster' # 注释此行 # 注释这行
html_theme = "sphinx_rtd_theme" # 修改此行 # 添加这行
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # 添加这行
然后重新执行:
make clean
make html
打开./docs/build/html/index.html可以预览到:
Markdown支持¶
修改conf.py文件
import recommonmark
from recommonmark.transform import AutoStructify
source_parsers = {
'.md': 'recommonmark.parser.CommonMarkParser',
}
source_suffix = ['.rst', '.md']
Jupyter Notebook支持¶
安装nbsphinx
在conf.py添加’nbsphinx’
extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.todo', 'nbsphinx' # Jupyter Notebook支持 ]
在index.rst中添加*.ipynb文件和
Welcome to sphinx_demo's documentation! ======================================= .. toctree:: :maxdepth: 4 # 如果发现展示层级不对,可以展示深度 :caption: Contents: intro # 添加markdown介绍文件 jupyter_demo.ipynb # 添加Notebook文件 modules
效果
- 自动化托管文档到readthedocs