自定义模板`sphinxapidoc`

2024-10-01 07:32:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近尝试使用来自Sphinxsphinx-apidoc来帮助从Python项目的API生成Sphinx特定的restructedText。在

然而,我得到的结果是:

Default look of <code>sphinx-api</code> result

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

  • 去掉所有的“子模块”、“子包”和“模块内容”标题,并且
  • 让我的__init__.py文件中docstring的结果直接显示在包的下面,这样如果我单击一个包名,我看到的第一件事就是包文档。目前,这个文档被放在每个包部分末尾有点奇怪的“模块内容”标题下。在

“子模块”和“子包”标题是多余的,因为包/模块的正常标题是“xxx.yyy年包装“和”xxx.yyy.zzz公司模块”。在

我希望上面这个小例子的结构是

  • 在orexplore.components公司包裹
    • 在或浏览.components.mbg120模块
  • 在orexplore.模拟器包裹
    • 在orexplore.simulators.test公司包裹
      • 在orexplore.simulators.test公司模块mbg120
    • 在orexplore.simulators.mbg120模块

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

或者甚至只是

  • 在orexplore.components公司
    • 在或浏览.components.mbg120在
  • 在orexplore.模拟器
    • 在orexplore.simulators.test公司
      • 在orexplore.simulators.test公司.mbg120型
  • 在orexplore.simulators.mbg120在

是否有某种方法可以从视觉上区分包装/模块(颜色?会徽?)而不是冗长的“包”和“模块”。在


Tags: 模块文档test标题内容sphinxcomponents公司
3条回答

我实现了better-apidoc,这是sphinx-apidoc脚本的修补版本,添加了对模板的完全支持。在

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

FWIW,这里有一个完整的脚本,让你做你想要的改变,这也是我想要的改变,在一个“文件名.rst.new“每个文件旁边”文件名.rst“:

#!/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()

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

注意,如果API和模块结构稳定,就不需要重复运行sphinxapidoc。您可以将生成的rst文件后处理一次,然后将它们置于版本控制之下。另请参见https://stackoverflow.com/a/28481785/407651。在

更新

从sphinx2.2.0开始,sphinxapidoc支持模板。见https://stackoverflow.com/a/57520238/407651。在

相关问题 更多 >