next up previous
Next: Using IPython as your Up: IPython An enhanced Interactive Previous: Interactive use

Subsections


Customization

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


Sample ipythonrc file

The default rcfile, called ipythonrc and supplied in your IPYTHONDIR directory contains lots of comments on all of these options. We reproduce it here for reference:


# -*- Mode: Shell-Script -*-  Not really, but shows comments correctly
# $Id: ipythonrc,v 1.4 2003/05/16 06:53:42 fperez Exp $

#***************************************************************************
#
# Configuration file for IPython -- ipythonrc format
#
# The format of this file is simply one of 'key value' lines.
# Lines containing only whitespace at the beginning and then a # are ignored
# as comments. But comments can NOT be put on lines with data.

# The meaning and use of each key are explained below.

#---------------------------------------------------------------------------
# Section: included files

# Put one or more *config* files (with the syntax of this file) you want to
# include. For keys with a unique value the outermost file has precedence. For
# keys with multiple values, they all get assembled into a list which then
# gets loaded by IPython.

# In this file, all lists of things should simply be space-separated.

# This allows you to build hierarchies of files which recursively load
# lower-level services. If this is your main ~/.ipython/ipythonrc file, you
# should only keep here basic things you always want available. Then you can
# include it in every other special-purpose config file you create.

include 

#---------------------------------------------------------------------------
# Section: startup setup

# These are mostly things which parallel a command line option of the same
# name.

# Keys in this section should only appear once. If any key from this section
# is encountered more than once, the last value remains, all earlier ones get
# discarded.

# Automatic calling of callable objects.  If set to true, callable objects are
# automatically called when invoked at the command line, even if you don't
# type parentheses.  IPython adds the parentheses for you.  For example:

#In [1]: str 45
#------> str(45)
#Out[1]: '45'

# IPython reprints your line with '---->' indicating that it added
# parentheses.  While this option is very convenient for interactive use, it
# may occasionally cause problems with objects which have side-effects if
# called unexpectedly.  Set it to 0 if you want to disable it.

# Note that even with autocall off, you can still use '/' at the start of a
# line to treat the first argument on the command line as a function and add
# parentheses to it:

#In [8]: /str 43
#------> str(43)
#Out[8]: '43'

autocall 1

# Auto-indent. IPython can recognize lines ending in ':' and indent the next
# line, while also un-indenting automatically after 'raise' or 'return'.  

# This feature uses the readline library, so it will honor your ~/.inputrc
# configuration (or whatever file your INPUTRC variable points to).  Adding
# the following lines to your .inputrc file can make indent/unindenting more
# convenient (M-i indents, M-u unindents):

#  $if Python
#  "\M-i": "    "
#  "\M-u": "\d\d\d\d"
#  $endif

# The feature is off by default because it can cause problems with pasting of
# indented code (the pasted code gets re-indented on each line).  But a magic
# function @autoindent allows you to toggle it on/off at runtime.

autoindent 0

# Auto-magic. This gives you access to all the magic functions without having
# to prepend them with an @ sign. If you define a variable with the same name
# as a magic function (say who=1), you will need to access the magic function
# with @ (@who in this example). However, if later you delete your variable
# (del who), you'll recover the automagic calling form.

# Considering that many magic functions provide a lot of shell-like
# functionality, automagic gives you something close to a full Python+system
# shell environment (and you can extend it further if you want).

automagic 1


# Size of the output cache. After this many entries are stored, the cache will
# get flushed. Depending on the size of your intermediate calculations, you
# may have memory problems if you make it too big, since keeping things in the
# cache prevents Python from reclaiming the memory for old results. Experiment
# with a value that works well for you.

# If you choose cache_size 0 IPython will revert to python's regular >>>
# unnumbered prompt. You will still have _, __ and ___ for your last three
# results, but that will be it.  No dynamic _1, _2, etc. will be created. If
# you are running on a slow machine or with very limited memory, this may
# help.

cache_size 1000


# Classic mode: Setting 'classic 1' you lose many of IPython niceties,
# but that's your choice! Classic 1 -> same as IPython -classic.
# Note that this is _not_ the normal python interpreter, it's simply
# IPython emulating most of the classic interpreter's behavior.
classic 0

