### Navigation

- index
- modules |
- next |
- previous |
- The Sage Command Line »

# Sage’s IPython Extension

A Sage extension which adds sage-specific features:

- magics
  - `%crun`
  - `%runfile`
  - `%attach`
  - `%display`
  - `%mode` (like `%maxima`, etc.)
- preparsing of input
- loading Sage library
- running init.sage
- changing prompt to Sage prompt
- Display hook

TESTS:

We test that preparsing is off for `%runfile`, on for `%time`:

    sage: import os, re
    sage: from sage.repl.interpreter import get_test_shell
    sage: from sage.misc.misc import tmp_dir
    sage: shell = get_test_shell()
    sage: TMP = tmp_dir()

The temporary directory should have a name of the form `.../12345/...`, to demonstrate that file names are not preparsed when calling `%runfile`

    sage: bool(re.search('/[0-9]+/', TMP))
    True
    sage: tmp = os.path.join(TMP, 'run_cell.py')
    sage: f = open(tmp, 'w'); f.write('a = 2\n'); f.close()
    sage: shell.run_cell('%runfile '+tmp)
    sage: shell.run_cell('a')
    2

In contrast, input to the `%time` magic command is preparsed:

    sage: shell.run_cell('%time 594.factor()')
    CPU times: user ...
    Wall time: ...
    2 * 3^3 * 11

class `sage.repl.ipython_extension.``SageCustomizations`(shell=None)

  Bases: `object`

  Initialize the Sage plugin.

  `init_environment`()

    Set up Sage command-line environment

  `init_inspector`()

    x.__init__(...) initializes x; see help(type(x)) for signature

  `init_line_transforms`()

    Set up transforms (like the preparser).

  `register_interface_magics`()

    Register magics for each of the Sage interfaces

  `run_init`()

    Run Sage’s initial startup file.

  `set_quit_hook`()

    Set the exit hook to cleanly exit Sage.

