diff --git a/Readme.rst b/Readme.rst index e1bca5a..388a12d 100644 --- a/Readme.rst +++ b/Readme.rst @@ -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 ------------ @@ -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:: diff --git a/sphinx_execute_code/__init__.py b/sphinx_execute_code/__init__.py index 9925521..12e68b6 100644 --- a/sphinx_execute_code/__init__.py +++ b/sphinx_execute_code/__init__.py @@ -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 @@ -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' @@ -139,7 +135,10 @@ 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 @@ -147,6 +146,7 @@ def run(self): output.append(code_results) return output + def setup(app): """ Register sphinx_execute_code directive with Sphinx """ app.add_directive('execute_code', ExecuteCode)