sphinx.ext.apidoc – 从 Python 包生成 API 文档

8.2 版本新增。

sphinx.ext.apidoc 是一个用于从 Python 包自动生成 Sphinx 源的工具。它以扩展形式提供 sphinx-apidoc 命令行工具,允许它在 Sphinx 构建过程中运行。

该扩展将生成的源文件写入提供的目录,然后 Sphinx 使用 sphinx.ext.autodoc 扩展读取这些文件。

警告

sphinx.ext.apidoc 生成的源文件使用 sphinx.ext.autodoc 来记录所有找到的模块。如果任何模块在导入时有副作用,当运行 sphinx-build 时,autodoc 将执行这些副作用。

如果您记录脚本(而不是库模块),请确保它们的主例程受 if __name__ == '__main__' 条件保护。

配置

apidoc 扩展使用以下配置值

apidoc_modules
类型:
Sequence[dict[str, str | int | bool | Sequence[str] | Set[str]]
默认:
()

描述要记录的模块的字典列表或序列。如果任何字典中未指定值,则使用通用配置值作为默认值。

例如

apidoc_modules = [
    {'path': 'path/to/module', 'destination': 'source/'},
    {
        'path': 'path/to/another_module',
        'destination': 'source/',
        'exclude_patterns': ['**/test*'],
        'max_depth': 4,
        'follow_links': False,
        'separate_modules': False,
        'include_private': False,
        'no_headings': False,
        'module_first': False,
        'implicit_namespaces': False,
        'automodule_options': {
            'members', 'show-inheritance', 'undoc-members'
        },
    },
]

有效键包括

'path'

要记录的模块的路径(必需)。此路径必须是绝对路径或相对于配置目录的路径。

'destination'

生成文件的输出目录(必需)。此目录必须相对于源目录,如果不存在,将创建它。

'exclude_patterns'

参见 apidoc_exclude_patterns

'max_depth'

参见 apidoc_max_depth

'follow_links'

参见 apidoc_follow_links

'separate_modules'

参见 apidoc_separate_modules

'include_private'

参见 apidoc_include_private

'no_headings'

参见 apidoc_no_headings

'module_first'

参见 apidoc_module_first

'implicit_namespaces'

参见 apidoc_implicit_namespaces

'automodule_options'

参见 apidoc_automodule_options

apidoc_exclude_patterns
类型:
序列[str]
默认:
()

要从生成中排除的模式序列。这些可以是字面路径或 fnmatch 风格的模式。

apidoc_max_depth
类型:
int
默认:
4

在生成的目录表中显示子模块的最大深度。

类型:
bool
默认:
False

跟随符号链接。

apidoc_separate_modules
类型:
bool
默认:
False

将每个模块的文档放在单独的页面上。

apidoc_include_private
类型:
bool
默认:
False

为带有前导下划线的“_private”模块生成文档。

apidoc_no_headings
类型:
bool
默认:
False

不为模块/包创建标题。当源文档字符串已包含标题时很有用。

apidoc_module_first
类型:
bool
默认:
False

将模块文档放在子模块文档之前。

apidoc_implicit_namespaces
类型:
bool
默认:
False

默认情况下,sphinx-apidoc 只在 sys.path 中搜索模块。Python 3.3 引入了 PEP 420 隐式命名空间,它允许模块路径结构,例如 foo/bar/module.pyfoo/bar/baz/__init__.py(请注意 barfoo 是命名空间,而不是模块)。

使用 PEP 420 隐式命名空间解释模块路径。

apidoc_automodule_options
类型:
Set[str]
默认:
{'members', 'show-inheritance', 'undoc-members'}

要传递给生成的 automodule 指令的选项。