文档 - noonecare/python GitHub Wiki

自记录文档( self document )

  • 软件工程中,提倡把文档和源码写在一起。这样方便同步源码和源码的说明。
  • 为此提倡在源码中写段落文档。python 中段落文档由 """document""" 表示。下面的代码演示了段落代码。
# coding: utf-8
"""
这就是段落注释
"""

def greet():
    print("hello")

自动生成文档

生成 api 文档,执行
python sphinx-apidoc-script.py . -o build

或者

sphinx-apidoc.exe . -o build

给当前目录下所有 modules 生成 modules.rst(根据 module 的 docstring 产生), <module_name>.rst 文档。

生成 index.rst(表示文档的首页), conf.py 等文档的配置文件

执行

python sphinx-quickstart.py

或者

sphinx-quickstart.exe

回答一系列有关配置的文件(最重要的是要 autodoc 选 yes, 生成 makefile 选 yes),会生成文档的框架,特别的有文档的配置文件 conf.py, 文档的首页 index.rst, 由 rst 转成其他格式(比如 html 格式) 的 Makefile 文件

生成 html 文档

执行

make html

生成 html 文档,生成出的 html 文档,格式就像是 python 官档一样。

Pycharm

Pycharm 为上面的过程提供了可视化的配置窗口(虽然比较鸡肋),以下是我使用 pycharm 生成文档的流程:

  • 点击 tools->sphinx quickstart (等价于执行 sphinx-quickstart.exe), 回答一系列配置问题。
  • 编辑 generate-api-doc Run Configuration。这个 Run Task 执行的脚本是 sphinx-apidoc-script.py(等价于执行 sphinx-apidoc-script.py),找包路径是当前路径,输出路径是 index.rst 所在的目录。
  • 编辑一个 sphinx task (等价于执行 make), command 设为 html(相当于执行 make html), 输出路径设为 build(会把生成的 html 放到 build 目录下), Before Launch 添加 generate-api-doc run task
  • 点击运行 sphinx task, 生成文档。

关于 sphinx 要说一点是, sphinx 生成的文档是 rst(生成 html 是执行的 make html 命令), 你要手动去修改文档,就需要去修改 rst 文档。rst 文档有点像 markdown, 更多的信息我就不知道了。

我认为,重要的是在源码中把docstring 写好。