不是一个完整的答案,或多或少是一个起点:
autodoc
将自动指令转换为 python 指令。因此可以使用自动文档事件来获取翻译后的 python 指令。
例如,如果您有以下内容mymodule.py
:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This is my module.
"""
def my_test_func(a, b=1):
"""This is my test function"""
return a + b
class MyClass(object):
"""This is my class"""
def __init__(x, y='test'):
"""The init of my class"""
self.x = float(x)
self.y = y
def my_method(self, z):
"""This is my method.
:param z: a number
:type z: float, int
:returns: the sum of self.x and z
:rtype: float
"""
return self.x + z
sphinx-apidoc
将创建
mymodule Module
===============
.. automodule:: mymodule
:members:
:undoc-members:
:show-inheritance:
以下扩展名(或对 的补充conf.py
):
NAMES = []
DIRECTIVES = {}
def get_rst(app, what, name, obj, options, signature,
return_annotation):
doc_indent = ' '
directive_indent = ''
if what in ['method', 'attribute']:
doc_indent += ' '
directive_indent += ' '
directive = '%s.. py:%s:: %s' % (directive_indent, what, name)
if signature: # modules, attributes, ... don't have a signature
directive += signature
NAMES.append(name)
rst = directive + '\n\n' + doc_indent + obj.__doc__ + '\n'
DIRECTIVES[name] = rst
def write_new_docs(app, exception):
txt = ['My module documentation']
txt.append('-----------------------\n')
for name in NAMES:
txt.append(DIRECTIVES[name])
print '\n'.join(txt)
with open('../doc_new/generated.rst', 'w') as outfile:
outfile.write('\n'.join(txt))
def setup(app):
app.connect('autodoc-process-signature', get_rst)
app.connect('build-finished', write_new_docs)
会给你:
My module documentation
-----------------------
.. py:module:: mymodule
This is my module.
.. py:class:: mymodule.MyClass(x, y='test')
This is my class
.. py:method:: mymodule.MyClass.my_method(z)
This is my method.
:param z: a number
:type z: float, int
:returns: the sum of self.x and z
:rtype: float
.. py:function:: mymodule.my_test_func(a, b=1)
This is my test function
然而autodoc
,当翻译完成时不会发出任何事件,因此 autodoc 所做的进一步处理必须适应此处的文档字符串。