目錄
前言:
項目層級
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, includingliteral blocks::$ python example_google.pySection 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 ineither the ``Attributes`` section of the module docstring, or in aninline docstring immediately following the variable.Either form is acceptable, but the two should not be mixed. Chooseone convention to document module level variables and be consistentwith it.Todo:* For module TODOs* You have to also use