# colors - Coloring option for prompts and traceback printouts.

# Currently available schemes: NoColor, Linux, LightBG.

# This option allows coloring the prompts and traceback printouts. This
# requires a terminal which can properly handle color escape sequences. If you
# are having problems with this, use the NoColor scheme (uses no color escapes
# at all).

# The Linux option works well in linux console type environments: dark
# background with light fonts.

# LightBG is similar to Linux but swaps dark/light colors to be more readable
# in light background terminals.

# keep uncommented only the one you want:
colors Linux
#colors LightBG
#colors NoColor

########################
# Note to Windows users

# I haven't been able to ever find a way to make color work reliably under
# Windows. If you find a solution, please let me know so I can include it in
# future releases.

########################


# color_info: IPython can display information about objects via a set of
# functions, and optionally can use colors for this, syntax highlighting
# source code and various other elements. This information is passed through a
# pager (it defaults to 'less' if $PAGER is not set). 

# If your pager has problems, try to setting it to properly handle escapes
# (see the less manpage for detail), or disable this option.  The magic
# function @color_info allows you to toggle this interactively for testing.

color_info 1

# confirm_exit: set to 1 if you want IPython to confirm when you try to exit
# with an EOF (Control-d in Unix, Control-Z/Enter in Windows). Note that using
# the magic functions @Exit or @Quit you can force a direct exit, bypassing
# any confirmation.

confirm_exit 1

# Use deep_reload() as a substitute for reload() by default. deep_reload() is
# still available as dreload() and appears as a builtin.

deep_reload 0

# Which editor to use with the @edit command. If you leave this at 0, IPython
# will honor your EDITOR environment variable. Since this editor is invoked on
# the fly by ipython and is meant for editing small code snippets, you may
# want to use a small, lightweight editor here.

# For Emacs users, setting up your Emacs server properly as described in the
# manual is a good idea. An alternative is to use jed, a very light editor
# with much of the feel of Emacs (though not as powerful for heavy-duty work).

editor 0

# log 1 -> same as ipython -log. This automatically logs to ./ipython.log
log 0

# Same as ipython -Logfile YourLogfileName. 
# Don't use with log 1 (use one or the other)
logfile ''

# banner 0 -> same as ipython -nobanner
banner 1

# messages 0 -> same as ipython -nomessages
messages 1

# Automatically call the pdb debugger after every uncaught exception. If you
# are used to debugging using pdb, this puts you automatically inside of it
# after any call (either in IPython or in code called by it) which triggers an
# exception which goes uncaught.
pdb 0

# Enable the pprint module for printing. pprint tends to give a more readable
# display (than print) for complex nested data structures.
pprint 1


# Prompt strings (see ipython --help for more details).
# Use %n to represent the current prompt number, and quote them to protect
# spaces.
prompt_in1 'In [%n]:'

# In prompt_in2, %n is replaced by as many dots as there are digits in the
# current value of %n.
prompt_in2 '   .%n.:'

prompt_out 'Out[%n]:'


# quick 1 -> same as ipython -quick
quick 0

# Use the readline library (1) or not (0). Most users will want this on, but
# if you experience strange problems with line management (mainly when using
# IPython inside Emacs buffers) you may try disabling it. Not having it on
# prevents you from getting command history with the arrow keys, searching and
# name completion using TAB.

readline 1

# Screen Length: number of lines of your screen. This is used to control
# printing of very long strings. Strings longer than this number of lines will
# be paged with the less command instead of directly printed.

# The default value for this is 0, which means IPython will auto-detect your
# screen size every time it needs to print. If for some reason this isn't
# working well (it needs curses support), specify it yourself. Otherwise don't
# change the default.

screen_length 0

# Prompt separators for input and output.
# Use \n for newline explicitly, without quotes.
# Use 0 (like at the cmd line) to turn off a given separator.

# The structure of prompt printing is:
# (SeparateIn)Input....
# (SeparateOut)Output...
# (SeparateOut2),   # that is, no newline is printed after Out2
# By choosing these you can organize your output any way you want.

separate_in \n

separate_out 0

separate_out2 0

