### Navigation

- index
- modules |
- modules |
- next |
- previous |
- home|
- search|
- documentation »
- The IPython API »

# Module: `sphinxext.ipython_directive`

Sphinx directive to support embedded IPython code.

This directive allows pasting of entire interactive IPython sessions, prompts and all, and their code will actually get re-executed at doc build time, with all prompts renumbered sequentially. It also allows you to input code as a pure python input by giving the argument python to the directive. The output looks like an interactive ipython section.

To enable this directive, simply list it in your Sphinx `conf.py` file (making sure the directory where you placed it is visible to sphinx, as is needed for all Sphinx directives). For example, to enable syntax highlighting and the IPython directive:

    extensions = ['IPython.sphinxext.ipython_console_highlighting',
                  'IPython.sphinxext.ipython_directive']

The IPython directive outputs code-blocks with the language ‘ipython’. So if you do not have the syntax highlighting extension enabled as well, then all rendered code-blocks will be uncolored. By default this directive assumes that your prompts are unchanged IPython ones, but this can be customized. The configurable options that can be placed in conf.py are:

ipython_savefig_dir:
  The directory in which to save the figures. This is relative to the Sphinx source directory. The default is html_static_path.
ipython_rgxin:
  The compiled regular expression to denote the start of IPython input lines. The default is re.compile(‘In [(d+)]:s?(.*)s*’). You shouldn’t need to change this.
ipython_rgxout:
  The compiled regular expression to denote the start of IPython output lines. The default is re.compile(‘Out[(d+)]:s?(.*)s*’). You shouldn’t need to change this.
ipython_promptin:
  The string to represent the IPython input prompt in the generated ReST. The default is ‘In [%d]:’. This expects that the line numbers are used in the prompt.
ipython_promptout:
  The string to represent the IPython prompt in the generated ReST. The default is ‘Out [%d]:’. This expects that the line numbers are used in the prompt.
ipython_mplbackend:
  The string which specifies if the embedded Sphinx shell should import Matplotlib and set the backend. The value specifies a backend that is passed to matplotlib.use() before any lines in ipython_execlines are executed. If not specified in conf.py, then the default value of ‘agg’ is used. To use the IPython directive without matplotlib as a dependency, set the value to None. It may end up that matplotlib is still imported if the user specifies so in ipython_execlines or makes use of the @savefig pseudo decorator.
ipython_execlines:
  A list of strings to be exec’d in the embedded Sphinx shell. Typical usage is to make certain packages always available. Set this to an empty list if you wish to have no imports always available. If specified in conf.py as None, then it has the effect of making no imports available. If omitted from conf.py altogether, then the default value of [‘import numpy as np’, ‘import matplotlib.pyplot as plt’] is used.
ipython_holdcount
  When the @suppress pseudo-decorator is used, the execution count can be incremented or not. The default behavior is to hold the execution count, corresponding to a value of True. Set this to False to increment the execution count after each suppressed command.

As an example, to use the IPython directive when matplotlib is not available, one sets the backend to None:

    ipython_mplbackend = None

An example usage of the directive is:

    .. ipython::

        In [1]: x = 1

        In [2]: y = x**2

        In [3]: print(y)

See http://matplotlib.org/sampledoc/ipython_directive.html for additional documentation.

## Pseudo-Decorators

Note: Only one decorator is supported per input. If more than one decorator is specified, then only the last one is used.

In addition to the Pseudo-Decorators/options described at the above link, several enhancements have been made. The directive will emit a message to the console at build-time if code-execution resulted in an exception or warning. You can suppress these on a per-block basis by specifying the :okexcept: or :okwarning: options:

    .. ipython::
        :okexcept:
        :okwarning:

        In [1]: 1/0
        In [2]: # raise warning.

### ToDo

- Turn the ad-hoc test() function into a real test suite.
- Break up ipython-specific functionality from matplotlib stuff into better separated code.

### Authors

- John D Hunter: orignal author.
- Fernando Perez: refactoring, documentation, cleanups, port to 0.11.
- VáclavŠmilauer <eudoxos-AT-arcig.cz>: Prompt generalizations.
- Skipper Seabold, refactoring, cleanups, pure python addition

## 2 Classes

class `IPython.sphinxext.ipython_directive.``EmbeddedSphinxShell`(exec_lines=None)

  Bases: `object`

  An embedded IPython instance to run inside Sphinx

  `__init__`(exec_lines=None)
  `custom_doctest`(decorator, input_lines, found, submitted)

    Perform a specialized doctest.

  `ensure_pyplot`()

    Ensures that pyplot has been imported into the embedded IPython shell.

    Also, makes sure to set the backend appropriately if not set already.

  `process_block`(block)

    process block from the block_parser and return a list of processed lines

  `process_comment`(data)

    Process data fPblock for COMMENT token.

  `process_image`(decorator)

    # build out an image directive like # .. image:: somefile.png # :width 4in # # from an input like # savefig somefile.png width=4in

  `process_input`(data, input_prompt, lineno)

    Process data block for INPUT token.

  `process_input_line`(line, store_history=True)

    process the input, capturing stdout

  `process_output`(data, output_prompt, input_lines, output, is_doctest, decorator, image_file)

    Process data block for OUTPUT token.

  `process_pure_python`(content)

    content is a list of strings. it is unedited directive content

    This runs it line by line in the InteractiveShell, prepends prompts as needed capturing stderr and stdout, then returns the content as a list as if it were ipython code

  `save_image`(image_file)

    Saves the image file to disk.

class `IPython.sphinxext.ipython_directive.``IPythonDirective`(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)

  Bases: `docutils.parsers.rst.Directive`

## 3 Functions

`IPython.sphinxext.ipython_directive.``block_parser`(part, rgxin, rgxout, fmtin, fmtout)

  part is a string of ipython text, comprised of at most one input, one ouput, comments, and blank lines. The block parser parses the text into a list of:

      blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...]

  where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and data is, depending on the type of token:

      COMMENT : the comment string

      INPUT: the (DECORATOR, INPUT_LINE, REST) where
         DECORATOR: the input decorator (or None)
         INPUT_LINE: the input as string (possibly multi-line)
         REST : any stdout generated by the input line (not OUTPUT)

      OUTPUT: the output string, possibly multi-line

`IPython.sphinxext.ipython_directive.``setup`(app)

`IPython.sphinxext.ipython_directive.``test`()

### Navigation

- index
- modules |
- modules |
- next |
- previous |
- home|
- search|
- documentation »
- The IPython API »