Python 使用sphinx生成API文档

2023-12-25 20:30:38

目录

前言:

项目层级

Python项目docstring规范

Example Google Style Python Docstrings

Example NumPy Style Python Docstrings

reStructuredText Style

设置代码docstrings风格(pycharm)

安装sphinx

创建sphinx文档项目

配置conf.py文件

编译代码为api文档

编译文档(windows)

?编辑

设置API文档主题样式

异常处理

异常1:无法生成rst文件

异常2:WARNING: autodoc: failed to import module xxx;WARNING: autodoc: failed to import module 'xxx'; the following exception was raised:No module named 'xxx'

异常3:Encoding error:'utf8' codec can't decode byte 0xc0 in position 44:invalid start byte


前言:

最近需要把项目生成API文档,在网上找了下发现sphinx这个框架用的比较多,研究了一下,发现还是挺赞的,只不过纸上得来终觉浅,绝知此事要躬行,别人的项目结构啥的和自己不一样,网上基本都是单目录的层级,但是实际项目往往都会有比较深的层级关系,所以还是踩了不少坑,在此结合自己的项目总结一下。


项目层级


一般情况真实项目都是会存在多种层级关系的,这是小编做的一个项目的层级结构: 

po_pattern/
├── __init__.py
├── config/
│ ├── env_const.py
├── pages/
│ ├── __init__.py
│ ├── APage.py
│ ├── BPage.py
└── testcase/
├── __init__.py
├── conftest.py
├── scenario_part1_test.py
├── scenario_part2_test.py


Ps:po上面还有一级项目目录,跟源码目录同级创建doc目录然后切换到doc目录创建文档项目
创建文档项目

Python项目docstring规范

sphinx支持多种docstring规范,包括:restructuredtext、Google 风格、NumPy 风格。

Google风格的docstring:

注意:docstring中的代码描述和关键字都要隔一行书写,不然生成的API文档中的关键字无法转义

如下:函数的描述参数关键字Args、Returns关键字,中间都需要换一行不换行无法转义关键字。

Example Google Style Python Docstrings

"""Example function with types documented in the docstring.

    :pep:`484` type annotations are supported. If attribute, parameter, and
    return types are annotated according to `PEP 484`_, they do not need to be
    included in the docstring:

    Args:
        param1 (int): The first parameter.
        param2 (str): The second parameter.

    Returns:
        bool: The return value. True for success, False otherwise.
    """

完整Google style docstrings

"""Example Google style docstrings.

This module demonstrates documentation as specified by the `Google Python
Style Guide`_. Docstrings may extend over multiple lines. Sections are created
with a section header and a colon followed by a block of indented text.

Example:
    Examples can be given using either the ``Example`` or ``Examples``
    sections. Sections support any reStructuredText formatting, including
    literal blocks::

        $ python example_google.py

Section breaks are created by resuming unindented text. Section breaks
are also implicitly created anytime a new section starts.

Attributes:
    module_level_variable1 (int): Module level variables may be documented in
        either the ``Attributes`` section of the module docstring, or in an
        inline docstring immediately following the variable.

        Either form is acceptable, but the two should not be mixed. Choose
        one convention to document module level variables and be consistent
        with it.

Todo:
    * For module TODOs
    * You have to also use

文章来源:https://blog.csdn.net/TalorSwfit20111208/article/details/134840110
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。