class `sage.repl.ipython_extension.``SageMagics`(shell=None, **kwargs)

  Bases: `IPython.core.magic.Magics`

  `attach`(s)

    Attach the code contained in the file `s`.

    This is designed to be used from the command line as `%attach /path/to/file`.

    - `s` – string. The file to be attached

    EXAMPLES:

        sage: import os
        sage: from sage.repl.interpreter import get_test_shell
        sage: shell = get_test_shell()
        sage: tmp = os.path.normpath(os.path.join(SAGE_TMP, 'run_cell.py'))
        sage: f = open(tmp, 'w'); f.write('a = 2\n'); f.close()
        sage: shell.run_cell('%attach ' + tmp)
        sage: shell.run_cell('a')
        2
        sage: sleep(1)  # filesystem timestamp granularity
        sage: f = open(tmp, 'w'); f.write('a = 3\n'); f.close()

    Note that the doctests are never really at the command prompt, so we call the input hook manually:

        sage: shell.run_cell('from sage.repl.inputhook import sage_inputhook')
        sage: shell.run_cell('sage_inputhook()')
        ### reloading attached file run_cell.py modified at ... ###
        0

        sage: shell.run_cell('a')
        3
        sage: shell.run_cell('detach(%r)'%tmp)
        sage: shell.run_cell('attached_files()')
        []
        sage: os.remove(tmp)

  `crun`(s)

    Profile C function calls

    INPUT:

    - `s` – string. Sage command to profile.

    EXAMPLES:

        sage: from sage.repl.interpreter import get_test_shell
        sage: shell = get_test_shell()
        sage: shell.run_cell('%crun sum(1/(1+n^2) for n in range(100))')   # optional - gperftools
        PROFILE: interrupts/evictions/bytes = ...
        Using local file ...
        Using local file ...

  `display`(args)

    A magic command to switch between simple display and ASCII art display.

    - `args` – string. See `sage.misc.display_hook.DisplayHookBase.set_display()` for allowed values. If the mode is `ascii_art`, it can optionally be followed by a width.

    How to use: if you want activate the ASCII art mod:

        sage: from sage.repl.interpreter import get_test_shell
        sage: shell = get_test_shell()
        sage: shell.run_cell('%display ascii_art')

    That means you don’t have to use `ascii_art()` to get an ASCII art output:

        sage: shell.run_cell("i = var('i')")
        sage: shell.run_cell('sum(i^2*x^i, i, 0, 10)')
             10       9       8       7       6       5       4      3      2
        100*x   + 81*x  + 64*x  + 49*x  + 36*x  + 25*x  + 16*x  + 9*x  + 4*x  + x

    Then when you want return in ‘textual mode’:

        sage: shell.run_cell('%display simple')
        sage: shell.run_cell('sum(i^2*x^i, i, 0, 10)')
        100*x^10 + 81*x^9 + 64*x^8 + 49*x^7 + 36*x^6 + 25*x^5 + 16*x^4 + 9*x^3 + 4*x^2 + x

    Sometime you could have to use a special output width and you could specify it:

        sage: shell.run_cell('%display ascii_art')
        sage: shell.run_cell('StandardTableaux(4).list()')
        [
        [                                                                  1  4    1  3
        [                 1  3  4    1  2  4    1  2  3    1  3    1  2    2       2
        [   1  2  3  4,   2      ,   3      ,   4      ,   2  4,   3  4,   3   ,   4
        <BLANKLINE>
                    1 ]
            1  2    2 ]
            3       3 ]
        ,   4   ,   4 ]
        sage: shell.run_cell('%display ascii_art 50')
        sage: shell.run_cell('StandardTableaux(4).list()')
        [
        [
        [                 1  3  4    1  2  4    1  2  3
        [   1  2  3  4,   2      ,   3      ,   4      ,
        <BLANKLINE>
                                                  1 ]
                          1  4    1  3    1  2    2 ]
          1  3    1  2    2       2       3       3 ]
          2  4,   3  4,   3   ,   4   ,   4   ,   4 ]

    As yet another option, typeset mode. This is used in the emacs interface:

        sage: shell.run_cell('%display typeset')
        sage: shell.run_cell('1/2')
        <html><script type="math/tex">...\frac{1}{2}</script></html>

    Switch back:

        sage: shell.run_cell('%display simple')

    TESTS:

        sage: shell.run_cell('%display invalid_mode')
        ---------------------------------------------------------------------------
        ValueError                                Traceback (most recent call last)
        ...
        ValueError: invalid mode set

  `iload`(args)

    A magic command to interactively load a file as in MAGMA.

    - `args` – string. The file to be interactively loaded

    Note

    Currently, this cannot be completely doctested as it relies on `raw_input()`.

    EXAMPLES:

        sage: ip = get_ipython()           # not tested: works only in interactive shell
        sage: ip.magic_iload('/dev/null')  # not tested: works only in interactive shell
        Interactively loading "/dev/null"  # not tested: works only in interactive shell

  `runfile`(s)

    Execute the code contained in the file `s`.

    This is designed to be used from the command line as `%runfile /path/to/file`.

    - `s` – string. The file to be loaded.

    EXAMPLES:

        sage: import os
        sage: from sage.repl.interpreter import get_test_shell
        sage: from sage.misc.misc import tmp_dir
        sage: shell = get_test_shell()
        sage: tmp = os.path.join(tmp_dir(), 'run_cell.py')
        sage: f = open(tmp, 'w'); f.write('a = 2\n'); f.close()
        sage: shell.run_cell('%runfile '+tmp)
        sage: shell.run_cell('a')
        2

`sage.repl.ipython_extension.``load_ipython_extension`(*args, **kwargs)

  Load the extension in IPython.

`sage.repl.ipython_extension.``run_once`(func)

  Runs a function (successfully) only once.

  The running can be reset by setting the `has_run` attribute to False

  TEST:

      sage: from sage.repl.ipython_extension import run_once
      sage: @run_once
      ....: def foo(work):
      ....:     if work:
      ....:         return 'foo worked'
      ....:     raise RuntimeError("foo didn't work")
      sage: foo(False)
      Traceback (most recent call last):
      ...
      RuntimeError: foo didn't work
      sage: foo(True)
      'foo worked'
      sage: foo(False)
      sage: foo(True)

### Navigation

- index
- modules |
- next |
- previous |
- The Sage Command Line »