概述
下文講述使用sphinx自動生成reStructuredText python API文檔的簡單過程。
配置流程
安裝依賴
$ pip install sphinx blurb python-docs-theme
創建項目
$ mkdir demo
$ cd demo
# 自動生成配置文件
demo $ sphinx-quickstart
項目相關文件說明(以默認配置為例)
項目結構:
# demo/
conf.py
Makefile
make.bat
_build/
|--doctrees/
|--environment.pickle
|--index.doctree
|--html/
|--_sources/
|--_static/
index.html
...
_static/
_templates/
index.rst
其中index.rst是入口文件,sphinx生成文檔的實質是根據配置遍歷路徑內文件並提取docstring進行渲染的過程,過程大致可划分為兩步:第一步是根據conf.py配置啟動文件,第二步是根據index.rst的指令渲染html文件。
假設項目的python源代碼放置在app/目錄下:
demo $ mkdir app
demo $ mkdir app/__init__.py
實現文件功能:
# demo/app/__init__.py
def run(host, port):
"""
run server on given host:port
:type host: str
:param host: server host
:type port: int
:param port: server port
:return app
"""
print('running on :{}:{}'.format(host, port))
return 0
配置文件
此時還sphinx還不知道原代碼文檔寫在哪里,需要在index.rst文件中配置:
Welcome to sphinx-demo's documentation!
=======================================
.. toctree::
:maxdepth: 2
:caption: Contents:
API
====
.. automodule:: app
:members:
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
配置的信息是API部分內容,這相當於告訴sphinx要生成該模塊docstring的對應文檔。
除了配置index.rst文檔,還需要在conf.py中修改兩個地方:添加導入路徑和添加插件,這是由於sphinx默認只會從sys.path路徑中執行導入操作,要讓sphinx知道上述模塊的路徑,需要執行如下更改:
# conf.py
import os
import sys
sys.path.insert(0, os.path.abspath('.'))
...
extensions = [
'sphinx.ext.autodoc'
]
做到這一步,就可以執行文檔生成操作:
demo $ make html .
# 或
demo $ sphinx-build . _build/
命令執行完畢就會在 _build/html下生成html文件,其中入口就是index.html。
總結
這就是python自動生成文檔的步驟,更加深入的知識可以參考一下內容:
