sphinx-python文档化

概述

下文讲述使用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自动生成文档的步骤,更加深入的知识可以参考一下内容:

reStructureText文档
conf.py配置文件说明
sphinx-build命令
python文档化

转载于:https://www.cnblogs.com/zhangjpn/p/10797130.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值