You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sphinx无法生成含代码文档的HTML输出,求解决方案及示例

解决Sphinx autodoc不生成代码文档的问题

1. 让Sphinx能找到你的Python模块

打开docs/source/conf.py,在文件开头添加以下代码,把你的项目根目录添加到Python路径中(假设代码文件和docs目录同级):

import os
import sys
sys.path.append(os.path.abspath('../'))

这一步是让Sphinx能成功导入你的Person类所在的模块。

2. 创建文档引用文件

在docs/source目录下新建person.rst文件,内容如下:

Person 模块文档
===============

.. automodule:: person
   :members:
   :undoc-members:
   :show-inheritance:
  • person是你的Python文件名(不带.py后缀),如果类在子模块里(比如myapp.person),就写完整的模块路径
  • :members:会提取类和方法的文档注释
  • :undoc-members:可选,用来包含没有写文档注释的成员

3. 更新索引页的目录结构

打开docs/source/index.rst,找到toctree部分,把新建的person添加进去:

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

   person

这样生成的HTML索引页会显示你的模块文档入口。

4. 确保代码可正常导入

检查你的代码文件,确保能被Python正常导入,比如补上date的导入语句:

from datetime import date

class Person:
    '''
    This class describes a person
    '''
    def __init__(self):
        self.name = ''
        self.birth_date = date.today()
        self.gender = ''

    def set_date_of_birth(self, year: int, month: int, day: int):
        '''
        Sets the value of the birth date.
        :param year: The year.
        :param month: The month.
        :param day: The day.
        :return: None.
        '''
        self.birth_date = date(year, month, day)

模块导入失败的话,Sphinx会跳过该模块的文档生成。

5. 重新生成HTML文档

回到docs目录,运行命令:

make html

现在打开docs/build/html/index.html,就能看到Person类的完整文档了。

内容的提问来源于stack exchange,提问作者Alex Konnen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 08:40:22