Customization of IPython — IPython 0.10.2 documentation

### Navigation

- index
- modules |
- next |
- previous |
- IPython 0.10.2 documentation »
- Configuration and customization »

# Customization of IPython

There are 2 ways to configure IPython - the old way of using ipythonrc files (an INI-file like format), and the new way that involves editing your ipy_user_conf.py. Both configuration systems work at the same time, so you can set your options in both, but if you are hesitating about which alternative to choose, we recommend the ipy_user_conf.py approach, as it will give you more power and control in the long run. However, there are few options such as pylab_import_all that can only be specified in ipythonrc file or command line - the reason for this is that they are needed before IPython has been started up, and the IPApi object used in ipy_user_conf.py is not yet available at that time. A hybrid approach of specifying a few options in ipythonrc and doing the more advanced configuration in ipy_user_conf.py is also possible.

## The ipythonrc approach

As we’ve already mentioned, IPython reads a configuration file which can be specified at the command line (-rcfile) or which by default is assumed to be called ipythonrc. Such a file is looked for in the current directory where IPython is started and then in your IPYTHONDIR, which allows you to have local configuration files for specific projects. In this section we will call these types of configuration files simply rcfiles (short for resource configuration file).

The syntax of an rcfile is one of key-value pairs separated by whitespace, one per line. Lines beginning with a # are ignored as comments, but comments can not be put on lines with data (the parser is fairly primitive). Note that these are not python files, and this is deliberate, because it allows us to do some things which would be quite tricky to implement if they were normal python files.

First, an rcfile can contain permanent default values for almost all command line options (except things like -help or -Version). This section contains a description of all command-line options. However, values you explicitly specify at the command line override the values defined in the rcfile.

Besides command line option values, the rcfile can specify values for certain extra special options which are not available at the command line. These options are briefly described below.

Each of these options may appear as many times as you need it in the file.

> - include <file1> <file2> ...: you can name other rcfiles you want to recursively load up to 15 levels (don’t use the <> brackets in your names!). This feature allows you to define a ‘base’ rcfile with general options and special-purpose files which can be loaded only when needed with particular configuration options. To make this more convenient, IPython accepts the -profile <name> option (abbreviates to -p <name>) which tells it to look for an rcfile named ipythonrc-<name>.
> - import_mod <mod1> <mod2> ...: import modules with ‘import <mod1>,<mod2>,...’
> - import_some <mod> <f1> <f2> ...: import functions with ‘from <mod> import <f1>,<f2>,...’
> - import_all <mod1> <mod2> ...: for each module listed import functions with `from <mod> import *`.
> - execute <python code>: give any single-line python code to be executed.
> - execfile <filename>: execute the python file given with an ‘execfile(filename)’ command. Username expansion is performed on the given names. So if you need any amount of extra fancy customization that won’t fit in any of the above ‘canned’ options, you can just put it in a separate python file and execute it.
> - alias <alias_def>: this is equivalent to calling ‘%alias <alias_def>’ at the IPython command line. This way, from within IPython you can do common system tasks without having to exit it or use the ! escape. IPython isn’t meant to be a shell replacement, but it is often very useful to be able to do things with files while testing code. This gives you the flexibility to have within IPython any aliases you may be used to under your normal system shell.

## ipy_user_conf.py

There should be a simple template ipy_user_conf.py file in your ~/.ipython directory. It is a plain python module that is imported during IPython startup, so you can do pretty much what you want there - import modules, configure extensions, change options, define magic commands, put variables and functions in the IPython namespace, etc. You use the IPython extension api object, acquired by IPython.ipapi.get() and documented in the “IPython extension API” chapter, to interact with IPython. A sample ipy_user_conf.py is listed below for reference:

    # Most of your config files and extensions will probably start
    # with this import

    import IPython.ipapi
    ip = IPython.ipapi.get()

    # You probably want to uncomment this if you did %upgrade -nolegacy
    # import ipy_defaults

    import os

    def main():

        #ip.dbg.debugmode = True
        ip.dbg.debug_stack()

        # uncomment if you want to get ipython -p sh behaviour
        # without having to use command line switches
        import ipy_profile_sh
        import jobctrl

        # Configure your favourite editor?
        # Good idea e.g. for %edit os.path.isfile

        #import ipy_editors

        # Choose one of these:

        #ipy_editors.scite()
        #ipy_editors.scite('c:/opt/scite/scite.exe')
        #ipy_editors.komodo()
        #ipy_editors.idle()
        # ... or many others, try 'ipy_editors??' after import to see them

        # Or roll your own:
        #ipy_editors.install_editor("c:/opt/jed +$line $file")

        o = ip.options
        # An example on how to set options
        #o.autocall = 1
        o.system_verbose = 0

        #import_all("os sys")
        #execf('~/_ipython/ns.py')

        # -- prompt
        # A different, more compact set of prompts from the default ones, that
        # always show your current location in the filesystem:

        #o.prompt_in1 = r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Normal\n\C_Green|\#>'
        #o.prompt_in2 = r'.\D: '
        #o.prompt_out = r'[\#] '

        # Try one of these color settings if you can't read the text easily
        # autoexec is a list of IPython commands to execute on startup
        #o.autoexec.append('%colors LightBG')
        #o.autoexec.append('%colors NoColor')
        o.autoexec.append('%colors Linux')

    # some config helper functions you can use
    def import_all(modules):
        """ Usage: import_all("os sys") """
        for m in modules.split():
            ip.ex("from %s import *" % m)

    def execf(fname):
        """ Execute a file in user namespace """
        ip.ex('execfile("%s")' % os.path.expanduser(fname))

    main()

