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.



class IPython.iplib.Bunch


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]


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


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


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.


Store ipython references into the builtin namespace.

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


Update information about the alias table.

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


Call for exiting. Can be overiden and used as a callback.


This will be executed at the time of exit.

Saving of persistent data should be performed here.


Keep track of the indent level.


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.


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 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.


Control auto-activation of pdb at exceptions


Remove any builtins which might have been added by add_builtins, or restore overwritten ones to their previous values.


Clear the cache of main modules.

Mainly for use by utilities like %reset.


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


Return a sorted list of all possible completions on text.


  • 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’]


Call the pydb/pdb debugger.


  • 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.


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

Loop until syntax error is fixed or user cancels.


Embeds IPython into a running python program.


  • 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.


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.


Execute a command given at the command line.

This emulates Python’s -c option.


Handle interactive exit.

This method calls the ask_exit callback.


Expand multiple levels of aliases:


alias foo bar /tmp alias baz foo


baz huhhahhei -> bar /tmp huhhahhei


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 input lines.


Hande lines which can be auto-executed, quoting if requested.


Handle input lines marked by python-mode.


Try to get some help for the object.

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


Execute magic functions.


Handle normal input lines. Use as a template for handlers.


Execute the line in a shell, empty return value


Wrap func for readline history saving

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


return the current level of indentation as a string


Define some aliases automatically.

These are ALL parameter-less aliases


Initialize all user-visible namespaces to their minimum defaults.

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


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.


Command history completion/saving/reloading.


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!).


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.


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.


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.


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.


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.


Make a system call, using IPython.


Creates the local namespace and starts the mainloop.

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


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.


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.


Return a new ‘main’ module object for user code execution.


Post configuration init method

This is called after the configuration files have been processed to ‘finalize’ the 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.


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

Currently it handles auto-indent only.


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 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()).


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.


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.


Reload the input history from disk file.


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.


Reset the input buffer.


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.

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.


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.


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)


Save input history to a file (via readline library).


Set the autoindent flag, checking for readline support.

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


reset readline’s completer to be our own.


Set the IPython crash handler.

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


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 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.


  • 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) -> 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.


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).


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.


Transform alias to system command string.


Install the user configuration directory.


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


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 a string to the default output


Write a string to the default error output


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).



class IPython.iplib.SpaceInInput

Bases: exceptions.Exception


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


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

Bases: IPython.ultraTB.ListTB

Extension which holds some state: the last exception value


Return the current error state and clear it


class IPython.iplib.Undefined



Return the number of initial spaces in a string


Copied from code.py, to remove the dependency


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.

Table Of Contents

Previous topic


Next topic


This Page