verilog: add sv_maps iterators
[ghdl-vlg.git] / doc / exec.py
blobf6ad8a8e88ace00d3fcf56afcb245e1ed450c5c3
1 # https://stackoverflow.com/questions/7250659/how-to-use-python-to-programmatically-generate-part-of-sphinx-documentation/18143318
3 import sys
4 from os.path import basename
6 try:
7 from StringIO import StringIO
8 except ImportError:
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"""
16 has_content = True
18 def run(self):
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)
24 try:
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)
29 return []
30 except Exception:
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])))]
32 finally:
33 sys.stdout = oldStdout
35 def setup(app):
36 app.add_directive('exec', ExecDirective)