自定义`sphinx-apidoc`的模板

est*_*tan 14 python python-sphinx

我一直在使用最近尝试狮身人面像,apidoc狮身人面像,以帮助生成从Python项目的API狮身人面像的具体reStructuredText的.

但是,我得到的结果是:

<code>sphinx-api</code>用于其输出?具体来说,我想:</p>

<ul>
<li>摆脱所有

  • 我的__init__.py文件中的docstring结果直接显示在包下面,因此,如果我单击包名,我首先看到的是包文档.目前,本文档位于每个软件包部分末尾略微奇怪的"模块内容"标题下.
  • 我认为"Submodules"和"Subpackages"标题是多余的,因为包/模块的正常标题是"xxx.yyy package"和"xxx.yyy.zzz module".

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

    • orexplore.components包
      • orexplore.components.mbg120模块
    • orexplore.simulators包
      • orexplore.simulators.test包
        • orexplore.simulators.test.mbg120模块
      • orexplore.simulators.mbg120模块

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

    或者甚至只是

    • orexplore.components
      • orexplore.components.mbg120
    • orexplore.simulators
      • orexplore.simulators.test
        • orexplore.simulators.test.mbg120
    • orexplore.simulators.mbg120

    如果有一些方法可以在视觉上区分包/模块(颜色?会徽?)而不是相当冗长的"包"和"模块".

    Mic*_*erz 8

    我实现了更好的apidoc,这是一个补丁版本的sphinx-apidoc脚本,增加了对模板的全面支持.

    它增加了一个-t/--template选项,允许通过,必须包含模板文件的模板目录package.rstmodule.rst.有关 示例,请参阅 package.rstmodule.rst.这些渲染到例如 http://qnet.readthedocs.io/en/latest/API/qnet.algebra.operator_algebra.html.


    Sco*_*ott 5

    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()
    
    Run Code Online (Sandbox Code Playgroud)


    mzj*_*zjn 4

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

    请注意,如果 API 和模块结构稳定,则无需重复运行 sphinx-apidoc。您可以根据自己的喜好对生成的第一个文件进行一次后处理,然后将它们置于版本控制之下。另请参阅/sf/answers/1993724981/

    更新

    从Sphinx 2.2.0开始,sphinx-apidoc支持模板。请参阅/sf/answers/4026416691/

    • 谢谢@mzjn。我有点怀疑没有办法定制它。在我看来,“sphinx-apidoc”的一个缺点是它没有模板化。你说得对,一旦包结构稳定,我就可以安全地编辑生成的“.rst”。目前情况有点不稳定,但我会忍受这种奇怪的表情,直到它稳定下来。之后我可能可以避免将来运行“sphinx-apidoc”并手动进行任何更新。 (2认同)
    • 从 Sphinx 2.2 开始,apidoc 脚本现在支持模板 (2认同)