使用sphinx自动生成Python类和模块文档

25 投票
1 回答
18955 浏览
提问于 2025-04-15 13:51

我安装了Sphinx,是为了给我正在开发的一些Python模块和类写文档。虽然这种标记语言看起来很不错,但我还没能自动生成Python代码的文档。

基本上,我有一个这样的Python模块:

SegLib.py

里面有一个叫做Seg的类。我希望在生成的Sphinx文档中显示这个类和模块的文档字符串,并添加一些格式化的文本。

我的index.rst文件看起来是这样的:

Contents:

.. toctree::
:maxdepth: 2

chapter1.rst

chapter1.rst是:

This is a header
================
Some text, *italic text*, **bold text**

* bulleted list.  There needs to be a space right after the "*"
* item 2

.. note::
   This is a note.

See :class:`Seg`

但是Seg只是以粗体显示,并没有链接到自动生成的类文档。

尝试以下方法也没有帮助:

See :class:`Seg`
Module :mod:'SegLib'
Module :mod:'SegLib.py'

编辑:把SegLib改成了segments(谢谢,iElectric!),并把chapter1.rst改成:

The :mod:`segments` Module
--------------------------

.. automodule:: segments.segments

.. autoclass:: segments.segments.Seg

不过,我还是无法让Sphinx直接记录类中的函数,或者更好的是,自动把类中的所有函数添加到文档里。我尝试了:

.. autofunction:: segments.segments.Seg.sid

结果是:

autodoc can't import/find function 'segments.segments.Seg.sid', it reported error: "No module named Seg"

有没有什么简单的方法可以自动记录函数和类呢?

1 个回答

18

在文件的开头添加:

.. module:: SegLib

试试用 :autoclass: 这个指令来为类写文档。

顺便说一下:模块的名字应该用小写字母。

编辑: 我从阅读其他源文件中学到了很多

撰写回答