## Fine-tuning your prompt

IPython’s prompts can be customized using a syntax similar to that of the bash shell. Many of bash’s escapes are supported, as well as a few additional ones. We list them below:

    \#
        the prompt/history count number. This escape is automatically
        wrapped in the coloring codes for the currently active color scheme.
    \N
        the 'naked' prompt/history count number: this is just the number
        itself, without any coloring applied to it. This lets you produce
        numbered prompts with your own colors.
    \D
        the prompt/history count, with the actual digits replaced by dots.
        Used mainly in continuation prompts (prompt_in2)
    \w
        the current working directory
    \W
        the basename of current working directory
    \Xn
        where $n=0\ldots5.$ The current working directory, with $HOME
        replaced by ~, and filtered out to contain only $n$ path elements
    \Yn
        Similar to \Xn, but with the $n+1$ element included if it is ~ (this
        is similar to the behavior of the %cn escapes in tcsh)
    \u
        the username of the current user
    \$
        if the effective UID is 0, a #, otherwise a $
    \h
        the hostname up to the first '.'
    \H
        the hostname
    \n
        a newline
    \r
        a carriage return
    \v
        IPython version string

In addition to these, ANSI color escapes can be insterted into the prompts, as C_ColorName. The list of valid color names is: Black, Blue, Brown, Cyan, DarkGray, Green, LightBlue, LightCyan, LightGray, LightGreen, LightPurple, LightRed, NoColor, Normal, Purple, Red, White, Yellow.

Finally, IPython supports the evaluation of arbitrary expressions in your prompt string. The prompt strings are evaluated through the syntax of PEP 215, but basically you can use $x.y to expand the value of x.y, and for more complicated expressions you can use braces: ${foo()+x} will call function foo and add to it the value of x, before putting the result into your prompt. For example, using prompt_in1 ‘${commands.getoutput(“uptime”)}nIn [#]: ‘ will print the result of the uptime command on each prompt (assuming the commands module has been imported in your ipythonrc file).

> Prompt examples

The following options in an ipythonrc file will give you IPython’s default prompts:

    prompt_in1 'In [\#]:'
    prompt_in2 '   .\D.:'
    prompt_out 'Out[\#]:'

which look like this:

    In [1]: 1+2
    Out[1]: 3

    In [2]: for i in (1,2,3):
       ...:    print i,
       ...:
    1 2 3

These will give you a very colorful prompt with path information:

    #prompt_in1 '\C_Red\u\C_Blue[\C_Cyan\Y1\C_Blue]\C_LightGreen\#>'
    prompt_in2 ' ..\D>'
    prompt_out '<\#>'

which look like this:

    fperez[~/ipython]1> 1+2
                    <1> 3
    fperez[~/ipython]2> for i in (1,2,3):
                   ...>     print i,
                   ...>
    1 2 3

## IPython profiles

As we already mentioned, IPython supports the -profile command-line option (see here). A profile is nothing more than a particular configuration file like your basic ipythonrc one, but with particular customizations for a specific purpose. When you start IPython with ‘ipython -profile <name>’, it assumes that in your IPYTHONDIR there is a file called ipythonrc-<name> or ipy_profile_<name>.py, and loads it instead of the normal ipythonrc.

This system allows you to maintain multiple configurations which load modules, set options, define functions, etc. suitable for different tasks and activate them in a very simple manner. In order to avoid having to repeat all of your basic options (common things that don’t change such as your color preferences, for example), any profile can include another configuration file. The most common way to use profiles is then to have each one include your basic ipythonrc file as a starting point, and then add further customizations.

### Navigation

- index
- modules |
- next |
- previous |
- IPython 0.10.2 documentation »
- Configuration and customization »