module sphinxext.sphinx_runpython_extension

Inheritance diagram of pyquickhelper.sphinxext.sphinx_runpython_extension

Short summary

module pyquickhelper.sphinxext.sphinx_runpython_extension

Defines runpython directives. See Tutorial: Writing a simple extension

source on GitHub

Classes

class

truncated documentation

runpython_node

defines runpython node

RunPythonCompileError

exception raised when a piece of code included in the documentation does not compile

RunPythonDirective

Extracts script to run described by ``

RunPythonExecutionError

Exception raised when a piece of code included in the documentation raises an exception.

Functions

function

truncated documentation

depart_runpython_node

What to do when leaving a node runpython_node the function should have different behaviour, depending on …

run_python_script

Executes a script python as a string.

setup

setup for runpython (sphinx)

visit_runpython_node

What to do when visiting a node runpython_node the function should have different behaviour, depending …

Methods

method

truncated documentation

modify_script_before_running

Takes the script as a string and returns another string before it is run. It does not modify what is displayed. …

run

Extracts the information in a dictionary, runs the script.

Documentation

Defines runpython directives. See Tutorial: Writing a simple extension

source on GitHub

exception pyquickhelper.sphinxext.sphinx_runpython_extension.RunPythonCompileError[source][source]

Bases: Exception

exception raised when a piece of code included in the documentation does not compile

source on GitHub

class pyquickhelper.sphinxext.sphinx_runpython_extension.RunPythonDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source][source]

Bases: docutils.parsers.rst.Directive

Extracts script to run described by .. runpython:: and modifies the documentation.

A python script which generates documentation

The following code prints the version of Python on the standard output. It is added to the documentation:

.. runpython::
    :showcode:

    import sys
    print("sys.version_info=", str(sys.version_info))

If give the following results:

    sys.version_info= sys.version_info(major=3, minor=7, micro=2, releaselevel='final', serial=0)

Options showcode can be used to display the code. The option rst will assume the output is in RST format and must be interpreted. showout will complement the RST output with the raw format.

The directive has a couple of options:

  • :assert: condition to validate at the end of the execution to check it went right

  • :current: runs the script in the source file directory

  • :exception: the code throws an exception but it is expected. The error is displayed.

  • :indent:<int> to indent the output

  • :language:: changes :: into .. code-block:: language

  • :nopep8: if present, leaves the code as it is and does not apply pep8 by default, see remove_extra_spaces_and_pep8.

  • :numpy_precision: <precision>, run numpy.set_printoptions(precision=...), precision is 3 by default

  • :process: run the script in an another process

  • :restore: restore the local context stored in sphinx application by the previous call to runpython

  • :rst: to interpret the output, otherwise, it is considered as raw text

  • :setsysvar: adds a member to sys module, the module can act differently based on that information, if the value is left empty, sys.enable_disabled_documented_pieces_of_code will be be set up to True.

  • :showcode: to show the code before its output

  • :showout if :rst: is set up, this flag adds the raw rst output to check what is happening

  • :sin:<text_for_in> which text to display before the code (by default In)

  • :sout:<text_for_in> which text to display before the output (by default Out)

  • :sphinx: by default, function nested_parse_with_titles is used to parse the output of the script, if this option is set to false, public_doctree.

  • :store: stores the local context in sphinx application to restore it later by another call to runpython

  • :toggle: add a button to hide or show the code, it takes the values code or out or both. The direction then hides the given section but adds a button to show it.

  • :warningout: name of warnings to disable (ex: ImportWarning), separated by spaces

Option rst can be used the following way:

.. runpython::
    :rst:

    for l in range(0,10):
        print("**line**", "*" +str(l)+"*")
        print('')

Which displays interpreted RST:

line 0

line 1

line 2

line 3

line 4

line 5

line 6

line 7

line 8

line 9

If the directive produces RST text to be included later in the documentation, it is able to interpret docutils directives and Sphinx directives with function nested_parse_with_titles Unless process option is enabled, global variables cannot be used. sphinx-autorun offers a similar service except it cannot produce compile RST content, hide the source and a couple of other options. Option toggle can hide or unhide the piece of code or/and its output. The directive also adds local variables such as __WD__ which contains the path to the documentation which contains the directive. It is useful to load additional files os.path.join(__WD__, ...).

<<<

print("Hide or unhide this output.")

Changed in version 1.7: Options warningout, toggle were added.

Changed in version 1.8: Options current, assert, store, restore were added.

source on GitHub

modify_script_before_running(script)[source][source]

Takes the script as a string and returns another string before it is run. It does not modify what is displayed. The function can be overwritten by any class based on this one.

source on GitHub

run()[source][source]

Extracts the information in a dictionary, runs the script.

Returns

a list of nodes

source on GitHub

runpython_class[source]

alias of runpython_node

exception pyquickhelper.sphinxext.sphinx_runpython_extension.RunPythonExecutionError[source][source]

Bases: Exception

Exception raised when a piece of code included in the documentation raises an exception.

source on GitHub

pyquickhelper.sphinxext.sphinx_runpython_extension.depart_runpython_node(self, node)[source][source]

What to do when leaving a node runpython_node the function should have different behaviour, depending on the format, or the setup should specify a different function for each.

source on GitHub

pyquickhelper.sphinxext.sphinx_runpython_extension.run_python_script(script, params=None, comment=None, setsysvar=None, process=False, exception=False, warningout=None, chdir=None, context=None)[source][source]

Executes a script python as a string.

Parameters
  • script – python script

  • params – params to add before the execution

  • comment – message to add in a exception when the script fails

  • setsysvar – if not None, add a member to module sys, set up this variable to True, if is remove after the execution

  • process – run the script in a separate process

  • exception – expects an exception to be raised, fails if it is not, the function returns no output and the error message

  • warningout – warning to disable (name of warnings)

  • chdir – change directory before running this script (if not None)

  • context – if not None, added to the local context

Returns

stdout, stderr, context

If the execution throws an exception such as NameError: name 'math' is not defined after importing the module math. It comes from the fact the domain name used by the function exec contains the declared objects. Example:

import math
def coordonnees_polaires(x,y):
    rho     = math.sqrt(x*x+y*y)
    theta   = math.atan2 (y,x)
    return rho, theta
coordonnees_polaires(1, 1)

The code can be modified into:

def fake_function():
    import math
    def coordonnees_polaires(x,y):
        rho     = math.sqrt(x*x+y*y)
        theta   = math.atan2 (y,x)
        return rho, theta
    coordonnees_polaires(1, 1)
fake_function()

Section l-image-rst-runpython explains how to display an image with this directive.

Changed in version 1.7: Parameter warningout was added.

Changed in version 1.8: Parameter chdir, context were added, returns the context too.

source on GitHub

class pyquickhelper.sphinxext.sphinx_runpython_extension.runpython_node(rawsource='', *children, **attributes)[source][source]

Bases: docutils.nodes.Structural, docutils.nodes.Element

defines runpython node

source on GitHub

__slotnames__ = [][source]
pyquickhelper.sphinxext.sphinx_runpython_extension.setup(app)[source][source]

setup for runpython (sphinx)

source on GitHub

pyquickhelper.sphinxext.sphinx_runpython_extension.visit_runpython_node(self, node)[source][source]

What to do when visiting a node runpython_node the function should have different behaviour, depending on the format, or the setup should specify a different function for each.

source on GitHub