繁体   English   中英

使 Sphinx 从 pydoc 生成 RST 类文档

[英]Make Sphinx generate RST class documentation from pydoc

我目前正在将所有现有(不完整)文档迁移到Sphinx

问题在于文档使用Python 文档字符串(模块是用 C 编写的,但可能无关紧要)并且类文档必须转换为可用于 Sphinx 的形式。

sphinx.ext.autodoc ,但它会自动将当前文档字符串放入文档中。 我想根据当前的文档字符串在( RST )中生成一个源文件,然后我可以手动编辑和改进。

您如何将文档字符串转换为 Sphinx 的 RST?

autodoc 确实会生成 RST,只是没有正式的方法可以摆脱它。 获得它的最简单方法是更改sphinx.ext.autodoc.Documenter.add_line方法以向我发送它得到的行。

因为我想要的是一次性迁移,所以输出到标准输出对我来说已经足够了:

def add_line(self, line, source, *lineno):
    """Append one line of generated reST to the output."""
    print(self.indent + line)
    self.directive.result.append(self.indent + line, source, *lineno)

现在 autodoc 会在运行时在 stdout 上打印生成的 RST,您可以简单地将其重定向或复制到其他地方。

猴子修补 autodoc 使其无需编辑任何内容即可工作:

import sphinx.ext.autodoc
rst = []
def add_line(self, line, source, *lineno):
    """Append one line of generated reST to the output."""
    rst.append(line)
    self.directive.result.append(self.indent + line, source, *lineno)
sphinx.ext.autodoc.Documenter.add_line = add_line
try:
    sphinx.main(['sphinx-build', '-b', 'html', '-d', '_build/doctrees', '.', '_build/html'])
except SystemExit:
    with file('doc.rst', 'w') as f:
        for line in rst:
            print >>f, line

据我所知,没有自动化工具可以做到这一点。 因此,我的方法是编写一个小脚本来读取相关模块(基于 sphinc.ext.autodoc)并将文档字符串放入文件(格式适当)中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM