当前位置: 代码网 > it编程>前端脚本>Python > python使用MkDocs自动生成文档的操作方法

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

2024年06月12日 Python 我要评论
前言python代码注释风格有很多,比较主流的有restructuredtext风格、numpy风格、google风格。自动生成文档的工具也有很多,常见的有:pydocs python环境自带,支持m

前言

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

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

  • pydocs python环境自带,支持markdown,但功能比较简单;
  • sphinx 非常流行,默认支持restructuredtext风格注释,若要支持markdown需要扩展插件支持;
  • mkdocs 优势是能够很好的支持markdown格式来组织文档,支持google风格注释;

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

使用mkdocs

环境

  • python3.9
  • 安装依赖
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

使用介绍

记得提前安装相关依赖。

项目结构

截取部分展示:

├── 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主配置文件

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模块路径:

# 使用(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, 内容示例如下:

version: 2

# 构建文档需要的环境
build:
  os: ubuntu-22.04
  tools:
    python: "3.9"

# 文档工具相关配置
mkdocs:
  configuration: mkdocs.yml

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

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

到此这篇关于python使用mkdocs自动生成文档的操作方法的文章就介绍到这了,更多相关python mkdocs生成文档内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com