### Navigation

- index
- modules |
- next |
- previous |
- IPython v0.10 documentation »
- The IPython API »

# iplib

## Module: `iplib`

Inheritance diagram for `IPython.iplib`:

IPython – An enhanced Interactive Python

Requires Python 2.4 or newer.

This file contains all the classes and helper functions specific to IPython.

## Classes

### `Bunch`

class `IPython.iplib.``Bunch`

### `InputList`

class `IPython.iplib.``InputList`

  Bases: `list`

  Class to store user input.

  It’s basically a list, but slices return a string instead of a list, thus allowing things like (assuming ‘In’ is an instance):

  exec In[4:7]

  or

  exec In[5:9] + In[14] + In[21:25]

  `__init__`()
    x.__init__(...) initializes x; see x.__class__.__doc__ for signature

### `InteractiveShell`

class `IPython.iplib.``InteractiveShell`(name, usage=None, rc=Struct({'__allownew': True, 'args': None, 'opts': None}), user_ns=None, user_global_ns=None, banner2='', custom_exceptions=((), None), embedded=False)

  Bases: `object`, `IPython.Magic.Magic`

  An enhanced console for Python.

  `__init__`(name, usage=None, rc=Struct({'__allownew': True, 'args': None, 'opts': None}), user_ns=None, user_global_ns=None, banner2='', custom_exceptions=((), None), embedded=False)
  `add_builtins`()

    Store ipython references into the builtin namespace.

    Some parts of ipython operate via builtins injected here, which hold a reference to IPython itself.

  `alias_table_validate`(verbose=0)

    Update information about the alias table.

    In particular, make sure no Python keywords/builtins are in it.

  `ask_exit`()
    Call for exiting. Can be overiden and used as a callback.
  `ask_yes_no`(prompt, default=True)
  `atexit_operations`()

    This will be executed at the time of exit.

    Saving of persistent data should be performed here.

  `autoindent_update`(line)
    Keep track of the indent level.
  `cache_main_mod`(ns, fname)

    Cache a main module’s namespace.

    When scripts are executed via %run, we must keep a reference to the namespace of their __main__ module (a FakeModule instance) around so that Python doesn’t clear it, rendering objects defined therein useless.

    This method keeps said reference in a private dict, keyed by the absolute path of the module object (which corresponds to the script path). This way, for multiple executions of the same script we only keep one copy of the namespace (the last one), thus preventing memory leaks from old references while allowing the objects from the last execution to be accessible.

    Note: we can not allow the actual FakeModule instances to be deleted, because of how Python tears down modules (it hard-sets all their references to None without regard for reference counts). This method must therefore make a copy of the given namespace, to allow the original module’s __dict__ to be cleared and reused.

    Parameters:

    ns : a namespace (a dict, typically)

    > fname : str

    >   Filename associated with the namespace.

    Examples

    In [10]: import IPython

    In [11]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)

    In [12]: IPython.__file__ in _ip.IP._main_ns_cache Out[12]: True

  `call_alias`(alias, rest='')

    Call an alias given its name and the rest of the line.

    This is only used to provide backwards compatibility for users of ipalias(), use of which is not recommended for anymore.

  `call_pdb`
    Control auto-activation of pdb at exceptions
  `clean_builtins`()
    Remove any builtins which might have been added by add_builtins, or restore overwritten ones to their previous values.
  `clear_main_mod_cache`()

    Clear the cache of main modules.

    Mainly for use by utilities like %reset.

    Examples

    In [15]: import IPython

    In [16]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)

    In [17]: len(_ip.IP._main_ns_cache) > 0 Out[17]: True

    In [18]: _ip.IP.clear_main_mod_cache()

    In [19]: len(_ip.IP._main_ns_cache) == 0 Out[19]: True

  `complete`(text)

    Return a sorted list of all possible completions on text.

    Inputs:

    > - text: a string of text to be completed on.

    This is a wrapper around the completion mechanism, similar to what readline does at the command line when the TAB key is hit. By exposing it as a method, it can be used by other non-readline environments (such as GUIs) for text completion.

    Simple usage example:

    In [7]: x = ‘hello’

    In [8]: x Out[8]: ‘hello’

    In [9]: print x hello

    In [10]: _ip.IP.complete(‘x.l’) Out[10]: [‘x.ljust’, ‘x.lower’, ‘x.lstrip’]

  `debugger`(force=False)

    Call the pydb/pdb debugger.

    Keywords:

    > - force(False): by default, this routine checks the instance call_pdb

    > flag and does not actually invoke the debugger if the flag is false. The ‘force’ option forces the debugger to activate even if the flag is false.

  `edit_syntax_error`()

    The bottom half of the syntax error handler called in the main loop.

    Loop until syntax error is fixed or user cancels.

  `embed_mainloop`(header='', local_ns=None, global_ns=None, stack_depth=0)

    Embeds IPython into a running python program.

    Input:

    > - header: An optional header message can be specified.
    > - local_ns, global_ns: working namespaces. If given as None, the

    > IPython-initialized one is updated with __main__.__dict__, so that program variables become visible but user-specific configuration remains possible.

    > - stack_depth: specifies how many levels in the stack to go to

    > looking for namespaces (when local_ns and global_ns are None). This allows an intermediate caller to make sure that this function gets the namespace from the intended level in the stack. By default (0) it will get its locals and globals from the immediate caller.

    Warning: it’s possible to use this in a program which is being run by IPython itself (via %run), but some funny things will happen (a few globals get overwritten). In the future this will be cleaned up, as there is no fundamental reason why it can’t work perfectly.

  `excepthook`(etype, value, tb)

    One more defense for GUI apps that call sys.excepthook.

    GUI frameworks like wxPython trap exceptions and call sys.excepthook themselves. I guess this is a feature that enables them to keep running after exceptions that would otherwise kill their mainloop. This is a bother for IPython which excepts to catch all of the program exceptions with a try: except: statement.

    Normally, IPython sets sys.excepthook to a CrashHandler instance, so if any app directly invokes sys.excepthook, it will look to the user like IPython crashed. In order to work around this, we can disable the CrashHandler and replace it with this excepthook instead, which prints a regular traceback using our InteractiveTB. In this fashion, apps which call sys.excepthook will generate a regular-looking exception from IPython, and the CrashHandler will only be triggered by real IPython crashes.

    This hook should be used sparingly, only in places which are not likely to be true IPython errors.

  `exec_init_cmd`()

    Execute a command given at the command line.

    This emulates Python’s -c option.

  `exit`()

    Handle interactive exit.

    This method calls the ask_exit callback.

  `expand_aliases`(fn, rest)

    Expand multiple levels of aliases:

    if:

    alias foo bar /tmp alias baz foo

    then:

    baz huhhahhei -> bar /tmp huhhahhei

  `getapi`()

    Get an IPApi object for this shell instance

    Getting an IPApi object is always preferable to accessing the shell directly, but this holds true especially for extensions.

    It should always be possible to implement an extension with IPApi alone. If not, contact maintainer to request an addition.

  `handle_alias`(line_info)
    Handle alias input lines.
  `handle_auto`(line_info)
    Hande lines which can be auto-executed, quoting if requested.
  `handle_emacs`(line_info)
    Handle input lines marked by python-mode.
  `handle_help`(line_info)

    Try to get some help for the object.

    obj? or ?obj -> basic information. obj?? or ??obj -> more details.

  `handle_magic`(line_info)
    Execute magic functions.
  `handle_normal`(line_info)
    Handle normal input lines. Use as a template for handlers.
  `handle_shell_escape`(line_info)
    Execute the line in a shell, empty return value
  `history_saving_wrapper`(func)

    Wrap func for readline history saving

    Convert func into callable that saves & restores history around the call

  `indent_current_str`()
    return the current level of indentation as a string
  `init_auto_alias`()

    Define some aliases automatically.

    These are ALL parameter-less aliases

  `init_namespaces`()

    Initialize all user-visible namespaces to their minimum defaults.

    Certain history lists are also initialized here, as they effectively act as user namespaces.

    Notes

    All data structures here are only filled in, they are NOT reset by this method. If they were not empty before, data will simply be added to therm.

  `init_readline`()
    Command history completion/saving/reloading.
  `interact`(banner=None)

    Closely emulate the interactive Python console.

    The optional banner argument specify the banner to print before the first interaction; by default it prints a banner similar to the one printed by the real Python interpreter, followed by the current class name in parentheses (so as not to confuse this with the real interpreter – since it’s so close!).

  `interact_handle_input`(line)

    Handle the input line (in read-eval-print loop)

    Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not used in standard IPython flow.

  `interact_prompt`()

    Print the prompt (in read-eval-print loop)

    Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not used in standard IPython flow.

  `interact_with_readline`()

    Demo of using interact_handle_input, interact_prompt

    This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), it should work like this.

  `ipalias`(arg_s)

    Call an alias by name.

    Input: a string containing the name of the alias to call and any additional arguments to be passed to the magic.

    ipalias(‘name -opt foo bar’) is equivalent to typing at the ipython prompt:

    In[1]: name -opt foo bar

    To call an alias without arguments, simply use ipalias(‘name’).

    This provides a proper Python function to call IPython’s aliases in any valid Python code you can type at the interpreter, including loops and compound statements. It is added by IPython to the Python builtin namespace upon initialization.

  `ipmagic`(arg_s)

    Call a magic function by name.

    Input: a string containing the name of the magic function to call and any additional arguments to be passed to the magic.

    ipmagic(‘name -opt foo bar’) is equivalent to typing at the ipython prompt:

    In[1]: %name -opt foo bar

    To call a magic without arguments, simply use ipmagic(‘name’).

    This provides a proper Python function to call IPython’s magics in any valid Python code you can type at the interpreter, including loops and compound statements. It is added by IPython to the Python builtin namespace upon initialization.

  `ipsystem`(arg_s)
    Make a system call, using IPython.
  `mainloop`(banner=None)

    Creates the local namespace and starts the mainloop.

    If an optional banner argument is given, it will override the internally created default banner.

  `mktempfile`(data=None)

    Make a new tempfile and return its filename.

    This makes a call to tempfile.mktemp, but it registers the created filename internally so ipython cleans it up at exit time.

    Optional inputs:

    > - data(None): if data is given, it gets written out to the temp file

    > immediately, and the file is closed again.

  `multiline_prefilter`(line, continue_prompt)

    Run _prefilter for each line of input

    Covers cases where there are multiple lines in the user entry, which is the case when the user goes back to a multiline history entry and presses enter.

  `new_main_mod`(ns=None)
    Return a new ‘main’ module object for user code execution.
  `post_config_initialization`()

    Post configuration init method

    This is called after the configuration files have been processed to ‘finalize’ the initialization.

  `pre_config_initialization`()

    Pre-configuration init method

    This is called before the configuration files are processed to prepare the services the config files might need.

    self.rc already has reasonable default values at this point.

  `pre_readline`()

    readline hook to be used at the start of each line.

    Currently it handles auto-indent only.

  `prefilter`(line, continue_prompt)

    Run _prefilter for each line of input

    Covers cases where there are multiple lines in the user entry, which is the case when the user goes back to a multiline history entry and presses enter.

  `push`(line)

    Push a line to the interpreter.

    The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter’s runsource() method is called with the concatenated contents of the buffer as source. If this indicates that the command was executed or invalid, the buffer is reset; otherwise, the command is incomplete, and the buffer is left as it was after the line was appended. The return value is 1 if more input is required, 0 if the line was dealt with in some way (this is the same as runsource()).

  `raw_input`(prompt='', continue_prompt=False)

    Write a prompt and read a line.

    The returned line does not include the trailing newline. When the user enters the EOF key sequence, EOFError is raised.

    Optional inputs:

    > - prompt(‘’): a string to be printed to prompt the user.
    > - continue_prompt(False): whether this line is the first one or a

    > continuation in a sequence of inputs.

  `rc_set_toggle`(rc_field, value=None)

    Set or toggle a field in IPython’s rc config. structure.

    If called with no arguments, it acts as a toggle.

    If called with a non-existent field, the resulting AttributeError exception will propagate out.

  `reloadhist`()
    Reload the input history from disk file.
  `reset`()

    Clear all internal namespaces.

    Note that this is much more aggressive than %reset, since it clears fully all namespaces, as well as all input/output lists.

  `resetbuffer`()
    Reset the input buffer.
  `runcode`(code_obj)

    Execute a code object.

    When an exception occurs, self.showtraceback() is called to display a traceback.

    Return value: a flag indicating whether the code to be run completed successfully:

    > - 0: successful execution.
    > - 1: an error occurred.

  `runlines`(lines)

    Run a string of one or more lines of source.

    This method is capable of running a string containing multiple source lines, as if they had been entered at the IPython prompt. Since it exposes IPython’s processing machinery, the given strings can contain magic calls (%magic), special shell access (!cmd), etc.

  `runsource`(source, filename='<input>', symbol='single')

    Compile and run some source in the interpreter.

    Arguments are as for compile_command().

    One several things can happen:

    1) The input is incorrect; compile_command() raised an exception (SyntaxError or OverflowError). A syntax traceback will be printed by calling the showsyntaxerror() method.

    2) The input is incomplete, and more input is required; compile_command() returned None. Nothing happens.

    3) The input is complete; compile_command() returned a code object. The code is executed by calling self.runcode() (which also handles run-time exceptions, except for SystemExit).

    The return value is:

    > - True in case 2
    > - False in the other cases, unless an exception is raised, where

    > None is returned instead. This can be used by external callers to know whether to continue feeding input or not.

    The return value can be used to decide whether to use sys.ps1 or sys.ps2 to prompt the next line.

  `safe_execfile`(fname, *where, **kw)

    A safe version of the builtin execfile().

    This version will never throw an exception, and knows how to handle ipython logs as well.

    Parameters:

    fname : string

      Name of the file to be executed.

    where : tuple

      One or two namespaces, passed to execfile() as (globals,locals). If only one is given, it is passed as both.

    Keywords: | islog : boolean (False) quiet : boolean (True) exit_ignore : boolean (False)

  `savehist`()
    Save input history to a file (via readline library).
  `set_autoindent`(value=None)

    Set the autoindent flag, checking for readline support.

    If called with no arguments, it acts as a toggle.

  `set_completer`()
    reset readline’s completer to be our own.
  `set_completer_frame`(frame=None)
  `set_crash_handler`(crashHandler)

    Set the IPython crash handler.

    This must be a callable with a signature suitable for use as sys.excepthook.

  `set_custom_completer`(completer, pos=0)

    Adds a new custom completer function.

    The position argument (defaults to 0) is the index in the completers list where you want the completer to be inserted.

  `set_custom_exc`(exc_tuple, handler)

    Set a custom exception handler, which will be called if any of the exceptions in exc_tuple occur in the mainloop (specifically, in the runcode() method.

    Inputs:

    > - exc_tuple: a tuple of valid exceptions to call the defined

    > handler for. It is very important that you use a tuple, and NOT A LIST here, because of the way Python’s except statement works. If you only want to trap a single exception, use a singleton tuple:

    > > exc_tuple == (MyCustomException,)

    > - handler: this must be defined as a function with the following

    > basic interface: def my_handler(self,etype,value,tb).

    > This will be made into an instance method (via new.instancemethod) of IPython itself, and it will be called if any of the exceptions listed in the exc_tuple are caught. If the handler is None, an internal basic one is used, which just prints basic info.

    WARNING: by putting in your own exception handler into IPython’s main execution loop, you run a very good chance of nasty crashes. This facility should only be used if you really know what you are doing.

  `set_hook`(name, hook, priority=50, str_key=None, re_key=None)

    set_hook(name,hook) -> sets an internal IPython hook.

    IPython exposes some of its internal API as user-modifiable hooks. By adding your function to one of these hooks, you can modify IPython’s behavior to call at runtime your own routines.

  `showsyntaxerror`(filename=None)

    Display the syntax error that just occurred.

    This doesn’t display a stack trace because there isn’t one.

    If a filename is given, it is stuffed in the exception instead of what was there before (because Python’s parser always uses “<string>” when reading from a string).

  `showtraceback`(exc_tuple=None, filename=None, tb_offset=None)

    Display the exception that just occurred.

    If nothing is known about the exception, this is the method which should be used throughout the code for presenting user tracebacks, rather than directly invoking the InteractiveTB object.

    A specific showsyntaxerror() also exists, but this method can take care of calling it if needed, so unless you are explicitly catching a SyntaxError exception, don’t try to analyze the stack manually and simply call this method.

  `split_user_input`(line)
  `transform_alias`(alias, rest='')
    Transform alias to system command string.
  `user_setup`(ipythondir, rc_suffix, mode='install')

    Install the user configuration directory.

    Notes

    DEPRECATED: use the top-level user_setup() function instead.

  `var_expand`(cmd, depth=0)

    Expand python variables in a string.

    The depth argument indicates how many frames above the caller should be walked to look for the local namespace where to expand variables.

    The global namespace for expansion is always the user’s interactive namespace.

  `write`(data)
    Write a string to the default output
  `write_err`(data)
    Write a string to the default error output

### `Quitter`

class `IPython.iplib.``Quitter`(shell, name)

  Bases: `object`

  Simple class to handle exit, similar to Python 2.5’s.

  It handles exiting in an ipython-safe manner, which the one in Python 2.5 doesn’t do (obviously, since it doesn’t know about ipython).

  `__init__`(shell, name)

### `SpaceInInput`

class `IPython.iplib.``SpaceInInput`

  Bases: `exceptions.Exception`

  `__init__`()
    x.__init__(...) initializes x; see x.__class__.__doc__ for signature

### `SyntaxTB`

class `IPython.iplib.``SyntaxTB`(color_scheme='NoColor')

  Bases: `IPython.ultraTB.ListTB`

  Extension which holds some state: the last exception value

  `__init__`(color_scheme='NoColor')
  `clear_err_state`()
    Return the current error state and clear it

### `Undefined`

class `IPython.iplib.``Undefined`

## Functions

`IPython.iplib.``num_ini_spaces`(strng)
  Return the number of initial spaces in a string

`IPython.iplib.``softspace`(file, newvalue)
  Copied from code.py, to remove the dependency

`IPython.iplib.``user_setup`(ipythondir, rc_suffix, mode='install', interactive=True)

  Install or upgrade the user configuration directory.

  Can be called when running for the first time or to upgrade the user’s .ipython/ directory.

  Parameters:

  ipythondir : path

  > > The directory to be used for installation/upgrade. In ‘install’ mode, if this path already exists, the function exits immediately.

  > rc_suffix : str

  >   Extension for the config files. On *nix platforms it is typically the empty string, while Windows normally uses ‘.ini’.

  > mode : str, optional

  >   Valid modes are ‘install’ and ‘upgrade’.

  > interactive : bool, optional

  >   If False, do not wait for user input on any errors. Normally after printing its status information, this function waits for the user to hit Return before proceeding. This is because the default use case is when first installing the IPython configuration, so we want the user to acknowledge the initial message, which contains some useful information.

### Navigation

- index
- modules |
- next |
- previous |
- IPython v0.10 documentation »
- The IPython API »