Sphinx的最佳实践

16 投票
3 回答
7258 浏览
提问于 2025-04-16 18:13

我刚开始使用Sphinx工具来为我的代码生成文档。但是我有点困惑,因为这并没有我想象中那么简单。我是这样创建Sphinx文档的:

sphinx-quickstart

然后我在“source”文件夹里创建了我的*.rst文件。看起来我需要为每个想要生成文档的模块创建一个*.rst文件。比如对于test.py,我创建了test.rst。在test.rst里面,我写了:

.. automodule:: test
    :members:
    :show-inheritance:

然后在test.py里面,我写了:

"""
.. module:: test
   :platform: Unix, Windows
   :synopsis: A useful module indeed.
"""

接着我用以下命令生成文档:

sphinx-build -b html source/ build/

一切都按预期工作,但问题是这并没有我想象中那么简单。我想应该有更简单的方法来跳过一些步骤。我在想是否有办法为一个包里的所有模块生成文档,而不是为每个模块都生成一个*.rst文件。

谢谢。

3 个回答

3

你可以使用 sphinx-apidoc 来为你生成 rst 文件。

sphinx-apidoc -o outputdir pythondir

下面是一个运行的示例输出:

% sphinx-apidoc -o source/ ../
File source/module1.rst already exists, skipping.
File source/module2.rst already exists, skipping.
Creating file source/module3.rst.

rst docs updated in source/.

注意, sphinx-apidoc 不会修改已经存在的文件,如果你想强制覆盖它们,可以使用 -f 这个选项。

10

快速记录你的应用程序有一个简单的方法,就是像往常一样在类和方法里写文档字符串(docstrings),如果需要的话,再在 .rst 文件中补充说明。

template.rst:

Templating
----------
Notes about templating would go here.

.. automodule:: myapp.lib.template
    :members:
    :undoc-members:

    .. py:attribute:: filepath

        Full path to template file. This attribute is added in runtime, so
        it has to be documented manually.

myapp/lib/template.py:

class Template(object):
    '''
    Class for rendering templates.

    Usage example::

        >>> t = Template('somefile')
        >>> document = t.render(variables={'ID': 1234})

    Rendered document is always returned as a unicode string.
    '''

    def render(self, **args):
        '''
        Render template. Keyword arguments are passed `as-is` to renderer.
        '''
13

没有更简单的方法了。Sphinx并不是像epydoc那样的API文档生成工具,它更注重手动编写文档。因此,你需要自己写很多文档。

这样做的好处是,你可以写的不仅仅是API文档(比如教程、使用指南,甚至是最终用户的文档),而且你可以更有逻辑地组织API文档,而不仅仅是简单的按字母顺序列出可用的对象。如果做得好,这种文档通常更容易理解,也更容易使用。

可以看看一些知名项目的文档(比如 Werkzeug 或者 Sphinx 自己的文档),了解一些最佳实践。

撰写回答