1. 程式人生 > 其它 >Sphinx根據google風格docstring生成文件

Sphinx根據google風格docstring生成文件

技術標籤:Python

安裝Sphinx

pip install sphinx

使用

1. 假設存在如下test.py

def say_hello(name='world'):
    """say hello to someone

    Say hello to the people who have the name you given.

    Args:
        name (str): The people's name you want to greet. world by default.

    """
print(f"Hello {name}!")

假設我們在docs目錄下存放文件,source目錄下存放原始碼。存在目錄結構如下:

work
├─docs
└─source
    └─test.py

2. 在docs目錄下執行sphinx-quikstart

sphinx-quickstart

根據提示輸入完成配置
注:zh_CN代表簡體中文

λ sphinx-quickstart.exe
Welcome to the Sphinx 3.4.1 quickstart utility.

Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).

Selected root path: .

You have two options for placing the build directory for Sphinx output.
Either, you use a directory "_build" within the root path, or you separate
"source" and "build" directories within the root path.
> Separate source and build directories (y/n) [n]: y

The project name will occur in several places in the built documentation.
> Project name: test
> Author name(s): hui
> Project release []: 0.1

If the documents are to be written in a language other than English,
you can select a language here by its language code. Sphinx will then
translate text that it generates into that language.

For a list of supported codes, see
https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-language.
> Project language [en]: zh_CN

...

此時,sphinx幫我們在docs目錄下建立了一些檔案,目錄結構如下:

work
├─docs
│  │  make.bat
│  │  Makefile
│  │
│  ├─build
│  └─source
│      │  conf.py
│      │  index.rst
│      │
│      ├─_static
│      └─_templates
└─source
        test.py

3. 配置conf.py

3.1 修改原始碼位置: 在這裡插入圖片描述

將如上圖所示的程式碼註釋去掉,修改成自己的原始檔所在目錄:

import os
import sys
sys.path.
insert(0, os.path.abspath('../../source'))

3.2 新增napoleon擴充套件

extensions列表中新增sphinx.ext.napoleon

extensions = [
    'sphinx.ext.napoleon',
]

儲存。
更多設定參考:
https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html?highlight=google

3.3 生成rst檔案

在work目錄下執行sphinx-apidoc -f -o docs/source projectdir

λ sphinx-apidoc.exe -f -o docs/source source
Creating file docs/source\test.rst.
Creating file docs/source\modules.rst.

3.4 進入docs目錄,執行make html生成html文件到build目錄

λ cd docs
λ make html
Running Sphinx v3.4.1
loading translations [zh_CN]... done
making output directory... done

...
省略輸出資訊
...

Running Sphinx v3.4.1
loading translations [zh_CN]... done
making output directory... done

進入build/html資料夾,開啟index.html,點進去索引或模組索引就能看到我們之前建立的函式的文件了:
在這裡插入圖片描述
需要注意的是,sphinx在make html或其他檔案時,是根據之前生成的rst檔案去生成的,所以要保證前面生成的rst檔案可以被找到。在make.bat中,預設是從source目錄中去獲取rst檔案,生成到build目錄中。