使用sphinx自动提取python中的注释成为接口文档

写好了代码,交付给他人使用的时候,查看代码固然可以了解各类和函数的功能细节,但接口文档能更方便的查找和说明功能。所以,一价与代码同步的接口文档是很有必要的。sphinx可以根据python中的注释,自动的生成接口文档,这样有利于保证文档和代码功能的同步。让我们来了解如何自动生成文档。

复制代码
class A:
    '''
    你好!
    '''
    @staticmethod
    def Aa():
        '''
        你也好!
        '''
        fun1()

看到类和函数中,都加入了注释。

  1. 安装shpinx

    pip install sphinx -i https://pypi.doubanio.com/simple --trusted-host pypi.doubanio.com

使用国内的镜像安装比较快。

  1. 配置shpinx

    cd myproject sphinx-quickstart
    Enter the root path for documentation.

    Root path for the documentation [.]: doc
    Project name: XXX
    Author name(s): XXX
    Project version []: 1.0
    Project release [1.0]:
    Project language [en]: zh_CN #如果注释中有中文,这里必须设置。否则生成接口文档出错。
    autodoc: automatically insert docstrings from modules (y/n) [n]: y
    其它项都选择默认

完成之后,会在当前目录创建 doc 目录,所有sphinx相关的文件都在 doc目录下。

复制代码
$ ls doc/
_build  conf.py  index.rst  Makefile  _static  _templates
$ vi doc/conf.py  #修改文件内容
sys.path.insert(0, os.path.abspath('.')) 
sys.path.insert(0, os.path.abspath('..')) # 缺少此行会导致在make html时提示 __import__出错,找不到module。 所以必须把上一级目录(即代码所在目录)include进来

$ sphinx-apidoc -o doc/ .
Creating file doc/a.rst.
Creating file doc/modules.rst

# 把生成的 doc/modules.rst添加到index.rst
$ vi doc/index.rst

Contents:
 .. toctree::
    :maxdepth: 2

    modules.rst

生成html页面
$ cd doc
$ make html

生成的html文档,在doc/_build/html里。

sphinx对仅工作在python2.7 或python3上。当文件中有中文时,可能会报错:'ascii' codec can't decode byte 0xe2 in position xxx。可以在报错的地方加入:

复制代码
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
相关推荐
m0_736919103 小时前
C++代码风格检查工具
开发语言·c++·算法
喵手4 小时前
Python爬虫实战:旅游数据采集实战 - 携程&去哪儿酒店机票价格监控完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集结果csv导出·旅游数据采集·携程/去哪儿酒店机票价格监控
2501_944934734 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
helloworldandy4 小时前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python
黎雁·泠崖4 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言
2301_763472465 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
肖永威5 小时前
macOS环境安装/卸载python实践笔记
笔记·python·macos
TechWJ5 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto
枷锁—sha6 小时前
【SRC】SQL注入WAF 绕过应对策略(二)
网络·数据库·python·sql·安全·网络安全
abluckyboy6 小时前
Java 实现求 n 的 n^n 次方的最后一位数字
java·python·算法