zoukankan      html  css  js  c++  java
  • 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文档化

  • 相关阅读:
    Hexo博客搭建教程
    windows7如何查看端口被占用
    openshift rhc
    .net面试题精选
    Java垃圾回收机制
    Maven 入门篇(下)
    Maven 入门篇 ( 上 )
    OPENSHIFT MYSQL使用Navicat远程连接
    ci配置smarty手记
    solr多核配置
  • 原文地址:https://www.cnblogs.com/zhangjpn/p/10797130.html
Copyright © 2011-2022 走看看