Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Sphinx generate RST class documentation from pydoc

I'm currently migrating all existing (incomplete) documentation to Sphinx.

The problem is that the documentation uses Python docstrings (the module is written in C, but it probably does not matter) and the class documentation must be converted into a form usable for Sphinx.

There is sphinx.ext.autodoc, but it automatically puts current docstrings to the document. I want to generate a source file in (RST) based on current docstrings, which I could then edit and improve manually.

How would you transform docstrings into RST for Sphinx?

like image 506
Michal Čihař Avatar asked Apr 19 '10 14:04

Michal Čihař


People also ask

What is RST Sphinx?

RST stands for ReStructured Text. It is the standard markup language used for documenting python packages. Sphinx is the Python package that generates an html website from RST files, and it is what we are using to generate this site.

What does Sphinx Autodoc do?

autodoc imports the modules to be documented. If any modules have side effects on import, these will be executed by autodoc when sphinx-build is run. If you document scripts (as opposed to library modules), make sure their main routine is protected by a if __name__ == '__main__' condition.


2 Answers

The autodoc does generate RST only there is no official way to get it out of it. The easiest hack to get it was by changing sphinx.ext.autodoc.Documenter.add_line method to emit me the line it gets.

As all I want is one time migration, output to stdout is good enough for me:

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)

Now autodoc prints generated RST on stdout while running and you can simply redirect or copy it elsewhere.

like image 158
Michal Čihař Avatar answered Nov 10 '22 11:11

Michal Čihař


monkey patching autodoc so it works without needing to edit anything:

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
like image 33
srepmub Avatar answered Nov 10 '22 09:11

srepmub