# 'nosep 1' is a shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 0'.
# Simply removes all input/output separators, overriding the choices above.
nosep 0

# xmode - Exception reporting mode. 

# Valid modes: Plain, Context and Verbose.

# Plain: similar to python's normal traceback printing.

# Context: prints 5 lines of context source code around each line in the
# traceback.

# Verbose: similar to Context, but additionally prints the variables currently
# visible where the exception happened (shortening their strings if too
# long). This can potentially be very slow, if you happen to have a huge data
# structure whose string representation is complex to compute. Your computer
# may appear to freeze for a while with cpu usage at 100%. If this occurs, you
# can cancel the traceback with Ctrl-C (maybe hitting it more than once).

#xmode Plain
xmode Context
#xmode Verbose

#---------------------------------------------------------------------------
# Section: Readline configuration (readline is not available for MS-Windows)

# This is done via the following options:

# (i) readline_parse_and_bind: this option can appear as many times as you
# want, each time defining a string to be executed via a
# readline.parse_and_bind() command. The syntax for valid commands of this
# kind can be found by reading the documentation for the GNU readline library,
# as these commands are of the kind which readline accepts in its
# configuration file.

# The TAB key can be used to complete names at the command line in one of two
# ways: 'complete' and 'menu-complete'. The difference is that 'complete' only
# completes as much as possible while 'menu-complete' cycles through all
# possible completions. Leave the one you prefer uncommented.

readline_parse_and_bind tab: complete
#readline_parse_and_bind tab: menu-complete

# This binds Control-l to printing the list of all possible completions when
# there is more than one (what 'complete' does when hitting TAB twice, or at
# the first TAB if show-all-if-ambiguous is on)
readline_parse_and_bind "\C-l": possible-completions

# This forces readline to automatically print the above list when tab
# completion is set to 'complete'. You can still get this list manually by
# using the key bound to 'possible-completions' (Control-l by default) or by
# hitting TAB twice. Turning this on makes the printing happen at the first
# TAB.
readline_parse_and_bind set show-all-if-ambiguous on

# If you have TAB set to complete names, you can rebind any key (Control-o by
# default) to insert a true TAB character.
readline_parse_and_bind "\C-o": tab-insert

# These commands allow you to indent/unindent easily, with the 4-space
# convention of the Python coding standards.  Since IPython's internal
# auto-indent system also uses 4 spaces, you should not change the number of
# spaces in the code below.
readline_parse_and_bind "\M-i": "    "
readline_parse_and_bind "\M-o": "\d\d\d\d"
readline_parse_and_bind "\M-I": "\d\d\d\d"

# Bindings for incremental searches in the history. These searches use the
# string typed so far on the command line and search anything in the previous
# input history containing them.
readline_parse_and_bind "\C-r": reverse-search-history
readline_parse_and_bind "\C-s": forward-search-history

# Bindings for completing the current line in the history of previous
# commands. This allows you to recall any previous command by typing its first
# few letters and hitting Control-p, bypassing all intermediate commands which
# may be in the history (much faster than hitting up-arrow 50 times!)
readline_parse_and_bind "\C-p": history-search-backward
readline_parse_and_bind "\C-n": history-search-forward

# (ii) readline_remove_delims: a string of characters to be removed from the
# default word-delimiters list used by readline, so that completions may be
# performed on strings which contain them.

readline_remove_delims '"[]{}-/~

#"' -- just to fix emacs coloring which gets confused by unmatched quotes.

# (iii) readline_omit__names: normally hitting <tab> after a '.' in a name
# will complete all attributes of an object, including all the special methods
# whose names inlclude double underscores (like __getitem__ or __class__). If
# you'd rather not see these names by default, you can set this option to 1.

# Note that even when this option is set, you can still see those names by
# explicitly typing a _ after the period and hitting <tab>: 'name._<tab>' will
# always complete attribute names starting with '_'.

# This option is off by default so that new users see all attributes of any
# objects they are dealing with.

readline_omit__names 0

#---------------------------------------------------------------------------
# Section: modules to be loaded with 'import ...'

# List, separated by spaces, the names of the modules you want to import

# Example:
# import_mod sys os
# will produce internally the statements
# import sys
# import os

