API文档生成(sphinx)

发布时间 2024-01-09 09:47:56作者: 一枚码农

1.安装

pip install Sphinx

2.使用

2.1文档手册

Sphinx 1.3.1 中文手册 (推荐查看)
教程
https://fengxc.me/基于python注释使用sphinx自动化生成API文档.html

2.2创建工程

新建一个文件夹sphinx_test, 并创建两个子文件夹code, doc。目录结构如下:
image

进去到doc目录, 打开powershell, 执行下边命令创建工程
sphinx-quickstart
image

输入y,回车
image

在这里设置工程名称、作者、版本信息、语言(中文用zh_CN表示)等
image

2.3修改配置

打开doc/source/conf.py, 修改一些内容

// 如果需要自动生成API文档,sphinx.ext.autodoc这个很关键
extensions = [
    'sphinx.ext.autodoc',
]

// 配置项目路径:
import os
import sys
sys.path.insert(0, os.path.abspath('../../code'))   // 这里的地址是代码路径地址 如果code下面有__init__.py文件,则可以路径为../../。

2.4生成rst文件

在code文件夹中编写自己的python代码
image

image

使用sphinx-apidoc生成rst文件,-o 后面跟的是保存rst文件的路径,你的index.rst文件在哪个目录,就指定哪个目录,然后最后面是代码路径

sphinx-apidoc -o ./source ../code
image

2.5生成html

在doc目录下,使用make命令生成html文件

使用前,先清除一下之前的生成文件
.\make.bat clean
image

生成html, (也可以生成pdf和其他的文档类型)
.\make.bat html
image

这块有个红色的warning,我们后面再来解决这个问题,先暂且放着。

2.6效果展示

现在我们用浏览器打开doc/build/html/index.html,显示如下:
image

这是不是和我们平时看到的python文档不太一样,那是因为我们的主题没有选对

2,7改变sphinx主题

安装主题
pip install sphinx_rtd_theme

导入模块:修改source/conf.py文件

# 导入模块
import sphinx_rtd_theme

# html_theme = "alabaster"修改如下,加上html_theme_path
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

重新生成html

// 在doc目录下执行
.\make.bat clean
.\make.bat html

效果展示
image

问题修复

不知道大家有没有发现,上面生成的文档左边导航栏下面是没有内容CONTENTS的,本来应该是像下面这样的:
image

还记得上面提到的在make html时的那个Warning么,这就是那个导致的

那个warning的意思是说,modules.rst没有被包含,没有被什么包含呢,是没有在index.rst里面包含,毕竟我们显示是用的index.rst。

所以我们需要在index.rst里面加上modules,不知道是不是这个版本的问题,我在好多教程里面都没有提到这个,所以踩了个坑。

修改后如下(source/index.rst):

.. SphinxTest documentation master file, created by
   sphinx-quickstart on Mon Jan  8 16:51:13 2024.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to SphinxTest's documentation!
======================================

.. toctree::
   :maxdepth: 2
   :caption: Contents:
   
   modules


Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

之后,再运行make clean和make html,则warning消失,页面上会显示CONTENTS