为 `sphinx-apidoc` 自定义模板

Customize templates for `sphinx-apidoc`

我最近尝试使用 sphinx-apidoc from Sphinx 从 Python 项目的 API 帮助生成 Sphinx 特定的 reStructuredText。

然而,我得到的结果是:

有人知道我是否可以自定义 sphinx-api 用于输出的模板吗?具体来说,我想:

我认为 "Submodules" 和 "Subpackages" 标题是多余的,因为 packages/modules 的正常标题是 "xxx.yyy package" 和 "xxx.yyy.zzz module"。

上面这个小例子我想要的结构是

在点击包的地方,我在页面上看到的第一件事就是包文档。

或者甚至只是

如果有某种方法可以从视觉上区分 packages/modules(颜色?标志?)而不是冗长的“包”和“模块”。

sphinx-apidoc 脚本使用 apidoc.py 模块。我无法提供详细说明,但为了删除标题或以其他方式自定义输出,您必须编写您自己的此模块版本。没有其他“模板”。

注意,如果API和模块结构稳定,就不需要运行sphinx-apidoc重复。您可以 post-process 根据自己的喜好 一次 生成第一个文件,然后将它们置于版本控制之下。另见 https://whosebug.com/a/28481785/407651

更新

从 Sphinx 2.2.0 开始,sphinx-apidoc 支持模板。参见 https://whosebug.com/a/57520238/407651

FWIW,这是一个完整的脚本,可以在每个 "filename.rst":

旁边的 "filename.rst.new" 文件中进行您想要的更改,这也是我想要的更改
#!/usr/bin/env python

'''
Rearrange content in sphinx-apidoc generated .rst files.

* Move "Module Contents" section to the top.
* Remove headers for "Module Contents", "Submodules" and "Subpackages",
  including their underlines and the following blank line.
'''


import argparse
import glob
import os


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def argument_parser():
    '''
    Define command line arguments.
    '''

    parser = argparse.ArgumentParser(
        description='''
        Rearrange content in sphinx-apidoc generated .rst files.
        '''
        )

    parser.add_argument(
        '-v', '--verbose',
        dest='verbose',
        default=False,
        action='store_true',
        help="""
            show more output.
            """
        )

    parser.add_argument(
        'input_file',
        metavar="INPUT_FILE",
        nargs='+',
        help="""
            file.
            """
        )

    return parser


# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def main():
    '''
    Main program entry point.
    '''

    global args
    parser = argument_parser()
    args = parser.parse_args()

    filenames = [glob.glob(x) for x in args.input_file]
    if len(filenames) > 0:
        filenames = reduce(lambda x, y: x + y, filenames)

    for filename in set(filenames):

        # line_num was going to be for some consistency checks, never
        # implemented but left in place.
        found = {
            'Subpackages': {'contents': False, 'line_num': None},
            'Submodules': {'contents': False, 'line_num': None},
            'Module contents': {'contents': True, 'line_num': None},
            }

        in_module_contents = False
        line_num = 0
        reordered = []
        module_contents = []

        new_filename = '.'.join([filename, 'new'])

        with open(filename, 'r') as fptr:

            for line in fptr:
                line = line.rstrip()
                discard = False

                line_num += 1

                if (
                        in_module_contents
                        and len(line) > 0
                        and line[0] not in ['.', '-', ' ']
                        ):  # pylint: disable=bad-continuation
                    in_module_contents = False

                for sought in found:

                    if line.find(sought) == 0:

                        found[sought]['line_num'] = line_num
                        if found[sought]['contents']:
                            in_module_contents = True

                        discard = True
                        # discard the underlines and a blank line too
                        _ = fptr.next()
                        _ = fptr.next()

                if in_module_contents and not discard:
                    module_contents.append(line)

                elif not discard:
                    reordered.append(line)

                # print '{:<6}|{}'.format(len(line), line)

        with open(new_filename, 'w') as fptr:
            fptr.write('\n'.join(reordered[:3]))
            fptr.write('\n')
            if module_contents:
                fptr.write('\n'.join(module_contents))
                fptr.write('\n')
                if len(module_contents[-1]) > 0:
                    fptr.write('\n')
            if reordered[3:]:
                fptr.write('\n'.join(reordered[3:]))
                fptr.write('\n')


if __name__ == "__main__":
    main()

我实现了 better-apidocsphinx-apidoc 脚本的补丁版本,添加了对模板的完全支持。

它添加了一个 -t/--template 选项,允许传递一个模板目录 必须包含模板文件 package.rstmodule.rst。 看 package.rstmodule.rst 举个例子。这些呈现给例如 http://qnet.readthedocs.io/en/latest/API/qnet.algebra.operator_algebra.html.