使用sphinx自動提取python中的注釋成為接口文檔


寫好了代碼,交付給他人使用的時候,查看代碼固然可以了解各類和函數的功能細節,但接口文檔能更方便的查找和說明功能。所以,一價與代碼同步的接口文檔是很有必要的。sphinx可以根據python中的注釋,自動的生成接口文檔,這樣有利於保證文檔和代碼功能的同步。讓我們來了解如何自動生成文檔。

1. python代碼格式。

class A:
    '''
    你好!
    '''
    @staticmethod
    def Aa():
        '''
        你也好!
        '''
        fun1()

看到類和函數中,都加入了注釋。

2. 安裝shpinx

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

使用國內的鏡像安裝比較快。

3. 配置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')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM