python
主页 > 脚本 > python >

python使用MkDocs自动生成文档的操作方法

2024-06-02 | 佚名 | 点击:

python代码注释风格有很多,比较主流的有 reStructuredText风格、numpy风格、Google风格。

自动生成文档的工具也有很多,常见的有:

对于熟悉MarkDown语法的人来说,推荐使用MkDocs,使用起来很方便。

使用MkDocs

环境

1

2

3

4

5

6

mkdocs==1.6.0

mkdocstrings==0.25.1

mkdocstrings-python==1.10.3

mkdocs-autorefs==1.0.1

mkdocs-material==9.5.24

mkdocs-same-dir==0.1.3

使用介绍

记得提前安装相关依赖。

项目结构

截取部分展示:

1

2

3

4

5

6

7

8

9

10

├── pykit_tools  # 源码目录

│   ├── __init__.py

├── docs

│   ├── CHANGELOG-1.x.md

│   ├── CONTRIBUTING.md

│   └── Reference.md

├── .readthedocs.yaml

├── mkdocs.yml

├── README.md

├── requirements_docs.txt

配置文件

mkdocs.yml MkDocs主配置文件

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

site_name: pykit-tools

repo_url: https://github.com/SkylerHu/pykit-tools

docs_dir: .

 

# 配置主题

theme:

  name: readthedocs

  # name: material

  language: zh

 

# 配置文档菜单

nav:

  - 首页: README.md

  - 使用(Usage): docs/Reference.md

  - Release Notes: docs/CHANGELOG-1.x.md

  - 贡献者指南: docs/CONTRIBUTING.md

 

# 插件配置

plugins:

  - search  # 内置插件,在标题中添加了一个搜索栏,允许用户搜索您的文档

  - same-dir  # 插件mkdocs-same-dir

  - autorefs

  - mkdocstrings:

      default_handler: python

      handlers:

        python:

          # 配置解析代码注释的路径

          paths: [pykit_tools]

          options:

            heading_level: 3  # 使用了三级菜单,在docs/Reference.md文档中会有体现

            show_root_heading: true

            show_symbol_type_heading: true

            show_source: false

          selection:

            docstring_style: google

注释生成文档的配置

配置文件中 options 配置详见 mkdocstrings globallocal-options

示例配置docs/Reference.md (截取部分) , 其中:::是特定格式,配置类或者函数的python模块路径:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

# 使用(Usage)

 

## 装饰器

::: decorators.common

    options:  # 会覆盖全局配置

        members:

          - handle_exception

          - time_record

 

::: decorators.cache

    options:

        members:

            - method_deco_cache

            - singleton_refresh_regular

运行与构建

执行 mkdocs serve 后可通过http://127.0.0.1:8000/访问;

执行 mkdocs build --clean 可以构建生成网站site目录,可以将site添加到.gitignore文件中;

site目录中的html、js等文件可用于自行部署成文档服务网站。

部署

免费开源的部署,一般有两个选择:

本文使用了readthedocs网站托管,网站可以使用Github账号登录,即可同步github项目信息,便捷导入生成文档。

部署需要依赖配置文件.readthedocs.yaml, 内容示例如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

version: 2

 

# 构建文档需要的环境

build:

  os: ubuntu-22.04

  tools:

    python: "3.9"

 

# 文档工具相关配置

mkdocs:

  configuration: mkdocs.yml

 

# 安装依赖

python:

  install:

  - requirements: requirements_docs.txt  # 自己维护在项目中的依赖文件

具体导入步骤根据同步的GitHub项目列表,参考指引提示即可完成;

原文链接:
相关文章
最新更新