代码之家  ›  专栏  ›  技术社区  ›  Michal Čihař

使sphinx从pydoc生成RST类文档

  •  7
  • Michal Čihař  · 技术社区  · 15 年前

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

    问题是文档使用 Python docstrings (模块是用C语言编写的,但这可能无关紧要),并且类文档必须转换为可供斯芬克斯使用的格式。

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

    如何将docstring转换为sphinx的rst?

    3 回复  |  直到 10 年前
        1
  •  13
  •   Michal Čihař    15 年前

    AutoDoc只会生成RST,没有正式的方法可以将其从RST中取出。最容易得到的黑客是通过改变 sphinx.ext.autodoc.Documenter.add_line 方法向我发出它得到的行。

    因为我只需要一次迁移,所以输出到stdout对我来说已经足够好了:

    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,您可以简单地将其重定向或复制到其他地方。

        2
  •  2
  •   srepmub    10 年前

    Monkey Patching 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
    
        3
  •  0
  •   Alex Gaynor    15 年前

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

    推荐文章