Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions Readme.rst
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ hide_headers
filename
If specified, will load code from a file (relative to sphinx doc root)
and ignore content.
precode
code which will also run, but not show up in the code window (e.g. for imports)

execute_code
------------
Expand Down Expand Up @@ -75,6 +77,17 @@ We can also hide the code input, showing only the executed code results::

Suppressing output headers
--------------------------
Suppressing the 'Headers' outputs for Code and Results header::

.. execute_code::
:hide_headers:
:precode: from MyPackage import MyClass

val = MyClass.test()
print(val)

Hiding imports
--------------------------
Suppressing the 'Headers' outputs for Code and Results header::

.. execute_code::
Expand Down
16 changes: 8 additions & 8 deletions sphinx_execute_code/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,28 +54,25 @@ class ExecuteCode(Directive):
'hide_headers': directives.flag,
'filename': directives.path,
'hide_filename': directives.flag,
'precode': directives.unchanged
}

@classmethod
def execute_code(cls, code):
""" Executes supplied code as pure python and returns a list of stdout, stderr

Args:
code (string): Python code to execute

Results:
(list): stdout, stderr of executed python code

Raises:
ExecutionError when supplied python is incorrect

Examples:
>>> execute_code('print "foobar"')
'foobar'
"""

output = StringIO.StringIO()
err = StringIO.StringIO()
output = StringIO()
err = StringIO()

sys.stdout = output
sys.stderr = err
Expand All @@ -99,7 +96,6 @@ def execute_code(cls, code):

def run(self):
""" Executes python code for an RST document, taking input from content or from a filename

:return:
"""
language = self.options.get('language') or 'python'
Expand Down Expand Up @@ -139,14 +135,18 @@ def run(self):
# Show the code results
if not 'hide_headers' in self.options:
output.append(nodes.caption(text='Results'))
code_results = self.execute_code(code)
# add precode
if 'precode' in self.options:
code = self.options['precode'] + '\n' + code
code_results = self.execute_code( code)
code_results = nodes.literal_block(code_results, code_results)

code_results['linenos'] = 'linenos' in self.options
code_results['language'] = output_language
output.append(code_results)
return output


def setup(app):
""" Register sphinx_execute_code directive with Sphinx """
app.add_directive('execute_code', ExecuteCode)
Expand Down