自动生成所有Python包内容的文档

56 投票
4 回答
29345 浏览
提问于 2025-04-16 09:30

我正在尝试使用 Sphinx 自动生成我的代码库的基本文档。不过,我在让 Sphinx 递归扫描我的文件时遇到了困难。

我的 Python 代码库有这样的文件夹结构:

<workspace>
└── src
    └── mypackage
        ├── __init__.py
        │   
        ├── subpackageA
        │   ├── __init__.py
        │   ├── submoduleA1
        │   └── submoduleA2
        │   
        └── subpackageB
            ├── __init__.py
            ├── submoduleB1
            └── submoduleB2

我在 <workspace> 目录下运行了 sphinx-quickstart,所以现在我的结构变成了:

<workspace>
├── src
│   └── mypackage
│       ├── __init__.py
│       │
│       ├── subpackageA
│       │   ├── __init__.py
│       │   ├── submoduleA1
│       │   └── submoduleA2
│       │
│       └── subpackageB
│           ├── __init__.py
│           ├── submoduleB1
│           └── ubmoduleB2
│
├── index.rst
├── _build
├── _static
└── _templates  

我看过 快速入门教程,虽然我还在努力理解文档,但里面的表述让我担心 Sphinx 会假设我需要手动为代码库中的每个模块、类和函数创建文档文件。

不过,我注意到了 "automodule" 这个语句,并且在快速入门时启用了 autodoc,所以我希望大部分文档可以自动生成。我修改了我的 conf.py 文件,把我的 src 文件夹添加到 sys.path 中,然后修改了我的 index.rst 文件以使用 automodule。现在我的 index.rst 看起来是这样的:

Contents:

.. toctree::
   :maxdepth: 2

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

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

.. automodule:: alphabuyer
   :members:

我在子包中定义了几十个类和函数。然而,当我运行:

sphinx-build -b html . ./_build

时,它报告:

updating environment: 1 added, 0 changed, 0 removed

这似乎没有成功导入我包中的任何内容。查看生成的 index.html,"Contents:" 旁边什么都没有。索引页面只显示 "mypackage (module)",但点击后也显示没有内容。

我该如何指示 Sphinx 递归解析一个包,并自动为它遇到的每个类、方法和函数生成文档,而不需要手动列出每个类呢?

4 个回答

6

注意

为了让 Sphinx(其实是执行 Sphinx 的 Python 解释器)找到你的模块,这个模块必须是可以被导入的。也就是说,模块或者包必须在 sys.path 的某个目录下——你需要在配置文件中调整你的 sys.path。

所以,去你的 conf.py 文件里添加:

import an_example_pypi_project.useful_1
import an_example_pypi_project.useful_2

现在你的 index.rst 文件看起来是:

.. toctree::
   :glob:

   example
   an_example_pypi_project/*

然后运行

make html

60

你可以试试使用sphinx-apidoc。

$ sphinx-apidoc --help
Usage: sphinx-apidoc [options] -o <output_path> <module_path> [exclude_paths, ...]

Look recursively in <module_path> for Python modules and packages and create
one reST file with automodule directives per package in the <output_path>.

你可以把sphinx-apidoc和sphinx-quickstart结合起来,这样就能创建一个完整的文档项目:

$ sphinx-apidoc -F -o docs project

这个命令会用sphinx-quickstart生成一个完整的项目,并在<module_path>(项目)中递归查找Python模块。

18

也许你可以试试 apigen.py 这个工具: https://github.com/nipy/nipy/tree/master/tools

这个工具在这里有个简单的介绍: http://comments.gmane.org/gmane.comp.python.sphinx.devel/2912

或者更好的是,使用 pdoc


更新:在 Sphinx 版本 1.1 中增加了 sphinx-apidoc 这个工具。

撰写回答