Python 是否从sphinx autodoc发出重构文本?
CPython不使用autodoc作为文档,我们使用手写散文 对于PEP3144(ipaddress模块),我想使用sphinx apidoc生成初始参考文档。这意味着我要运行两次传递操作:Python 是否从sphinx autodoc发出重构文本?,python,python-sphinx,autodoc,Python,Python Sphinx,Autodoc,CPython不使用autodoc作为文档,我们使用手写散文 对于PEP3144(ipaddress模块),我想使用sphinx apidoc生成初始参考文档。这意味着我要运行两次传递操作: 使用sphinx apidoc为依赖于autodoc的模块生成sphinx项目 运行sphinx builder,创建新的StructuredText源文件,所有autodoc指令都替换为生成相同输出的内联StructuredText内容和标记 第一步很简单,但我不知道如何进行第二步,甚至想不出好的方法来搜
第一步很简单,但我不知道如何进行第二步,甚至想不出好的方法来搜索这些方面的任何现有项目。不是完整的答案,或多或少是一个起点:
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
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)
sphinx apidoc
将创建
mymodule Module
===============
.. automodule:: mymodule
:members:
:undoc-members:
:show-inheritance:
以下扩展名(或添加到conf.py
):
将为您提供:
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完成的进一步处理必须适应此处的docstring 我也遇到了同样的问题,有一次我使用了非常难看的解决方案来修补Sphinx,请参见。使用autodoc生成的rst文件(因此只有AutoDirections没有完整的py域定义)并扩展它们有什么错?ipaddress已经有了大量的文档字符串,所以,我不想复制粘贴它们,然后手动重新格式化其余的文档。那么,为什么你要复制它们呢?您可以在auto指令之间编写附加文档,并让sphinx进行翻译,无需复制。对不起,也许我不理解你(或你的问题)。@ncoghlan:对提供的两个答案有什么反馈吗?明天我将颁发奖金。@bmu CPython docs构建过程没有启用autodoc(经过深思熟虑的选择)+1,因为我认为这是让autodoc完全格式化rst源代码的唯一方法。autodoc中应该有一个事件来获取它。(另见我的答案)。