[英]Emit reStructuredText from sphinx autodoc?
CPython 的文档不使用 autodoc - 我们使用手写散文。
对于 PEP 3144(ipaddress 模块),我想使用 sphinx-apidoc 生成初始参考文档。 这意味着我要运行两遍操作:
使用 sphinx-apidoc 为依赖于 autodoc 的模块发出 Sphinx 项目
运行创建新 reStructuredText 源文件的 sphinx 生成器,所有 autodoc 指令都替换为内联 reStructuredText 内容和产生相同输出的标记
第一步很简单,但我不知道如何做第二步,甚至想不出沿着这些路线搜索任何现有项目的好方法。
我有同样的问题,有一次生成文档我使用了非常丑陋的解决方案来修补 Sphinx,请参阅Make Sphinx generate RST class documentation from pydoc 。
不是一个完整的答案,或多或少是一个起点:
autodoc
将自动指令转换为 python 指令。 所以可以使用 autodoc 事件来获取翻译的 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 完成的进一步处理必须适应此处的文档字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.