# Each import is executed in its own try/except block, so if one module
# fails to load the others will still be ok.

import_mod 

#---------------------------------------------------------------------------
# Section: modules to import some functions from: 'from ... import ...'

# List, one per line, the modules for which you want only to import some
# functions. Give the module name first and then the name of functions to be
# imported from that module.

# Example:
# import_some struct pack unpack
# will produce internally the statement
# from struct import pack,unpack

# If you have more than one modules_some line, each gets its own try/except
# block (like modules, see above).

import_some 

#---------------------------------------------------------------------------
# Section: modules to import all from : 'from ... import *'

# List (same syntax as import_mod above) those modules for which you want to
# import all functions. Remember, this is a potentially dangerous thing to do,
# since it is very easy to overwrite names of things you need. Use with
# caution.

# Example:
# import_all sys os
# will produce internally the statements
# from sys import *
# from os import *

# As before, each will be called in a separate try/except block.

import_all 

#---------------------------------------------------------------------------
# Section: Python code to execute.

# Put here code to be explicitly executed (keep it simple!)
# Put one line of python code per line. All whitespace is removed (this is a
# feature, not a bug), so don't get fancy building loops here.
# This is just for quick convenient creation of things you want available.

# Example:
# execute x = 1
# execute print 'hello world'; y = z = 'a'
# will produce internally
# x = 1
# print 'hello world'; y = z = 'a'
# and each *line* (not each statement, we don't do python syntax parsing) is
# executed in its own try/except block.

execute 

# Note for the adventurous: you can use this to define your own names for the
# magic functions, by playing some namespace tricks:

# execute __IP.magic_cl = __IP.magic_clear

# defines @cl as a new name for @clear.

#---------------------------------------------------------------------------
# Section: Pyhton files to load and execute.

# Put here the full names of files you want executed with execfile(file).  If
# you want complicated initialization, just write whatever you want in a
# regular python file and load it from here.

# Filenames defined here (which *must* include the extension) are searched for
# through all of sys.path. Since IPython adds your .ipython directory to
# sys.path, they can also be placed in your .ipython dir and will be
# found. Otherwise (if you want to execute things not in .ipyton nor in
# sys.path) give a full path (you can use ~, it gets expanded)

# Example:
# execfile file1.py ~/file2.py
# will generate
# execfile('file1.py')
# execfile('_path_to_your_home/file2.py')

# As before, each file gets its own try/except block.

execfile

# If you are feeling adventurous, you can even add functionality to IPython
# through here. IPython works through a global variable called __ip which
# exists at the time when these files are read. If you know what you are doing
# (read the source) you can add functions to __ip in files loaded here. 

# The file example-magic.py contains a simple but correct example. Try it:

# execfile example-magic.py

# Look at the examples in IPython/iplib.py for more details on how these magic
# functions need to process their arguments.

#---------------------------------------------------------------------------
# Section: aliases for system shell commands

# Here you can define your own names for system commands. The syntax is
# similar to that of the builtin @alias function:

# alias alias_name command_string

# The resulting aliases are auto-generated magic functions (hence usable as
# @alias_name)

# For example:

# alias myls ls -la

# will define '@myls' as an alias for executing the system command 'ls -la'.
# If automagic is on, you can just type myls like you would at a system shell
# prompt.  This allows you to customize IPython's environment to have the same
# aliases you are accustomed to from your own shell.

# You can also define aliases with parameters using %s specifiers (one per
# parameter):

# alias parts echo first %s second %s

# will give you in IPython:
# >>> @parts A B
# first A second B

# Use one 'alias' statement per alias you wish to define.

alias 

#************************* end of file <ipythonrc> ************************


IPython profiles

As we already mentioned, IPython supports the -profile command-line option (see sec. 5.1). 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>, 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.

In sections 11 and 12 we discuss some particular profiles which come as part of the standard IPython distribution. You may also look in your IPYTHONDIR directory, any file whose name begins with ipythonrc- is a profile. You can use those as examples for further customizations to suit your own needs.


next up previous
Next: Using IPython as your Up: IPython An enhanced Interactive Previous: Interactive use
Fernando Perez 2003-08-25