Sphinx.ext.apidoc的基本用法
Sphinx是一个用于生成软件文档的工具,它可以帮助开发者自动生成文档,并且提供了许多扩展模块来增强文档的功能。其中一个扩展模块就是Sphinx.ext.apidoc,它可以自动遍历项目源代码中的模块、类、函数等元素,并生成对应的API文档。
Sphinx.ext.apidoc的基本用法非常简单,只需要在Sphinx的配置文件conf.py中进行相应的配置即可。以下是一个基本的配置示例:
# conf.py
# enable the apidoc extension
extensions = [
'sphinx.ext.apidoc'
]
# configure the apidoc extension
apidoc_module_dir = '../src'
apidoc_output_dir = 'api'
apidoc_excluded_paths = ['*tests*']
apidoc_separate_modules = True
# enable the autodoc extension to generate documentation for the modules
extensions.append('sphinx.ext.autodoc')
在这个示例中,我们首先启用了apidoc和autodoc两个扩展模块。然后,我们配置了apidoc模块的一些参数:
- apidoc_module_dir:指定要遍历的源代码目录。通常情况下,我们会把源代码放在项目的src目录中,所以这里指定了../src。
- apidoc_output_dir:指定生成API文档的目录。这里指定为api,表示文档将生成在api目录下。
- apidoc_excluded_paths:指定要排除在文档之外的路径。这里我们使用通配符*tests*来排除所有包含tests的路径,因为通常测试代码不需要生成API文档。
- apidoc_separate_modules:指定是否将每个模块的文档分开生成。如果设置为True,则每个模块的文档将生成在独立的文件中;如果设置为False,则所有模块的文档将生成在同一个文件中。
完成这些配置后,只需要在命令行中执行sphinx-apidoc命令,就可以自动生成API文档了。例如:
sphinx-apidoc -o docs/ ../src
这个命令会遍历../src目录下的所有模块,并根据配置生成相应的API文档。生成的文档将保存在docs/目录中。
下面是一个生成API文档的例子。
首先,我们有一个包含以下几个模块的源代码目录:
mypackage/
__init__.py
module1.py
module2.py
tests/
test_module1.py
test_module2.py
其中module1.py和module2.py分别定义了两个模块,我们希望为它们生成API文档。而test_module1.py和test_module2.py是测试代码,不需要生成API文档。
然后,我们在conf.py中进行如下配置:
# conf.py
extensions = [
'sphinx.ext.apidoc'
]
apidoc_module_dir = '../src'
apidoc_output_dir = 'api'
apidoc_excluded_paths = ['*tests*']
apidoc_separate_modules = True
extensions.append('sphinx.ext.autodoc')
接着,在命令行中执行以下命令:
sphinx-apidoc -o docs/ ../src
执行完毕后,我们可以在docs/api/目录下看到生成的API文档文件。
假设module1.py的源代码如下:
# module1.py
def foo():
"""
This is a function.
"""
pass
class MyClass:
"""
This is a class.
"""
def bar(self):
"""
This is a method.
"""
pass
生成的API文档文件modulename.rst内容如下:
module1 ======= .. automodule:: module1 :members: :undoc-members: :show-inheritance: .. autoclass:: MyClass :members: :undoc-members: :show-inheritance: .. autofunction:: foo
可以看到,文档中出现了module1、MyClass和foo三个元素,它们分别对应module1.py中的模块、类和函数。
这样,我们就成功地使用Sphinx.ext.apidoc扩展模块生成了API文档。通过配置适当的参数,我们可以灵活地控制文档的生成方式,从而生成符合自己需要的API文档。
