关于python:自定义sphinx-apidoc的模板

Customize templates for `sphinx-apidoc`

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

但是,我得到的结果是:

Default look of <x0>结果

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

  • 删除所有"子模块","子包"和"模块内容"标题,以及
  • __init__.py文件中docstring的结果直接显示在软件包的下面,因此,如果单击软件包名称,我首先看到的是软件包文档。目前,该文档位于每个软件包部分末尾的"模块内容"标题下。

我认为"子模块"和"子包"标题是多余的,因为包/模块的常规标题是" xxx.yyy包"和" xxx.yyy.zzz模块"。

我希望上面的小示例的结构是

  • 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

是否有某种方法可以从视觉上区分包装/模块(颜色?标志?),而不是用词"包装"和"模块"。


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

它添加了-t/--template选项,允许传递模板目录,该目录
必须包含模板文件package.rstmodule.rst
看到


模块
举个例子这些呈现给例如
http://qnet.readthedocs.io/en/latest/API/qnet.algebra.operator_algebra.html。


FWIW,这是一个脚本的完整技巧,可以在每个" filename.rst"旁边的" filename.rst.new"文件中进行所需的更改,这也是我所需的更改:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#!/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('\
'
.join(reordered[:3]))
            fptr.write('\
'
)
            if module_contents:
                fptr.write('\
'
.join(module_contents))
                fptr.write('\
'
)
                if len(module_contents[-1]) > 0:
                    fptr.write('\
'
)
            if reordered[3:]:
                fptr.write('\
'
.join(reordered[3:]))
                fptr.write('\
'
)


if __name__ =="__main__":
    main()

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

请注意,如果API和模块结构稳定,则无需重复运行sphinx-apidoc。您可以按自己的喜好对生成的rst文件进行一次后处理,然后将其置于版本控制下。另请参阅https://stackoverflow.com/a/28481785/407651。

更新资料

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