1 # https://stackoverflow.com/questions/7250659/how-to-use-python-to-programmatically-generate-part-of-sphinx-documentation/18143318
4 from os
.path
import basename
7 from StringIO
import StringIO
9 from io
import StringIO
11 from docutils
.parsers
.rst
import Directive
12 from docutils
import nodes
, statemachine
14 class ExecDirective(Directive
):
15 """Execute the specified python code and insert the output into the document"""
19 oldStdout
, sys
.stdout
= sys
.stdout
, StringIO()
21 tab_width
= self
.options
.get('tab-width', self
.state
.document
.settings
.tab_width
)
22 source
= self
.state_machine
.input_lines
.source(self
.lineno
- self
.state_machine
.input_offset
- 1)
25 exec('\n'.join(self
.content
))
26 text
= sys
.stdout
.getvalue()
27 lines
= statemachine
.string2lines(text
, tab_width
, convert_whitespace
=True)
28 self
.state_machine
.insert_input(lines
, source
)
31 return [nodes
.error(None, nodes
.paragraph(text
= "Unable to execute python code at %s:%d:" % (basename(source
), self
.lineno
)), nodes
.paragraph(text
= str(sys
.exc_info()[1])))]
33 sys
.stdout
= oldStdout
36 app
.add_directive('exec', ExecDirective
)