Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add output to interactive Python console blocks in Sphinx docs?

How can I add the output to interactive Python console blocks in Sphinx docs?

For example, so I can do something like:

First set the variable::

    >>> x = 1

Then print the variable::

    >>> print x

And have Sphinx automatically insert the output of print x into the documentation?

I've tried:

  • sphinxcontrib-autorun https://pypi.python.org/pypi/sphinxcontrib-autorun/0.1-20140415 — but it runs each block in a separate interpriter
  • IPython.sphinxext.ipython_directive — but it forces IPython syntax instead of the "traditional" Python console.

Is there anything else that can do this?

like image 467
David Wolever Avatar asked Sep 18 '26 15:09

David Wolever


2 Answers

Okay, I've gone ahead and built one of those here: https://bitbucket.org/wolever/sphinx-contrib/src/tip/autorun2/?at=default

like image 183
David Wolever Avatar answered Sep 20 '26 04:09

David Wolever


The docs for writing an extension for Sphinx is at http://sphinx-doc.org/extdev/index.html#dev-extensions

The only hint I would give is that using self.state.nested_parse(..) will save you a lot of headaches. Here is the simplest extension I have:

class SvnRevisionDirective(Directive):
    """Directive to display subversion revision of the path.
    """
    has_content = True
    required_arguments = 1
    optional_arguments = 1
    final_argument_whitespace = False
    option_spec = {}

    def run(self):
        path = self.arguments[0]
        rev = svntools.Revision(path)   # uses subprocess etc.
        paragraph = nodes.paragraph()
        self.state.nested_parse(
            StringList([
                '**Revision:** r%d' % rev   # you can use regular rst syntax here(!)
            ]), 0, paragraph)
        return [paragraph]

...

def setup(app):
    ...
    app.add_directive('svnrevision', SvnRevisionDirective)

it's used like

.. snvrevision: 'my/file.py'
like image 35
thebjorn Avatar answered Sep 20 '26 03:09

thebjorn