使用Sphinx自动生成Python文档
这是一个关于Sphinx的更一般化的问题,参考了之前的一个提问。
有没有办法可以递归地自动生成包含类和函数的模块或包的文档呢?
我觉得每个函数都加上autofunction
或automodule
这样的指令太麻烦了;一定有办法可以自动化这个过程,否则我觉得使用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 个回答
16
Etienne提到的脚本,现在已经被整合进Sphinx,叫做sphinx-apidoc。它正好满足了提问者的需求。这个功能预计会在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>.
27
为了让事情变得简单一些,你可以使用这个脚本(在页面底部可以找到最新版本):http://bitbucket.org/birkenfeld/sphinx/issue/98/add-the-autogenerate-script-to-sphinx
这个脚本会分析你的包和模块,然后生成所有必要的文件,以便从文档字符串中构建文档。
我是这个脚本的原作者。
更新
这个脚本现在已经成为 Sphinx 1.1 的一部分,叫做 apidoc。
38
我们使用
.. automodule:: module
:members: