使用Sphinx自动记录Python代码文档

18

这是一个泛化版本的有关Sphinx的先前问题

是否有一种递归自动记录包含类和函数的模块或包的方法?

我认为为每个函数添加autofunctionautomodule指令很愚蠢;必须有一种自动化的方法,否则我看不出使用Sphinx的意义。

澄清:而不是:

.. automodule:: segments.segments

    .. autoclass:: segments.segments.Seg

        .. automethod:: Seg.method_1

        .. automethod:: Seg.method_2

        .. automethod:: Seg.method_3

        .......

        .. automethod:: Seg.method_n
我需要手动剪切和粘贴所有方法名称,并相应地更新文档,我想要一个像这样的命令:
.. automodule:: segments.segments

    .. autoclass:: segments.segments.Seg

        .. MAGIC COMMAND: Automatically print the docstrings and signatures 
           of all Seg() methods.
5个回答

38
我们使用
.. automodule:: module
   :members:

太好了!有什么办法可以告诉Sphinx显示所有成员,而不仅仅是那些有文档字符串的吗?你能给我提供一些相关的资源链接吗?谢谢! - Adam Matan
21
这里写着所有的内容:http://sphinx.pocoo.org/ext/autodoc.html 简而言之,需要添加 :undoc-members: - iElectric

27

16

在Etienne的回答中提到的脚本现已被整合到Sphinx中作为sphinx-apidoc。它正是OP所需要的。它将在Sphinx 1.1中发布,或者可以从Hg仓库获取:

https://bitbucket.org/birkenfeld/sphinx

对我来说它运行得非常好。文档读起来如下:

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

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

我该如何包含<pre>样式块(例如上面的命令帮助输出片段),而不使它们像<code>块一样着色? - Jonathan Hartley

0
我认为为每个函数添加autofunction或automodule指令是愚蠢的;必须有一种自动化的方法,否则我看不出使用Sphinx的意义。

我建议使用Epydoc,它专门从docstrings生成文档。

5
Epydoc似乎已经失效了。与最新的docutils版本不兼容几乎是无法继续使用的原因。http://sourceforge.net/tracker/?func=detail&aid=2895197&group_id=32455&atid=405618 - Pekka Klärck

-8
你想让它比仅指定自动模块更简单吗?即使对于一个大型库,输入所有模块名称只需要5分钟的工作量。
这样做的原因是因为Sphinx很难猜测需要记录哪些内容。
您还可以编写autopackage,它会搜索模块并使用automodule指令(如果automodule尚未执行此操作)。

自动模块会为其中的类和函数生成文档吗?它在这里没有生成。 - Adam Matan
2
它会的,你只需要更仔细地阅读Sphinx文档。所有指令都接受特殊参数,以使它们按照你的意愿运作。 - iElectric
请您能否详细说明或提供链接? - Adam Matan
8
手动操作的问题不在于工作本身,尽管这种方式很麻烦且重复。而在于容易出错。你很可能会漏掉某些内容,而且当你更改源结构时,结果就会过时。 - Jonathan Hartley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接