##// END OF EJS Templates
update docs with new cl-arguments
MinRK -
Show More
@@ -1,136 +1,136 b''
1 .. _configuring_ipython:
1 .. _configuring_ipython:
2
2
3 ===========================================================
3 ===========================================================
4 Configuring the :command:`ipython` command line application
4 Configuring the :command:`ipython` command line application
5 ===========================================================
5 ===========================================================
6
6
7 This section contains information about how to configure the
7 This section contains information about how to configure the
8 :command:`ipython` command line application. See the :ref:`configuration
8 :command:`ipython` command line application. See the :ref:`configuration
9 overview <config_overview>` for a more general description of the
9 overview <config_overview>` for a more general description of the
10 configuration system and configuration file format.
10 configuration system and configuration file format.
11
11
12 The default configuration file for the :command:`ipython` command line application
12 The default configuration file for the :command:`ipython` command line application
13 is :file:`ipython_config.py`. By setting the attributes in this file, you
13 is :file:`ipython_config.py`. By setting the attributes in this file, you
14 can configure the application. A sample is provided in
14 can configure the application. A sample is provided in
15 :mod:`IPython.config.default.ipython_config`. Simply copy this file to your
15 :mod:`IPython.config.default.ipython_config`. Simply copy this file to your
16 :ref:`IPython directory <ipython_dir>` to start using it.
16 :ref:`IPython directory <ipython_dir>` to start using it.
17
17
18 Most configuration attributes that this file accepts are associated with
18 Most configuration attributes that this file accepts are associated with
19 classes that are subclasses of :class:`~IPython.core.component.Component`.
19 classes that are subclasses of :class:`~IPython.core.component.Component`.
20
20
21 A few configuration attributes are not associated with a particular
21 A few configuration attributes are not associated with a particular
22 :class:`~IPython.core.component.Component` subclass. These are application
22 :class:`~IPython.core.component.Component` subclass. These are application
23 wide configuration attributes and are stored in the ``Global``
23 wide configuration attributes and are stored in the ``Global``
24 sub-configuration section. We begin with a description of these
24 sub-configuration section. We begin with a description of these
25 attributes.
25 attributes.
26
26
27 Global configuration
27 Global configuration
28 ====================
28 ====================
29
29
30 Assuming that your configuration file has the following at the top::
30 Assuming that your configuration file has the following at the top::
31
31
32 c = get_config()
32 c = get_config()
33
33
34 the following attributes can be set in the ``Global`` section.
34 the following attributes can be set in the ``Global`` section.
35
35
36 :attr:`c.Global.display_banner`
36 :attr:`c.IPythonApp.display_banner`
37 A boolean that determined if the banner is printer when :command:`ipython`
37 A boolean that determined if the banner is printer when :command:`ipython`
38 is started.
38 is started.
39
39
40 :attr:`c.Global.classic`
40 :attr:`c.IPythonApp.classic`
41 A boolean that determines if IPython starts in "classic" mode. In this
41 A boolean that determines if IPython starts in "classic" mode. In this
42 mode, the prompts and everything mimic that of the normal :command:`python`
42 mode, the prompts and everything mimic that of the normal :command:`python`
43 shell
43 shell
44
44
45 :attr:`c.Global.nosep`
45 :attr:`c.IPythonApp.nosep`
46 A boolean that determines if there should be no blank lines between
46 A boolean that determines if there should be no blank lines between
47 prompts.
47 prompts.
48
48
49 :attr:`c.Global.log_level`
49 :attr:`c.IPythonApp.log_level`
50 An integer that sets the detail of the logging level during the startup
50 An integer that sets the detail of the logging level during the startup
51 of :command:`ipython`. The default is 30 and the possible values are
51 of :command:`ipython`. The default is 30 and the possible values are
52 (0, 10, 20, 30, 40, 50). Higher is quieter and lower is more verbose.
52 (0, 10, 20, 30, 40, 50). Higher is quieter and lower is more verbose.
53
53
54 :attr:`c.Global.extensions`
54 :attr:`c.IPythonApp.extensions`
55 A list of strings, each of which is an importable IPython extension. An
55 A list of strings, each of which is an importable IPython extension. An
56 IPython extension is a regular Python module or package that has a
56 IPython extension is a regular Python module or package that has a
57 :func:`load_ipython_extension(ip)` method. This method gets called when
57 :func:`load_ipython_extension(ip)` method. This method gets called when
58 the extension is loaded with the currently running
58 the extension is loaded with the currently running
59 :class:`~IPython.core.iplib.InteractiveShell` as its only argument. You
59 :class:`~IPython.core.iplib.InteractiveShell` as its only argument. You
60 can put your extensions anywhere they can be imported but we add the
60 can put your extensions anywhere they can be imported but we add the
61 :file:`extensions` subdirectory of the ipython directory to ``sys.path``
61 :file:`extensions` subdirectory of the ipython directory to ``sys.path``
62 during extension loading, so you can put them there as well. Extensions
62 during extension loading, so you can put them there as well. Extensions
63 are not executed in the user's interactive namespace and they must be pure
63 are not executed in the user's interactive namespace and they must be pure
64 Python code. Extensions are the recommended way of customizing
64 Python code. Extensions are the recommended way of customizing
65 :command:`ipython`. Extensions can provide an
65 :command:`ipython`. Extensions can provide an
66 :func:`unload_ipython_extension` that will be called when the extension is
66 :func:`unload_ipython_extension` that will be called when the extension is
67 unloaded.
67 unloaded.
68
68
69 :attr:`c.Global.exec_lines`
69 :attr:`c.IPythonApp.exec_lines`
70 A list of strings, each of which is Python code that is run in the user's
70 A list of strings, each of which is Python code that is run in the user's
71 namespace after IPython start. These lines can contain full IPython syntax
71 namespace after IPython start. These lines can contain full IPython syntax
72 with magics, etc.
72 with magics, etc.
73
73
74 :attr:`c.Global.exec_files`
74 :attr:`c.IPythonApp.exec_files`
75 A list of strings, each of which is the full pathname of a ``.py`` or
75 A list of strings, each of which is the full pathname of a ``.py`` or
76 ``.ipy`` file that will be executed as IPython starts. These files are run
76 ``.ipy`` file that will be executed as IPython starts. These files are run
77 in IPython in the user's namespace. Files with a ``.py`` extension need to
77 in IPython in the user's namespace. Files with a ``.py`` extension need to
78 be pure Python. Files with a ``.ipy`` extension can have custom IPython
78 be pure Python. Files with a ``.ipy`` extension can have custom IPython
79 syntax (magics, etc.). These files need to be in the cwd, the ipythondir
79 syntax (magics, etc.). These files need to be in the cwd, the ipythondir
80 or be absolute paths.
80 or be absolute paths.
81
81
82 Classes that can be configured
82 Classes that can be configured
83 ==============================
83 ==============================
84
84
85 The following classes can also be configured in the configuration file for
85 The following classes can also be configured in the configuration file for
86 :command:`ipython`:
86 :command:`ipython`:
87
87
88 * :class:`~IPython.core.iplib.InteractiveShell`
88 * :class:`~IPython.core.iplib.InteractiveShell`
89
89
90 * :class:`~IPython.core.prefilter.PrefilterManager`
90 * :class:`~IPython.core.prefilter.PrefilterManager`
91
91
92 * :class:`~IPython.core.alias.AliasManager`
92 * :class:`~IPython.core.alias.AliasManager`
93
93
94 To see which attributes of these classes are configurable, please see the
94 To see which attributes of these classes are configurable, please see the
95 source code for these classes, the class docstrings or the sample
95 source code for these classes, the class docstrings or the sample
96 configuration file :mod:`IPython.config.default.ipython_config`.
96 configuration file :mod:`IPython.config.default.ipython_config`.
97
97
98 Example
98 Example
99 =======
99 =======
100
100
101 For those who want to get a quick start, here is a sample
101 For those who want to get a quick start, here is a sample
102 :file:`ipython_config.py` that sets some of the common configuration
102 :file:`ipython_config.py` that sets some of the common configuration
103 attributes::
103 attributes::
104
104
105 # sample ipython_config.py
105 # sample ipython_config.py
106 c = get_config()
106 c = get_config()
107
107
108 c.Global.display_banner = True
108 c.IPythonApp.display_banner = True
109 c.Global.log_level = 20
109 c.IPythonApp.log_level = 20
110 c.Global.extensions = [
110 c.IPythonApp.extensions = [
111 'myextension'
111 'myextension'
112 ]
112 ]
113 c.Global.exec_lines = [
113 c.IPythonApp.exec_lines = [
114 'import numpy',
114 'import numpy',
115 'import scipy'
115 'import scipy'
116 ]
116 ]
117 c.Global.exec_files = [
117 c.IPythonApp.exec_files = [
118 'mycode.py',
118 'mycode.py',
119 'fancy.ipy'
119 'fancy.ipy'
120 ]
120 ]
121 c.InteractiveShell.autoindent = True
121 c.InteractiveShell.autoindent = True
122 c.InteractiveShell.colors = 'LightBG'
122 c.InteractiveShell.colors = 'LightBG'
123 c.InteractiveShell.confirm_exit = False
123 c.InteractiveShell.confirm_exit = False
124 c.InteractiveShell.deep_reload = True
124 c.InteractiveShell.deep_reload = True
125 c.InteractiveShell.editor = 'nano'
125 c.InteractiveShell.editor = 'nano'
126 c.InteractiveShell.prompt_in1 = 'In [\#]: '
126 c.InteractiveShell.prompt_in1 = 'In [\#]: '
127 c.InteractiveShell.prompt_in2 = ' .\D.: '
127 c.InteractiveShell.prompt_in2 = ' .\D.: '
128 c.InteractiveShell.prompt_out = 'Out[\#]: '
128 c.InteractiveShell.prompt_out = 'Out[\#]: '
129 c.InteractiveShell.prompts_pad_left = True
129 c.InteractiveShell.prompts_pad_left = True
130 c.InteractiveShell.xmode = 'Context'
130 c.InteractiveShell.xmode = 'Context'
131
131
132 c.PrefilterManager.multi_line_specials = True
132 c.PrefilterManager.multi_line_specials = True
133
133
134 c.AliasManager.user_aliases = [
134 c.AliasManager.user_aliases = [
135 ('la', 'ls -al')
135 ('la', 'ls -al')
136 ]
136 ]
@@ -1,342 +1,342 b''
1 .. _config_overview:
1 .. _config_overview:
2
2
3 ============================================
3 ============================================
4 Overview of the IPython configuration system
4 Overview of the IPython configuration system
5 ============================================
5 ============================================
6
6
7 This section describes the IPython configuration system. Starting with version
7 This section describes the IPython configuration system. Starting with version
8 0.11, IPython has a completely new configuration system that is quite
8 0.11, IPython has a completely new configuration system that is quite
9 different from the older :file:`ipythonrc` or :file:`ipy_user_conf.py`
9 different from the older :file:`ipythonrc` or :file:`ipy_user_conf.py`
10 approaches. The new configuration system was designed from scratch to address
10 approaches. The new configuration system was designed from scratch to address
11 the particular configuration needs of IPython. While there are many
11 the particular configuration needs of IPython. While there are many
12 other excellent configuration systems out there, we found that none of them
12 other excellent configuration systems out there, we found that none of them
13 met our requirements.
13 met our requirements.
14
14
15 .. warning::
15 .. warning::
16
16
17 If you are upgrading to version 0.11 of IPython, you will need to migrate
17 If you are upgrading to version 0.11 of IPython, you will need to migrate
18 your old :file:`ipythonrc` or :file:`ipy_user_conf.py` configuration files
18 your old :file:`ipythonrc` or :file:`ipy_user_conf.py` configuration files
19 to the new system. Read on for information on how to do this.
19 to the new system. Read on for information on how to do this.
20
20
21 The discussion that follows is focused on teaching user's how to configure
21 The discussion that follows is focused on teaching user's how to configure
22 IPython to their liking. Developer's who want to know more about how they
22 IPython to their liking. Developer's who want to know more about how they
23 can enable their objects to take advantage of the configuration system
23 can enable their objects to take advantage of the configuration system
24 should consult our :ref:`developer guide <developer_guide>`
24 should consult our :ref:`developer guide <developer_guide>`
25
25
26 The main concepts
26 The main concepts
27 =================
27 =================
28
28
29 There are a number of abstractions that the IPython configuration system uses.
29 There are a number of abstractions that the IPython configuration system uses.
30 Each of these abstractions is represented by a Python class.
30 Each of these abstractions is represented by a Python class.
31
31
32 Configuration object: :class:`~IPython.config.loader.Config`
32 Configuration object: :class:`~IPython.config.loader.Config`
33 A configuration object is a simple dictionary-like class that holds
33 A configuration object is a simple dictionary-like class that holds
34 configuration attributes and sub-configuration objects. These classes
34 configuration attributes and sub-configuration objects. These classes
35 support dotted attribute style access (``Foo.bar``) in addition to the
35 support dotted attribute style access (``Foo.bar``) in addition to the
36 regular dictionary style access (``Foo['bar']``). Configuration objects
36 regular dictionary style access (``Foo['bar']``). Configuration objects
37 are smart. They know how to merge themselves with other configuration
37 are smart. They know how to merge themselves with other configuration
38 objects and they automatically create sub-configuration objects.
38 objects and they automatically create sub-configuration objects.
39
39
40 Application: :class:`~IPython.core.application.Application`
40 Application: :class:`~IPython.core.application.Application`
41 An application is a process that does a specific job. The most obvious
41 An application is a process that does a specific job. The most obvious
42 application is the :command:`ipython` command line program. Each
42 application is the :command:`ipython` command line program. Each
43 application reads a *single* configuration file and command line options
43 application reads a *single* configuration file and command line options
44 and then produces a master configuration object for the application. This
44 and then produces a master configuration object for the application. This
45 configuration object is then passed to the configurable objects that the
45 configuration object is then passed to the configurable objects that the
46 application creates. These configurable objects implement the actual logic
46 application creates. These configurable objects implement the actual logic
47 of the application and know how to configure themselves given the
47 of the application and know how to configure themselves given the
48 configuration object.
48 configuration object.
49
49
50 Component: :class:`~IPython.config.configurable.Configurable`
50 Component: :class:`~IPython.config.configurable.Configurable`
51 A configurable is a regular Python class that serves as a base class for
51 A configurable is a regular Python class that serves as a base class for
52 all main classes in an application. The
52 all main classes in an application. The
53 :class:`~IPython.config.configurable.Configurable` base class is
53 :class:`~IPython.config.configurable.Configurable` base class is
54 lightweight and only does one things.
54 lightweight and only does one things.
55
55
56 This :class:`~IPython.config.configurable.Configurable` is a subclass
56 This :class:`~IPython.config.configurable.Configurable` is a subclass
57 of :class:`~IPython.utils.traitlets.HasTraits` that knows how to configure
57 of :class:`~IPython.utils.traitlets.HasTraits` that knows how to configure
58 itself. Class level traits with the metadata ``config=True`` become
58 itself. Class level traits with the metadata ``config=True`` become
59 values that can be configured from the command line and configuration
59 values that can be configured from the command line and configuration
60 files.
60 files.
61
61
62 Developers create :class:`~IPython.config.configurable.Configurable`
62 Developers create :class:`~IPython.config.configurable.Configurable`
63 subclasses that implement all of the logic in the application. Each of
63 subclasses that implement all of the logic in the application. Each of
64 these subclasses has its own configuration information that controls how
64 these subclasses has its own configuration information that controls how
65 instances are created.
65 instances are created.
66
66
67 Having described these main concepts, we can now state the main idea in our
67 Having described these main concepts, we can now state the main idea in our
68 configuration system: *"configuration" allows the default values of class
68 configuration system: *"configuration" allows the default values of class
69 attributes to be controlled on a class by class basis*. Thus all instances of
69 attributes to be controlled on a class by class basis*. Thus all instances of
70 a given class are configured in the same way. Furthermore, if two instances
70 a given class are configured in the same way. Furthermore, if two instances
71 need to be configured differently, they need to be instances of two different
71 need to be configured differently, they need to be instances of two different
72 classes. While this model may seem a bit restrictive, we have found that it
72 classes. While this model may seem a bit restrictive, we have found that it
73 expresses most things that need to be configured extremely well. However, it
73 expresses most things that need to be configured extremely well. However, it
74 is possible to create two instances of the same class that have different
74 is possible to create two instances of the same class that have different
75 trait values. This is done by overriding the configuration.
75 trait values. This is done by overriding the configuration.
76
76
77 Now, we show what our configuration objects and files look like.
77 Now, we show what our configuration objects and files look like.
78
78
79 Configuration objects and files
79 Configuration objects and files
80 ===============================
80 ===============================
81
81
82 A configuration file is simply a pure Python file that sets the attributes
82 A configuration file is simply a pure Python file that sets the attributes
83 of a global, pre-created configuration object. This configuration object is a
83 of a global, pre-created configuration object. This configuration object is a
84 :class:`~IPython.config.loader.Config` instance. While in a configuration
84 :class:`~IPython.config.loader.Config` instance. While in a configuration
85 file, to get a reference to this object, simply call the :func:`get_config`
85 file, to get a reference to this object, simply call the :func:`get_config`
86 function. We inject this function into the global namespace that the
86 function. We inject this function into the global namespace that the
87 configuration file is executed in.
87 configuration file is executed in.
88
88
89 Here is an example of a super simple configuration file that does nothing::
89 Here is an example of a super simple configuration file that does nothing::
90
90
91 c = get_config()
91 c = get_config()
92
92
93 Once you get a reference to the configuration object, you simply set
93 Once you get a reference to the configuration object, you simply set
94 attributes on it. All you have to know is:
94 attributes on it. All you have to know is:
95
95
96 * The name of each attribute.
96 * The name of each attribute.
97 * The type of each attribute.
97 * The type of each attribute.
98
98
99 The answers to these two questions are provided by the various
99 The answers to these two questions are provided by the various
100 :class:`~IPython.config.configurable.Configurable` subclasses that an
100 :class:`~IPython.config.configurable.Configurable` subclasses that an
101 application uses. Let's look at how this would work for a simple component
101 application uses. Let's look at how this would work for a simple component
102 subclass::
102 subclass::
103
103
104 # Sample component that can be configured.
104 # Sample component that can be configured.
105 from IPython.config.configurable import Configurable
105 from IPython.config.configurable import Configurable
106 from IPython.utils.traitlets import Int, Float, Str, Bool
106 from IPython.utils.traitlets import Int, Float, Str, Bool
107
107
108 class MyClass(Configurable):
108 class MyClass(Configurable):
109 name = Str('defaultname', config=True)
109 name = Str('defaultname', config=True)
110 ranking = Int(0, config=True)
110 ranking = Int(0, config=True)
111 value = Float(99.0)
111 value = Float(99.0)
112 # The rest of the class implementation would go here..
112 # The rest of the class implementation would go here..
113
113
114 In this example, we see that :class:`MyClass` has three attributes, two
114 In this example, we see that :class:`MyClass` has three attributes, two
115 of whom (``name``, ``ranking``) can be configured. All of the attributes
115 of whom (``name``, ``ranking``) can be configured. All of the attributes
116 are given types and default values. If a :class:`MyClass` is instantiated,
116 are given types and default values. If a :class:`MyClass` is instantiated,
117 but not configured, these default values will be used. But let's see how
117 but not configured, these default values will be used. But let's see how
118 to configure this class in a configuration file::
118 to configure this class in a configuration file::
119
119
120 # Sample config file
120 # Sample config file
121 c = get_config()
121 c = get_config()
122
122
123 c.MyClass.name = 'coolname'
123 c.MyClass.name = 'coolname'
124 c.MyClass.ranking = 10
124 c.MyClass.ranking = 10
125
125
126 After this configuration file is loaded, the values set in it will override
126 After this configuration file is loaded, the values set in it will override
127 the class defaults anytime a :class:`MyClass` is created. Furthermore,
127 the class defaults anytime a :class:`MyClass` is created. Furthermore,
128 these attributes will be type checked and validated anytime they are set.
128 these attributes will be type checked and validated anytime they are set.
129 This type checking is handled by the :mod:`IPython.utils.traitlets` module,
129 This type checking is handled by the :mod:`IPython.utils.traitlets` module,
130 which provides the :class:`Str`, :class:`Int` and :class:`Float` types. In
130 which provides the :class:`Str`, :class:`Int` and :class:`Float` types. In
131 addition to these traitlets, the :mod:`IPython.utils.traitlets` provides
131 addition to these traitlets, the :mod:`IPython.utils.traitlets` provides
132 traitlets for a number of other types.
132 traitlets for a number of other types.
133
133
134 .. note::
134 .. note::
135
135
136 Underneath the hood, the :class:`Configurable` base class is a subclass of
136 Underneath the hood, the :class:`Configurable` base class is a subclass of
137 :class:`IPython.utils.traitlets.HasTraits`. The
137 :class:`IPython.utils.traitlets.HasTraits`. The
138 :mod:`IPython.utils.traitlets` module is a lightweight version of
138 :mod:`IPython.utils.traitlets` module is a lightweight version of
139 :mod:`enthought.traits`. Our implementation is a pure Python subset
139 :mod:`enthought.traits`. Our implementation is a pure Python subset
140 (mostly API compatible) of :mod:`enthought.traits` that does not have any
140 (mostly API compatible) of :mod:`enthought.traits` that does not have any
141 of the automatic GUI generation capabilities. Our plan is to achieve 100%
141 of the automatic GUI generation capabilities. Our plan is to achieve 100%
142 API compatibility to enable the actual :mod:`enthought.traits` to
142 API compatibility to enable the actual :mod:`enthought.traits` to
143 eventually be used instead. Currently, we cannot use
143 eventually be used instead. Currently, we cannot use
144 :mod:`enthought.traits` as we are committed to the core of IPython being
144 :mod:`enthought.traits` as we are committed to the core of IPython being
145 pure Python.
145 pure Python.
146
146
147 It should be very clear at this point what the naming convention is for
147 It should be very clear at this point what the naming convention is for
148 configuration attributes::
148 configuration attributes::
149
149
150 c.ClassName.attribute_name = attribute_value
150 c.ClassName.attribute_name = attribute_value
151
151
152 Here, ``ClassName`` is the name of the class whose configuration attribute you
152 Here, ``ClassName`` is the name of the class whose configuration attribute you
153 want to set, ``attribute_name`` is the name of the attribute you want to set
153 want to set, ``attribute_name`` is the name of the attribute you want to set
154 and ``attribute_value`` the the value you want it to have. The ``ClassName``
154 and ``attribute_value`` the the value you want it to have. The ``ClassName``
155 attribute of ``c`` is not the actual class, but instead is another
155 attribute of ``c`` is not the actual class, but instead is another
156 :class:`~IPython.config.loader.Config` instance.
156 :class:`~IPython.config.loader.Config` instance.
157
157
158 .. note::
158 .. note::
159
159
160 The careful reader may wonder how the ``ClassName`` (``MyClass`` in
160 The careful reader may wonder how the ``ClassName`` (``MyClass`` in
161 the above example) attribute of the configuration object ``c`` gets
161 the above example) attribute of the configuration object ``c`` gets
162 created. These attributes are created on the fly by the
162 created. These attributes are created on the fly by the
163 :class:`~IPython.config.loader.Config` instance, using a simple naming
163 :class:`~IPython.config.loader.Config` instance, using a simple naming
164 convention. Any attribute of a :class:`~IPython.config.loader.Config`
164 convention. Any attribute of a :class:`~IPython.config.loader.Config`
165 instance whose name begins with an uppercase character is assumed to be a
165 instance whose name begins with an uppercase character is assumed to be a
166 sub-configuration and a new empty :class:`~IPython.config.loader.Config`
166 sub-configuration and a new empty :class:`~IPython.config.loader.Config`
167 instance is dynamically created for that attribute. This allows deeply
167 instance is dynamically created for that attribute. This allows deeply
168 hierarchical information created easily (``c.Foo.Bar.value``) on the fly.
168 hierarchical information created easily (``c.Foo.Bar.value``) on the fly.
169
169
170 Configuration files inheritance
170 Configuration files inheritance
171 ===============================
171 ===============================
172
172
173 Let's say you want to have different configuration files for various purposes.
173 Let's say you want to have different configuration files for various purposes.
174 Our configuration system makes it easy for one configuration file to inherit
174 Our configuration system makes it easy for one configuration file to inherit
175 the information in another configuration file. The :func:`load_subconfig`
175 the information in another configuration file. The :func:`load_subconfig`
176 command can be used in a configuration file for this purpose. Here is a simple
176 command can be used in a configuration file for this purpose. Here is a simple
177 example that loads all of the values from the file :file:`base_config.py`::
177 example that loads all of the values from the file :file:`base_config.py`::
178
178
179 # base_config.py
179 # base_config.py
180 c = get_config()
180 c = get_config()
181 c.MyClass.name = 'coolname'
181 c.MyClass.name = 'coolname'
182 c.MyClass.ranking = 100
182 c.MyClass.ranking = 100
183
183
184 into the configuration file :file:`main_config.py`::
184 into the configuration file :file:`main_config.py`::
185
185
186 # main_config.py
186 # main_config.py
187 c = get_config()
187 c = get_config()
188
188
189 # Load everything from base_config.py
189 # Load everything from base_config.py
190 load_subconfig('base_config.py')
190 load_subconfig('base_config.py')
191
191
192 # Now override one of the values
192 # Now override one of the values
193 c.MyClass.name = 'bettername'
193 c.MyClass.name = 'bettername'
194
194
195 In a situation like this the :func:`load_subconfig` makes sure that the
195 In a situation like this the :func:`load_subconfig` makes sure that the
196 search path for sub-configuration files is inherited from that of the parent.
196 search path for sub-configuration files is inherited from that of the parent.
197 Thus, you can typically put the two in the same directory and everything will
197 Thus, you can typically put the two in the same directory and everything will
198 just work.
198 just work.
199
199
200 Class based configuration inheritance
200 Class based configuration inheritance
201 =====================================
201 =====================================
202
202
203 There is another aspect of configuration where inheritance comes into play.
203 There is another aspect of configuration where inheritance comes into play.
204 Sometimes, your classes will have an inheritance hierarchy that you want
204 Sometimes, your classes will have an inheritance hierarchy that you want
205 to be reflected in the configuration system. Here is a simple example::
205 to be reflected in the configuration system. Here is a simple example::
206
206
207 from IPython.config.configurable import Configurable
207 from IPython.config.configurable import Configurable
208 from IPython.utils.traitlets import Int, Float, Str, Bool
208 from IPython.utils.traitlets import Int, Float, Str, Bool
209
209
210 class Foo(Configurable):
210 class Foo(Configurable):
211 name = Str('fooname', config=True)
211 name = Str('fooname', config=True)
212 value = Float(100.0, config=True)
212 value = Float(100.0, config=True)
213
213
214 class Bar(Foo):
214 class Bar(Foo):
215 name = Str('barname', config=True)
215 name = Str('barname', config=True)
216 othervalue = Int(0, config=True)
216 othervalue = Int(0, config=True)
217
217
218 Now, we can create a configuration file to configure instances of :class:`Foo`
218 Now, we can create a configuration file to configure instances of :class:`Foo`
219 and :class:`Bar`::
219 and :class:`Bar`::
220
220
221 # config file
221 # config file
222 c = get_config()
222 c = get_config()
223
223
224 c.Foo.name = 'bestname'
224 c.Foo.name = 'bestname'
225 c.Bar.othervalue = 10
225 c.Bar.othervalue = 10
226
226
227 This class hierarchy and configuration file accomplishes the following:
227 This class hierarchy and configuration file accomplishes the following:
228
228
229 * The default value for :attr:`Foo.name` and :attr:`Bar.name` will be
229 * The default value for :attr:`Foo.name` and :attr:`Bar.name` will be
230 'bestname'. Because :class:`Bar` is a :class:`Foo` subclass it also
230 'bestname'. Because :class:`Bar` is a :class:`Foo` subclass it also
231 picks up the configuration information for :class:`Foo`.
231 picks up the configuration information for :class:`Foo`.
232 * The default value for :attr:`Foo.value` and :attr:`Bar.value` will be
232 * The default value for :attr:`Foo.value` and :attr:`Bar.value` will be
233 ``100.0``, which is the value specified as the class default.
233 ``100.0``, which is the value specified as the class default.
234 * The default value for :attr:`Bar.othervalue` will be 10 as set in the
234 * The default value for :attr:`Bar.othervalue` will be 10 as set in the
235 configuration file. Because :class:`Foo` is the parent of :class:`Bar`
235 configuration file. Because :class:`Foo` is the parent of :class:`Bar`
236 it doesn't know anything about the :attr:`othervalue` attribute.
236 it doesn't know anything about the :attr:`othervalue` attribute.
237
237
238
238
239 .. _ipython_dir:
239 .. _ipython_dir:
240
240
241 Configuration file location
241 Configuration file location
242 ===========================
242 ===========================
243
243
244 So where should you put your configuration files? By default, all IPython
244 So where should you put your configuration files? By default, all IPython
245 applications look in the so called "IPython directory". The location of
245 applications look in the so called "IPython directory". The location of
246 this directory is determined by the following algorithm:
246 this directory is determined by the following algorithm:
247
247
248 * If the ``--ipython-dir`` command line flag is given, its value is used.
248 * If the ``ipython_dir`` command line flag is given, its value is used.
249
249
250 * If not, the value returned by :func:`IPython.utils.path.get_ipython_dir`
250 * If not, the value returned by :func:`IPython.utils.path.get_ipython_dir`
251 is used. This function will first look at the :envvar:`IPYTHON_DIR`
251 is used. This function will first look at the :envvar:`IPYTHON_DIR`
252 environment variable and then default to a platform-specific default.
252 environment variable and then default to a platform-specific default.
253
253
254 On posix systems (Linux, Unix, etc.), IPython respects the ``$XDG_CONFIG_HOME``
254 On posix systems (Linux, Unix, etc.), IPython respects the ``$XDG_CONFIG_HOME``
255 part of the `XDG Base Directory`_ specification. If ``$XDG_CONFIG_HOME`` is
255 part of the `XDG Base Directory`_ specification. If ``$XDG_CONFIG_HOME`` is
256 defined and exists ( ``XDG_CONFIG_HOME`` has a default interpretation of
256 defined and exists ( ``XDG_CONFIG_HOME`` has a default interpretation of
257 :file:`$HOME/.config`), then IPython's config directory will be located in
257 :file:`$HOME/.config`), then IPython's config directory will be located in
258 :file:`$XDG_CONFIG_HOME/ipython`. If users still have an IPython directory
258 :file:`$XDG_CONFIG_HOME/ipython`. If users still have an IPython directory
259 in :file:`$HOME/.ipython`, then that will be used. in preference to the
259 in :file:`$HOME/.ipython`, then that will be used. in preference to the
260 system default.
260 system default.
261
261
262 For most users, the default value will simply be something like
262 For most users, the default value will simply be something like
263 :file:`$HOME/.config/ipython` on Linux, or :file:`$HOME/.ipython`
263 :file:`$HOME/.config/ipython` on Linux, or :file:`$HOME/.ipython`
264 elsewhere.
264 elsewhere.
265
265
266 Once the location of the IPython directory has been determined, you need to
266 Once the location of the IPython directory has been determined, you need to
267 know what filename to use for the configuration file. The basic idea is that
267 know what filename to use for the configuration file. The basic idea is that
268 each application has its own default configuration filename. The default named
268 each application has its own default configuration filename. The default named
269 used by the :command:`ipython` command line program is
269 used by the :command:`ipython` command line program is
270 :file:`ipython_config.py`. This value can be overriden by the ``-config_file``
270 :file:`ipython_config.py`. This value can be overriden by the ``config_file``
271 command line flag. A sample :file:`ipython_config.py` file can be found
271 command line flag. A sample :file:`ipython_config.py` file can be found
272 in :mod:`IPython.config.default.ipython_config.py`. Simple copy it to your
272 in :mod:`IPython.config.default.ipython_config.py`. Simple copy it to your
273 IPython directory to begin using it.
273 IPython directory to begin using it.
274
274
275 .. _Profiles:
275 .. _Profiles:
276
276
277 Profiles
277 Profiles
278 ========
278 ========
279
279
280 A profile is simply a configuration file that follows a simple naming
280 A profile is simply a configuration file that follows a simple naming
281 convention and can be loaded using a simplified syntax. The idea is
281 convention and can be loaded using a simplified syntax. The idea is
282 that users often want to maintain a set of configuration files for different
282 that users often want to maintain a set of configuration files for different
283 purposes: one for doing numerical computing with NumPy and SciPy and
283 purposes: one for doing numerical computing with NumPy and SciPy and
284 another for doing symbolic computing with SymPy. Profiles make it easy
284 another for doing symbolic computing with SymPy. Profiles make it easy
285 to keep a separate configuration file for each of these purposes.
285 to keep a separate configuration file for each of these purposes.
286
286
287 Let's start by showing how a profile is used:
287 Let's start by showing how a profile is used:
288
288
289 .. code-block:: bash
289 .. code-block:: bash
290
290
291 $ ipython -p sympy
291 $ ipython profile=sympy
292
292
293 This tells the :command:`ipython` command line program to get its
293 This tells the :command:`ipython` command line program to get its
294 configuration from the "sympy" profile. The search path for profiles is the
294 configuration from the "sympy" profile. The search path for profiles is the
295 same as that of regular configuration files. The only difference is that
295 same as that of regular configuration files. The only difference is that
296 profiles are named in a special way. In the case above, the "sympy" profile
296 profiles are named in a special way. In the case above, the "sympy" profile
297 would need to have the name :file:`ipython_config_sympy.py`.
297 would need to have the name :file:`ipython_config_sympy.py`.
298
298
299 The general pattern is this: simply add ``_profilename`` to the end of the
299 The general pattern is this: simply add ``<profilename>`` to the end of the
300 normal configuration file name. Then load the profile by adding ``-p
300 normal configuration file name. Then load the profile by adding
301 profilename`` to your command line options.
301 ``profile=<profilename>`` to your command line options.
302
302
303 IPython ships with some sample profiles in :mod:`IPython.config.profile`.
303 IPython ships with some sample profiles in :mod:`IPython.config.profile`.
304 Simply copy these to your IPython directory to begin using them.
304 Simply copy these to your IPython directory to begin using them.
305
305
306 Design requirements
306 Design requirements
307 ===================
307 ===================
308
308
309 Here are the main requirements we wanted our configuration system to have:
309 Here are the main requirements we wanted our configuration system to have:
310
310
311 * Support for hierarchical configuration information.
311 * Support for hierarchical configuration information.
312
312
313 * Full integration with command line option parsers. Often, you want to read
313 * Full integration with command line option parsers. Often, you want to read
314 a configuration file, but then override some of the values with command line
314 a configuration file, but then override some of the values with command line
315 options. Our configuration system automates this process and allows each
315 options. Our configuration system automates this process and allows each
316 command line option to be linked to a particular attribute in the
316 command line option to be linked to a particular attribute in the
317 configuration hierarchy that it will override.
317 configuration hierarchy that it will override.
318
318
319 * Configuration files that are themselves valid Python code. This accomplishes
319 * Configuration files that are themselves valid Python code. This accomplishes
320 many things. First, it becomes possible to put logic in your configuration
320 many things. First, it becomes possible to put logic in your configuration
321 files that sets attributes based on your operating system, network setup,
321 files that sets attributes based on your operating system, network setup,
322 Python version, etc. Second, Python has a super simple syntax for accessing
322 Python version, etc. Second, Python has a super simple syntax for accessing
323 hierarchical data structures, namely regular attribute access
323 hierarchical data structures, namely regular attribute access
324 (``Foo.Bar.Bam.name``). Third, using Python makes it easy for users to
324 (``Foo.Bar.Bam.name``). Third, using Python makes it easy for users to
325 import configuration attributes from one configuration file to another.
325 import configuration attributes from one configuration file to another.
326 Forth, even though Python is dynamically typed, it does have types that can
326 Forth, even though Python is dynamically typed, it does have types that can
327 be checked at runtime. Thus, a ``1`` in a config file is the integer '1',
327 be checked at runtime. Thus, a ``1`` in a config file is the integer '1',
328 while a ``'1'`` is a string.
328 while a ``'1'`` is a string.
329
329
330 * A fully automated method for getting the configuration information to the
330 * A fully automated method for getting the configuration information to the
331 classes that need it at runtime. Writing code that walks a configuration
331 classes that need it at runtime. Writing code that walks a configuration
332 hierarchy to extract a particular attribute is painful. When you have
332 hierarchy to extract a particular attribute is painful. When you have
333 complex configuration information with hundreds of attributes, this makes
333 complex configuration information with hundreds of attributes, this makes
334 you want to cry.
334 you want to cry.
335
335
336 * Type checking and validation that doesn't require the entire configuration
336 * Type checking and validation that doesn't require the entire configuration
337 hierarchy to be specified statically before runtime. Python is a very
337 hierarchy to be specified statically before runtime. Python is a very
338 dynamic language and you don't always know everything that needs to be
338 dynamic language and you don't always know everything that needs to be
339 configured when a program starts.
339 configured when a program starts.
340
340
341
341
342 .. _`XDG Base Directory`: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
342 .. _`XDG Base Directory`: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
@@ -1,1578 +1,1579 b''
1 =================
1 =================
2 IPython reference
2 IPython reference
3 =================
3 =================
4
4
5 .. warning::
5 .. warning::
6
6
7 As of the 0.11 version of IPython, some of the features and APIs
7 As of the 0.11 version of IPython, some of the features and APIs
8 described in this section have been deprecated or are broken. Our plan
8 described in this section have been deprecated or are broken. Our plan
9 is to continue to support these features, but they need to be updated
9 is to continue to support these features, but they need to be updated
10 to take advantage of recent API changes. Furthermore, this section
10 to take advantage of recent API changes. Furthermore, this section
11 of the documentation need to be updated to reflect all of these changes.
11 of the documentation need to be updated to reflect all of these changes.
12
12
13 .. _command_line_options:
13 .. _command_line_options:
14
14
15 Command-line usage
15 Command-line usage
16 ==================
16 ==================
17
17
18 You start IPython with the command::
18 You start IPython with the command::
19
19
20 $ ipython [options] files
20 $ ipython [options] files
21
21
22 If invoked with no options, it executes all the files listed in sequence
22 If invoked with no options, it executes all the files listed in sequence
23 and drops you into the interpreter while still acknowledging any options
23 and drops you into the interpreter while still acknowledging any options
24 you may have set in your ipythonrc file. This behavior is different from
24 you may have set in your ipython_config.py. This behavior is different from
25 standard Python, which when called as python -i will only execute one
25 standard Python, which when called as python -i will only execute one
26 file and ignore your configuration setup.
26 file and ignore your configuration setup.
27
27
28 Please note that some of the configuration options are not available at
28 Please note that some of the configuration options are not available at
29 the command line, simply because they are not practical here. Look into
29 the command line, simply because they are not practical here. Look into
30 your ipythonrc configuration file for details on those. This file is typically
30 your ipythonrc configuration file for details on those. This file is typically
31 installed in the IPYTHON_DIR directory. For Linux
31 installed in the IPYTHON_DIR directory. For Linux
32 users, this will be $HOME/.config/ipython, and for other users it will be
32 users, this will be $HOME/.config/ipython, and for other users it will be
33 $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and
33 $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and
34 Settings\\YourUserName in most instances.
34 Settings\\YourUserName in most instances.
35
35
36
36
37
37
38
38
39 Special Threading Options
39 Special Threading Options
40 -------------------------
40 -------------------------
41
41
42 Previously IPython had command line options for controlling GUI event loop
42 Previously IPython had command line options for controlling GUI event loop
43 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
43 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
44 version 0.11, these have been deprecated. Please see the new ``%gui``
44 version 0.11, these have been removed. Please see the new ``%gui``
45 magic command or :ref:`this section <gui_support>` for details on the new
45 magic command or :ref:`this section <gui_support>` for details on the new
46 interface.
46 interface, or specify the gui at the commandline::
47
48 $ ipython gui=qt
49
47
50
48 Regular Options
51 Regular Options
49 ---------------
52 ---------------
50
53
51 After the above threading options have been given, regular options can
54 After the above threading options have been given, regular options can
52 follow in any order. All options can be abbreviated to their shortest
55 follow in any order. All options can be abbreviated to their shortest
53 non-ambiguous form and are case-sensitive. One or two dashes can be
56 non-ambiguous form and are case-sensitive. One or two dashes can be
54 used. Some options have an alternate short form, indicated after a ``|``.
57 used. Some options have an alternate short form, indicated after a ``|``.
55
58
56 Most options can also be set from your ipythonrc configuration file. See
59 Most options can also be set from your ipythonrc configuration file. See
57 the provided example for more details on what the options do. Options
60 the provided example for more details on what the options do. Options
58 given at the command line override the values set in the ipythonrc file.
61 given at the command line override the values set in the ipythonrc file.
59
62
60 All options with a [no] prepended can be specified in negated form
63 All options with a [no] prepended can be specified in negated form
61 (-nooption instead of -option) to turn the feature off.
64 (--no-option instead of --option) to turn the feature off.
62
65
63 -help print a help message and exit.
66 -h, --help print a help message and exit.
64
67
65 -pylab
68 --pylab, pylab=<name>
66 Deprecated. See :ref:`Matplotlib support <matplotlib_support>`
69 See :ref:`Matplotlib support <matplotlib_support>`
67 for more details.
70 for more details.
68
71
69 -autocall <val>
72 autocall=<val>
70 Make IPython automatically call any callable object even if you
73 Make IPython automatically call any callable object even if you
71 didn't type explicit parentheses. For example, 'str 43' becomes
74 didn't type explicit parentheses. For example, 'str 43' becomes
72 'str(43)' automatically. The value can be '0' to disable the feature,
75 'str(43)' automatically. The value can be '0' to disable the feature,
73 '1' for smart autocall, where it is not applied if there are no more
76 '1' for smart autocall, where it is not applied if there are no more
74 arguments on the line, and '2' for full autocall, where all callable
77 arguments on the line, and '2' for full autocall, where all callable
75 objects are automatically called (even if no arguments are
78 objects are automatically called (even if no arguments are
76 present). The default is '1'.
79 present). The default is '1'.
77
80
78 -[no]autoindent
81 --[no-]autoindent
79 Turn automatic indentation on/off.
82 Turn automatic indentation on/off.
80
83
81 -[no]automagic
84 --[no-]automagic
82 make magic commands automatic (without needing their first character
85 make magic commands automatic (without needing their first character
83 to be %). Type %magic at the IPython prompt for more information.
86 to be %). Type %magic at the IPython prompt for more information.
84
87
85 -[no]autoedit_syntax
88 --[no-]autoedit_syntax
86 When a syntax error occurs after editing a file, automatically
89 When a syntax error occurs after editing a file, automatically
87 open the file to the trouble causing line for convenient
90 open the file to the trouble causing line for convenient
88 fixing.
91 fixing.
89
92
90 -[no]banner Print the initial information banner (default on).
93 --[no-]banner Print the initial information banner (default on).
91
94
92 -c <command>
95 c=<command>
93 execute the given command string. This is similar to the -c
96 execute the given command string. This is similar to the -c
94 option in the normal Python interpreter.
97 option in the normal Python interpreter.
95
98
96 -cache_size, cs <n>
99 cache_size=<n>
97 size of the output cache (maximum number of entries to hold in
100 size of the output cache (maximum number of entries to hold in
98 memory). The default is 1000, you can change it permanently in your
101 memory). The default is 1000, you can change it permanently in your
99 config file. Setting it to 0 completely disables the caching system,
102 config file. Setting it to 0 completely disables the caching system,
100 and the minimum value accepted is 20 (if you provide a value less than
103 and the minimum value accepted is 20 (if you provide a value less than
101 20, it is reset to 0 and a warning is issued) This limit is defined
104 20, it is reset to 0 and a warning is issued) This limit is defined
102 because otherwise you'll spend more time re-flushing a too small cache
105 because otherwise you'll spend more time re-flushing a too small cache
103 than working.
106 than working.
104
107
105 -classic, cl
108 --classic
106 Gives IPython a similar feel to the classic Python
109 Gives IPython a similar feel to the classic Python
107 prompt.
110 prompt.
108
111
109 -colors <scheme>
112 colors=<scheme>
110 Color scheme for prompts and exception reporting. Currently
113 Color scheme for prompts and exception reporting. Currently
111 implemented: NoColor, Linux and LightBG.
114 implemented: NoColor, Linux and LightBG.
112
115
113 -[no]color_info
116 --[no-]color_info
114 IPython can display information about objects via a set of functions,
117 IPython can display information about objects via a set of functions,
115 and optionally can use colors for this, syntax highlighting source
118 and optionally can use colors for this, syntax highlighting source
116 code and various other elements. However, because this information is
119 code and various other elements. However, because this information is
117 passed through a pager (like 'less') and many pagers get confused with
120 passed through a pager (like 'less') and many pagers get confused with
118 color codes, this option is off by default. You can test it and turn
121 color codes, this option is off by default. You can test it and turn
119 it on permanently in your ipythonrc file if it works for you. As a
122 it on permanently in your ipythonrc file if it works for you. As a
120 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
123 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
121 that in RedHat 7.2 doesn't.
124 that in RedHat 7.2 doesn't.
122
125
123 Test it and turn it on permanently if it works with your
126 Test it and turn it on permanently if it works with your
124 system. The magic function %color_info allows you to toggle this
127 system. The magic function %color_info allows you to toggle this
125 interactively for testing.
128 interactively for testing.
126
129
127 -[no]debug
130 --[no-]debug
128 Show information about the loading process. Very useful to pin down
131 Show information about the loading process. Very useful to pin down
129 problems with your configuration files or to get details about
132 problems with your configuration files or to get details about
130 session restores.
133 session restores.
131
134
132 -[no]deep_reload:
135 --[no-]deep_reload:
133 IPython can use the deep_reload module which reloads changes in
136 IPython can use the deep_reload module which reloads changes in
134 modules recursively (it replaces the reload() function, so you don't
137 modules recursively (it replaces the reload() function, so you don't
135 need to change anything to use it). deep_reload() forces a full
138 need to change anything to use it). deep_reload() forces a full
136 reload of modules whose code may have changed, which the default
139 reload of modules whose code may have changed, which the default
137 reload() function does not.
140 reload() function does not.
138
141
139 When deep_reload is off, IPython will use the normal reload(),
142 When deep_reload is off, IPython will use the normal reload(),
140 but deep_reload will still be available as dreload(). This
143 but deep_reload will still be available as dreload(). This
141 feature is off by default [which means that you have both
144 feature is off by default [which means that you have both
142 normal reload() and dreload()].
145 normal reload() and dreload()].
143
146
144 -editor <name>
147 editor=<name>
145 Which editor to use with the %edit command. By default,
148 Which editor to use with the %edit command. By default,
146 IPython will honor your EDITOR environment variable (if not
149 IPython will honor your EDITOR environment variable (if not
147 set, vi is the Unix default and notepad the Windows one).
150 set, vi is the Unix default and notepad the Windows one).
148 Since this editor is invoked on the fly by IPython and is
151 Since this editor is invoked on the fly by IPython and is
149 meant for editing small code snippets, you may want to use a
152 meant for editing small code snippets, you may want to use a
150 small, lightweight editor here (in case your default EDITOR is
153 small, lightweight editor here (in case your default EDITOR is
151 something like Emacs).
154 something like Emacs).
152
155
153 -ipythondir <name>
156 ipython_dir=<name>
154 name of your IPython configuration directory IPYTHON_DIR. This
157 name of your IPython configuration directory IPYTHON_DIR. This
155 can also be specified through the environment variable
158 can also be specified through the environment variable
156 IPYTHON_DIR.
159 IPYTHON_DIR.
157
160
158 -log, l
161 -log, l
159 generate a log file of all input. The file is named
162 generate a log file of all input. The file is named
160 ipython_log.py in your current directory (which prevents logs
163 ipython_log.py in your current directory (which prevents logs
161 from multiple IPython sessions from trampling each other). You
164 from multiple IPython sessions from trampling each other). You
162 can use this to later restore a session by loading your
165 can use this to later restore a session by loading your
163 logfile as a file to be executed with option -logplay (see
166 logfile as a file to be executed with option -logplay (see
164 below).
167 below).
165
168
166 -logfile, lf <name> specify the name of your logfile.
169 -logfile, lf <name> specify the name of your logfile.
167
170
168 -logplay, lp <name>
171 -logplay, lp <name>
169
172
170 you can replay a previous log. For restoring a session as close as
173 you can replay a previous log. For restoring a session as close as
171 possible to the state you left it in, use this option (don't just run
174 possible to the state you left it in, use this option (don't just run
172 the logfile). With -logplay, IPython will try to reconstruct the
175 the logfile). With -logplay, IPython will try to reconstruct the
173 previous working environment in full, not just execute the commands in
176 previous working environment in full, not just execute the commands in
174 the logfile.
177 the logfile.
175
178
176 When a session is restored, logging is automatically turned on
179 When a session is restored, logging is automatically turned on
177 again with the name of the logfile it was invoked with (it is
180 again with the name of the logfile it was invoked with (it is
178 read from the log header). So once you've turned logging on for
181 read from the log header). So once you've turned logging on for
179 a session, you can quit IPython and reload it as many times as
182 a session, you can quit IPython and reload it as many times as
180 you want and it will continue to log its history and restore
183 you want and it will continue to log its history and restore
181 from the beginning every time.
184 from the beginning every time.
182
185
183 Caveats: there are limitations in this option. The history
186 Caveats: there are limitations in this option. The history
184 variables _i*,_* and _dh don't get restored properly. In the
187 variables _i*,_* and _dh don't get restored properly. In the
185 future we will try to implement full session saving by writing
188 future we will try to implement full session saving by writing
186 and retrieving a 'snapshot' of the memory state of IPython. But
189 and retrieving a 'snapshot' of the memory state of IPython. But
187 our first attempts failed because of inherent limitations of
190 our first attempts failed because of inherent limitations of
188 Python's Pickle module, so this may have to wait.
191 Python's Pickle module, so this may have to wait.
189
192
190 -[no]messages
193 --[no-]messages
191 Print messages which IPython collects about its startup
194 Print messages which IPython collects about its startup
192 process (default on).
195 process (default on).
193
196
194 -[no]pdb
197 --[no-]pdb
195 Automatically call the pdb debugger after every uncaught
198 Automatically call the pdb debugger after every uncaught
196 exception. If you are used to debugging using pdb, this puts
199 exception. If you are used to debugging using pdb, this puts
197 you automatically inside of it after any call (either in
200 you automatically inside of it after any call (either in
198 IPython or in code called by it) which triggers an exception
201 IPython or in code called by it) which triggers an exception
199 which goes uncaught.
202 which goes uncaught.
200
203
201 -pydb
204 --pydb
202 Makes IPython use the third party "pydb" package as debugger,
205 Makes IPython use the third party "pydb" package as debugger,
203 instead of pdb. Requires that pydb is installed.
206 instead of pdb. Requires that pydb is installed.
204
207
205 -[no]pprint
208 --[no-]pprint
206 ipython can optionally use the pprint (pretty printer) module
209 ipython can optionally use the pprint (pretty printer) module
207 for displaying results. pprint tends to give a nicer display
210 for displaying results. pprint tends to give a nicer display
208 of nested data structures. If you like it, you can turn it on
211 of nested data structures. If you like it, you can turn it on
209 permanently in your config file (default off).
212 permanently in your config file (default off).
210
213
211 -profile, p <name>
214 profile=<name>
212
215
213 assume that your config file is ipythonrc-<name> or
216 assume that your config file is ipythonrc-<name> or
214 ipy_profile_<name>.py (looks in current dir first, then in
217 ipy_profile_<name>.py (looks in current dir first, then in
215 IPYTHON_DIR). This is a quick way to keep and load multiple
218 IPYTHON_DIR). This is a quick way to keep and load multiple
216 config files for different tasks, especially if you use the
219 config files for different tasks, especially if you use the
217 include option of config files. You can keep a basic
220 include option of config files. You can keep a basic
218 IPYTHON_DIR/ipythonrc file and then have other 'profiles' which
221 IPYTHON_DIR/ipythonrc file and then have other 'profiles' which
219 include this one and load extra things for particular
222 include this one and load extra things for particular
220 tasks. For example:
223 tasks. For example:
221
224
222 1. $IPYTHON_DIR/ipythonrc : load basic things you always want.
225 1. $IPYTHON_DIR/ipythonrc : load basic things you always want.
223 2. $IPYTHON_DIR/ipythonrc-math : load (1) and basic math-related modules.
226 2. $IPYTHON_DIR/ipythonrc-math : load (1) and basic math-related modules.
224 3. $IPYTHON_DIR/ipythonrc-numeric : load (1) and Numeric and plotting modules.
227 3. $IPYTHON_DIR/ipythonrc-numeric : load (1) and Numeric and plotting modules.
225
228
226 Since it is possible to create an endless loop by having
229 Since it is possible to create an endless loop by having
227 circular file inclusions, IPython will stop if it reaches 15
230 circular file inclusions, IPython will stop if it reaches 15
228 recursive inclusions.
231 recursive inclusions.
229
232
230 -prompt_in1, pi1 <string>
233 pi1=<string>
231
234
232 Specify the string used for input prompts. Note that if you are using
235 Specify the string used for input prompts. Note that if you are using
233 numbered prompts, the number is represented with a '\#' in the
236 numbered prompts, the number is represented with a '\#' in the
234 string. Don't forget to quote strings with spaces embedded in
237 string. Don't forget to quote strings with spaces embedded in
235 them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>`
238 them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>`
236 discusses in detail all the available escapes to customize your
239 discusses in detail all the available escapes to customize your
237 prompts.
240 prompts.
238
241
239 -prompt_in2, pi2 <string>
242 pi2=<string>
240 Similar to the previous option, but used for the continuation
243 Similar to the previous option, but used for the continuation
241 prompts. The special sequence '\D' is similar to '\#', but
244 prompts. The special sequence '\D' is similar to '\#', but
242 with all digits replaced dots (so you can have your
245 with all digits replaced dots (so you can have your
243 continuation prompt aligned with your input prompt). Default:
246 continuation prompt aligned with your input prompt). Default:
244 ' .\D.:' (note three spaces at the start for alignment with
247 ' .\D.:' (note three spaces at the start for alignment with
245 'In [\#]').
248 'In [\#]').
246
249
247 -prompt_out,po <string>
250 po=<string>
248 String used for output prompts, also uses numbers like
251 String used for output prompts, also uses numbers like
249 prompt_in1. Default: 'Out[\#]:'
252 prompt_in1. Default: 'Out[\#]:'
250
253
251 -quick start in bare bones mode (no config file loaded).
254 --quick
255 start in bare bones mode (no config file loaded).
252
256
253 -rcfile <name>
257 config_file=<name>
254 name of your IPython resource configuration file. Normally
258 name of your IPython resource configuration file. Normally
255 IPython loads ipythonrc (from current directory) or
259 IPython loads ipython_config.py (from current directory) or
256 IPYTHON_DIR/ipythonrc.
260 IPYTHON_DIR/profile_default.
257
261
258 If the loading of your config file fails, IPython starts with
262 If the loading of your config file fails, IPython starts with
259 a bare bones configuration (no modules loaded at all).
263 a bare bones configuration (no modules loaded at all).
260
264
261 -[no]readline
265 --[no-]readline
262 use the readline library, which is needed to support name
266 use the readline library, which is needed to support name
263 completion and command history, among other things. It is
267 completion and command history, among other things. It is
264 enabled by default, but may cause problems for users of
268 enabled by default, but may cause problems for users of
265 X/Emacs in Python comint or shell buffers.
269 X/Emacs in Python comint or shell buffers.
266
270
267 Note that X/Emacs 'eterm' buffers (opened with M-x term) support
271 Note that X/Emacs 'eterm' buffers (opened with M-x term) support
268 IPython's readline and syntax coloring fine, only 'emacs' (M-x
272 IPython's readline and syntax coloring fine, only 'emacs' (M-x
269 shell and C-c !) buffers do not.
273 shell and C-c !) buffers do not.
270
274
271 -screen_length, sl <n>
275 sl=<n>
272 number of lines of your screen. This is used to control
276 number of lines of your screen. This is used to control
273 printing of very long strings. Strings longer than this number
277 printing of very long strings. Strings longer than this number
274 of lines will be sent through a pager instead of directly
278 of lines will be sent through a pager instead of directly
275 printed.
279 printed.
276
280
277 The default value for this is 0, which means IPython will
281 The default value for this is 0, which means IPython will
278 auto-detect your screen size every time it needs to print certain
282 auto-detect your screen size every time it needs to print certain
279 potentially long strings (this doesn't change the behavior of the
283 potentially long strings (this doesn't change the behavior of the
280 'print' keyword, it's only triggered internally). If for some
284 'print' keyword, it's only triggered internally). If for some
281 reason this isn't working well (it needs curses support), specify
285 reason this isn't working well (it needs curses support), specify
282 it yourself. Otherwise don't change the default.
286 it yourself. Otherwise don't change the default.
283
287
284 -separate_in, si <string>
288 si=<string>
285
289
286 separator before input prompts.
290 separator before input prompts.
287 Default: '\n'
291 Default: '\n'
288
292
289 -separate_out, so <string>
293 so=<string>
290 separator before output prompts.
294 separator before output prompts.
291 Default: nothing.
295 Default: nothing.
292
296
293 -separate_out2, so2
297 so2=<string>
294 separator after output prompts.
298 separator after output prompts.
295 Default: nothing.
299 Default: nothing.
296 For these three options, use the value 0 to specify no separator.
300 For these three options, use the value 0 to specify no separator.
297
301
298 -nosep
302 --nosep
299 shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2
303 shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2
300 0'. Simply removes all input/output separators.
304 0'. Simply removes all input/output separators.
301
305
302 -upgrade
306 --init
303 allows you to upgrade your IPYTHON_DIR configuration when you
307 allows you to initialize your IPYTHON_DIR configuration when you
304 install a new version of IPython. Since new versions may
308 install a new version of IPython. Since new versions may
305 include new command line options or example files, this copies
309 include new command line options or example files, this copies
306 updated ipythonrc-type files. However, it backs up (with a
310 updated config files. However, it backs up (with a
307 .old extension) all files which it overwrites so that you can
311 .old extension) all files which it overwrites so that you can
308 merge back any customizations you might have in your personal
312 merge back any customizations you might have in your personal
309 files. Note that you should probably use %upgrade instead,
313 files. Note that you should probably use %upgrade instead,
310 it's a safer alternative.
314 it's a safer alternative.
311
315
312
316
313 -Version print version information and exit.
317 --version print version information and exit.
314
315 -wxversion <string>
316 Deprecated.
317
318
318 -xmode <modename>
319 xmode=<modename>
319
320
320 Mode for exception reporting.
321 Mode for exception reporting.
321
322
322 Valid modes: Plain, Context and Verbose.
323 Valid modes: Plain, Context and Verbose.
323
324
324 * Plain: similar to python's normal traceback printing.
325 * Plain: similar to python's normal traceback printing.
325 * Context: prints 5 lines of context source code around each
326 * Context: prints 5 lines of context source code around each
326 line in the traceback.
327 line in the traceback.
327 * Verbose: similar to Context, but additionally prints the
328 * Verbose: similar to Context, but additionally prints the
328 variables currently visible where the exception happened
329 variables currently visible where the exception happened
329 (shortening their strings if too long). This can potentially be
330 (shortening their strings if too long). This can potentially be
330 very slow, if you happen to have a huge data structure whose
331 very slow, if you happen to have a huge data structure whose
331 string representation is complex to compute. Your computer may
332 string representation is complex to compute. Your computer may
332 appear to freeze for a while with cpu usage at 100%. If this
333 appear to freeze for a while with cpu usage at 100%. If this
333 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
334 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
334 more than once).
335 more than once).
335
336
336 Interactive use
337 Interactive use
337 ===============
338 ===============
338
339
339 Warning: IPython relies on the existence of a global variable called
340 Warning: IPython relies on the existence of a global variable called
340 _ip which controls the shell itself. If you redefine _ip to anything,
341 _ip which controls the shell itself. If you redefine _ip to anything,
341 bizarre behavior will quickly occur.
342 bizarre behavior will quickly occur.
342
343
343 Other than the above warning, IPython is meant to work as a drop-in
344 Other than the above warning, IPython is meant to work as a drop-in
344 replacement for the standard interactive interpreter. As such, any code
345 replacement for the standard interactive interpreter. As such, any code
345 which is valid python should execute normally under IPython (cases where
346 which is valid python should execute normally under IPython (cases where
346 this is not true should be reported as bugs). It does, however, offer
347 this is not true should be reported as bugs). It does, however, offer
347 many features which are not available at a standard python prompt. What
348 many features which are not available at a standard python prompt. What
348 follows is a list of these.
349 follows is a list of these.
349
350
350
351
351 Caution for Windows users
352 Caution for Windows users
352 -------------------------
353 -------------------------
353
354
354 Windows, unfortunately, uses the '\' character as a path
355 Windows, unfortunately, uses the '\' character as a path
355 separator. This is a terrible choice, because '\' also represents the
356 separator. This is a terrible choice, because '\' also represents the
356 escape character in most modern programming languages, including
357 escape character in most modern programming languages, including
357 Python. For this reason, using '/' character is recommended if you
358 Python. For this reason, using '/' character is recommended if you
358 have problems with ``\``. However, in Windows commands '/' flags
359 have problems with ``\``. However, in Windows commands '/' flags
359 options, so you can not use it for the root directory. This means that
360 options, so you can not use it for the root directory. This means that
360 paths beginning at the root must be typed in a contrived manner like:
361 paths beginning at the root must be typed in a contrived manner like:
361 ``%copy \opt/foo/bar.txt \tmp``
362 ``%copy \opt/foo/bar.txt \tmp``
362
363
363 .. _magic:
364 .. _magic:
364
365
365 Magic command system
366 Magic command system
366 --------------------
367 --------------------
367
368
368 IPython will treat any line whose first character is a % as a special
369 IPython will treat any line whose first character is a % as a special
369 call to a 'magic' function. These allow you to control the behavior of
370 call to a 'magic' function. These allow you to control the behavior of
370 IPython itself, plus a lot of system-type features. They are all
371 IPython itself, plus a lot of system-type features. They are all
371 prefixed with a % character, but parameters are given without
372 prefixed with a % character, but parameters are given without
372 parentheses or quotes.
373 parentheses or quotes.
373
374
374 Example: typing '%cd mydir' (without the quotes) changes you working
375 Example: typing '%cd mydir' (without the quotes) changes you working
375 directory to 'mydir', if it exists.
376 directory to 'mydir', if it exists.
376
377
377 If you have 'automagic' enabled (in your ipythonrc file, via the command
378 If you have 'automagic' enabled (in your ipythonrc file, via the command
378 line option -automagic or with the %automagic function), you don't need
379 line option -automagic or with the %automagic function), you don't need
379 to type in the % explicitly. IPython will scan its internal list of
380 to type in the % explicitly. IPython will scan its internal list of
380 magic functions and call one if it exists. With automagic on you can
381 magic functions and call one if it exists. With automagic on you can
381 then just type 'cd mydir' to go to directory 'mydir'. The automagic
382 then just type 'cd mydir' to go to directory 'mydir'. The automagic
382 system has the lowest possible precedence in name searches, so defining
383 system has the lowest possible precedence in name searches, so defining
383 an identifier with the same name as an existing magic function will
384 an identifier with the same name as an existing magic function will
384 shadow it for automagic use. You can still access the shadowed magic
385 shadow it for automagic use. You can still access the shadowed magic
385 function by explicitly using the % character at the beginning of the line.
386 function by explicitly using the % character at the beginning of the line.
386
387
387 An example (with automagic on) should clarify all this::
388 An example (with automagic on) should clarify all this::
388
389
389 In [1]: cd ipython # %cd is called by automagic
390 In [1]: cd ipython # %cd is called by automagic
390
391
391 /home/fperez/ipython
392 /home/fperez/ipython
392
393
393 In [2]: cd=1 # now cd is just a variable
394 In [2]: cd=1 # now cd is just a variable
394
395
395 In [3]: cd .. # and doesn't work as a function anymore
396 In [3]: cd .. # and doesn't work as a function anymore
396
397
397 ------------------------------
398 ------------------------------
398
399
399 File "<console>", line 1
400 File "<console>", line 1
400
401
401 cd ..
402 cd ..
402
403
403 ^
404 ^
404
405
405 SyntaxError: invalid syntax
406 SyntaxError: invalid syntax
406
407
407 In [4]: %cd .. # but %cd always works
408 In [4]: %cd .. # but %cd always works
408
409
409 /home/fperez
410 /home/fperez
410
411
411 In [5]: del cd # if you remove the cd variable
412 In [5]: del cd # if you remove the cd variable
412
413
413 In [6]: cd ipython # automagic can work again
414 In [6]: cd ipython # automagic can work again
414
415
415 /home/fperez/ipython
416 /home/fperez/ipython
416
417
417 You can define your own magic functions to extend the system. The
418 You can define your own magic functions to extend the system. The
418 following example defines a new magic command, %impall::
419 following example defines a new magic command, %impall::
419
420
420 import IPython.ipapi
421 import IPython.ipapi
421
422
422 ip = IPython.ipapi.get()
423 ip = IPython.ipapi.get()
423
424
424 def doimp(self, arg):
425 def doimp(self, arg):
425
426
426 ip = self.api
427 ip = self.api
427
428
428 ip.ex("import %s; reload(%s); from %s import *" % (
429 ip.ex("import %s; reload(%s); from %s import *" % (
429
430
430 arg,arg,arg)
431 arg,arg,arg)
431
432
432 )
433 )
433
434
434 ip.expose_magic('impall', doimp)
435 ip.expose_magic('impall', doimp)
435
436
436 You can also define your own aliased names for magic functions. In your
437 You can also define your own aliased names for magic functions. In your
437 ipythonrc file, placing a line like::
438 ipythonrc file, placing a line like::
438
439
439 execute __IP.magic_cl = __IP.magic_clear
440 execute __IP.magic_cl = __IP.magic_clear
440
441
441 will define %cl as a new name for %clear.
442 will define %cl as a new name for %clear.
442
443
443 Type %magic for more information, including a list of all available
444 Type %magic for more information, including a list of all available
444 magic functions at any time and their docstrings. You can also type
445 magic functions at any time and their docstrings. You can also type
445 %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for
446 %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for
446 information on the '?' system) to get information about any particular
447 information on the '?' system) to get information about any particular
447 magic function you are interested in.
448 magic function you are interested in.
448
449
449 The API documentation for the :mod:`IPython.Magic` module contains the full
450 The API documentation for the :mod:`IPython.Magic` module contains the full
450 docstrings of all currently available magic commands.
451 docstrings of all currently available magic commands.
451
452
452
453
453 Access to the standard Python help
454 Access to the standard Python help
454 ----------------------------------
455 ----------------------------------
455
456
456 As of Python 2.1, a help system is available with access to object docstrings
457 As of Python 2.1, a help system is available with access to object docstrings
457 and the Python manuals. Simply type 'help' (no quotes) to access it. You can
458 and the Python manuals. Simply type 'help' (no quotes) to access it. You can
458 also type help(object) to obtain information about a given object, and
459 also type help(object) to obtain information about a given object, and
459 help('keyword') for information on a keyword. As noted :ref:`here
460 help('keyword') for information on a keyword. As noted :ref:`here
460 <accessing_help>`, you need to properly configure your environment variable
461 <accessing_help>`, you need to properly configure your environment variable
461 PYTHONDOCS for this feature to work correctly.
462 PYTHONDOCS for this feature to work correctly.
462
463
463 .. _dynamic_object_info:
464 .. _dynamic_object_info:
464
465
465 Dynamic object information
466 Dynamic object information
466 --------------------------
467 --------------------------
467
468
468 Typing ?word or word? prints detailed information about an object. If
469 Typing ?word or word? prints detailed information about an object. If
469 certain strings in the object are too long (docstrings, code, etc.) they
470 certain strings in the object are too long (docstrings, code, etc.) they
470 get snipped in the center for brevity. This system gives access variable
471 get snipped in the center for brevity. This system gives access variable
471 types and values, full source code for any object (if available),
472 types and values, full source code for any object (if available),
472 function prototypes and other useful information.
473 function prototypes and other useful information.
473
474
474 Typing ??word or word?? gives access to the full information without
475 Typing ??word or word?? gives access to the full information without
475 snipping long strings. Long strings are sent to the screen through the
476 snipping long strings. Long strings are sent to the screen through the
476 less pager if longer than the screen and printed otherwise. On systems
477 less pager if longer than the screen and printed otherwise. On systems
477 lacking the less command, IPython uses a very basic internal pager.
478 lacking the less command, IPython uses a very basic internal pager.
478
479
479 The following magic functions are particularly useful for gathering
480 The following magic functions are particularly useful for gathering
480 information about your working environment. You can get more details by
481 information about your working environment. You can get more details by
481 typing %magic or querying them individually (use %function_name? with or
482 typing %magic or querying them individually (use %function_name? with or
482 without the %), this is just a summary:
483 without the %), this is just a summary:
483
484
484 * **%pdoc <object>**: Print (or run through a pager if too long) the
485 * **%pdoc <object>**: Print (or run through a pager if too long) the
485 docstring for an object. If the given object is a class, it will
486 docstring for an object. If the given object is a class, it will
486 print both the class and the constructor docstrings.
487 print both the class and the constructor docstrings.
487 * **%pdef <object>**: Print the definition header for any callable
488 * **%pdef <object>**: Print the definition header for any callable
488 object. If the object is a class, print the constructor information.
489 object. If the object is a class, print the constructor information.
489 * **%psource <object>**: Print (or run through a pager if too long)
490 * **%psource <object>**: Print (or run through a pager if too long)
490 the source code for an object.
491 the source code for an object.
491 * **%pfile <object>**: Show the entire source file where an object was
492 * **%pfile <object>**: Show the entire source file where an object was
492 defined via a pager, opening it at the line where the object
493 defined via a pager, opening it at the line where the object
493 definition begins.
494 definition begins.
494 * **%who/%whos**: These functions give information about identifiers
495 * **%who/%whos**: These functions give information about identifiers
495 you have defined interactively (not things you loaded or defined
496 you have defined interactively (not things you loaded or defined
496 in your configuration files). %who just prints a list of
497 in your configuration files). %who just prints a list of
497 identifiers and %whos prints a table with some basic details about
498 identifiers and %whos prints a table with some basic details about
498 each identifier.
499 each identifier.
499
500
500 Note that the dynamic object information functions (?/??, %pdoc, %pfile,
501 Note that the dynamic object information functions (?/??, %pdoc, %pfile,
501 %pdef, %psource) give you access to documentation even on things which
502 %pdef, %psource) give you access to documentation even on things which
502 are not really defined as separate identifiers. Try for example typing
503 are not really defined as separate identifiers. Try for example typing
503 {}.get? or after doing import os, type os.path.abspath??.
504 {}.get? or after doing import os, type os.path.abspath??.
504
505
505
506
506 .. _readline:
507 .. _readline:
507
508
508 Readline-based features
509 Readline-based features
509 -----------------------
510 -----------------------
510
511
511 These features require the GNU readline library, so they won't work if
512 These features require the GNU readline library, so they won't work if
512 your Python installation lacks readline support. We will first describe
513 your Python installation lacks readline support. We will first describe
513 the default behavior IPython uses, and then how to change it to suit
514 the default behavior IPython uses, and then how to change it to suit
514 your preferences.
515 your preferences.
515
516
516
517
517 Command line completion
518 Command line completion
518 +++++++++++++++++++++++
519 +++++++++++++++++++++++
519
520
520 At any time, hitting TAB will complete any available python commands or
521 At any time, hitting TAB will complete any available python commands or
521 variable names, and show you a list of the possible completions if
522 variable names, and show you a list of the possible completions if
522 there's no unambiguous one. It will also complete filenames in the
523 there's no unambiguous one. It will also complete filenames in the
523 current directory if no python names match what you've typed so far.
524 current directory if no python names match what you've typed so far.
524
525
525
526
526 Search command history
527 Search command history
527 ++++++++++++++++++++++
528 ++++++++++++++++++++++
528
529
529 IPython provides two ways for searching through previous input and thus
530 IPython provides two ways for searching through previous input and thus
530 reduce the need for repetitive typing:
531 reduce the need for repetitive typing:
531
532
532 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
533 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
533 (next,down) to search through only the history items that match
534 (next,down) to search through only the history items that match
534 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
535 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
535 prompt, they just behave like normal arrow keys.
536 prompt, they just behave like normal arrow keys.
536 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
537 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
537 searches your history for lines that contain what you've typed so
538 searches your history for lines that contain what you've typed so
538 far, completing as much as it can.
539 far, completing as much as it can.
539
540
540
541
541 Persistent command history across sessions
542 Persistent command history across sessions
542 ++++++++++++++++++++++++++++++++++++++++++
543 ++++++++++++++++++++++++++++++++++++++++++
543
544
544 IPython will save your input history when it leaves and reload it next
545 IPython will save your input history when it leaves and reload it next
545 time you restart it. By default, the history file is named
546 time you restart it. By default, the history file is named
546 $IPYTHON_DIR/history, but if you've loaded a named profile,
547 $IPYTHON_DIR/history, but if you've loaded a named profile,
547 '-PROFILE_NAME' is appended to the name. This allows you to keep
548 '-PROFILE_NAME' is appended to the name. This allows you to keep
548 separate histories related to various tasks: commands related to
549 separate histories related to various tasks: commands related to
549 numerical work will not be clobbered by a system shell history, for
550 numerical work will not be clobbered by a system shell history, for
550 example.
551 example.
551
552
552
553
553 Autoindent
554 Autoindent
554 ++++++++++
555 ++++++++++
555
556
556 IPython can recognize lines ending in ':' and indent the next line,
557 IPython can recognize lines ending in ':' and indent the next line,
557 while also un-indenting automatically after 'raise' or 'return'.
558 while also un-indenting automatically after 'raise' or 'return'.
558
559
559 This feature uses the readline library, so it will honor your ~/.inputrc
560 This feature uses the readline library, so it will honor your ~/.inputrc
560 configuration (or whatever file your INPUTRC variable points to). Adding
561 configuration (or whatever file your INPUTRC variable points to). Adding
561 the following lines to your .inputrc file can make indenting/unindenting
562 the following lines to your .inputrc file can make indenting/unindenting
562 more convenient (M-i indents, M-u unindents)::
563 more convenient (M-i indents, M-u unindents)::
563
564
564 $if Python
565 $if Python
565 "\M-i": " "
566 "\M-i": " "
566 "\M-u": "\d\d\d\d"
567 "\M-u": "\d\d\d\d"
567 $endif
568 $endif
568
569
569 Note that there are 4 spaces between the quote marks after "M-i" above.
570 Note that there are 4 spaces between the quote marks after "M-i" above.
570
571
571 Warning: this feature is ON by default, but it can cause problems with
572 Warning: this feature is ON by default, but it can cause problems with
572 the pasting of multi-line indented code (the pasted code gets
573 the pasting of multi-line indented code (the pasted code gets
573 re-indented on each line). A magic function %autoindent allows you to
574 re-indented on each line). A magic function %autoindent allows you to
574 toggle it on/off at runtime. You can also disable it permanently on in
575 toggle it on/off at runtime. You can also disable it permanently on in
575 your ipythonrc file (set autoindent 0).
576 your ipythonrc file (set autoindent 0).
576
577
577
578
578 Customizing readline behavior
579 Customizing readline behavior
579 +++++++++++++++++++++++++++++
580 +++++++++++++++++++++++++++++
580
581
581 All these features are based on the GNU readline library, which has an
582 All these features are based on the GNU readline library, which has an
582 extremely customizable interface. Normally, readline is configured via a
583 extremely customizable interface. Normally, readline is configured via a
583 file which defines the behavior of the library; the details of the
584 file which defines the behavior of the library; the details of the
584 syntax for this can be found in the readline documentation available
585 syntax for this can be found in the readline documentation available
585 with your system or on the Internet. IPython doesn't read this file (if
586 with your system or on the Internet. IPython doesn't read this file (if
586 it exists) directly, but it does support passing to readline valid
587 it exists) directly, but it does support passing to readline valid
587 options via a simple interface. In brief, you can customize readline by
588 options via a simple interface. In brief, you can customize readline by
588 setting the following options in your ipythonrc configuration file (note
589 setting the following options in your ipythonrc configuration file (note
589 that these options can not be specified at the command line):
590 that these options can not be specified at the command line):
590
591
591 * **readline_parse_and_bind**: this option can appear as many times as
592 * **readline_parse_and_bind**: this option can appear as many times as
592 you want, each time defining a string to be executed via a
593 you want, each time defining a string to be executed via a
593 readline.parse_and_bind() command. The syntax for valid commands
594 readline.parse_and_bind() command. The syntax for valid commands
594 of this kind can be found by reading the documentation for the GNU
595 of this kind can be found by reading the documentation for the GNU
595 readline library, as these commands are of the kind which readline
596 readline library, as these commands are of the kind which readline
596 accepts in its configuration file.
597 accepts in its configuration file.
597 * **readline_remove_delims**: a string of characters to be removed
598 * **readline_remove_delims**: a string of characters to be removed
598 from the default word-delimiters list used by readline, so that
599 from the default word-delimiters list used by readline, so that
599 completions may be performed on strings which contain them. Do not
600 completions may be performed on strings which contain them. Do not
600 change the default value unless you know what you're doing.
601 change the default value unless you know what you're doing.
601 * **readline_omit__names**: when tab-completion is enabled, hitting
602 * **readline_omit__names**: when tab-completion is enabled, hitting
602 <tab> after a '.' in a name will complete all attributes of an
603 <tab> after a '.' in a name will complete all attributes of an
603 object, including all the special methods whose names include
604 object, including all the special methods whose names include
604 double underscores (like __getitem__ or __class__). If you'd
605 double underscores (like __getitem__ or __class__). If you'd
605 rather not see these names by default, you can set this option to
606 rather not see these names by default, you can set this option to
606 1. Note that even when this option is set, you can still see those
607 1. Note that even when this option is set, you can still see those
607 names by explicitly typing a _ after the period and hitting <tab>:
608 names by explicitly typing a _ after the period and hitting <tab>:
608 'name._<tab>' will always complete attribute names starting with '_'.
609 'name._<tab>' will always complete attribute names starting with '_'.
609
610
610 This option is off by default so that new users see all
611 This option is off by default so that new users see all
611 attributes of any objects they are dealing with.
612 attributes of any objects they are dealing with.
612
613
613 You will find the default values along with a corresponding detailed
614 You will find the default values along with a corresponding detailed
614 explanation in your ipythonrc file.
615 explanation in your ipythonrc file.
615
616
616
617
617 Session logging and restoring
618 Session logging and restoring
618 -----------------------------
619 -----------------------------
619
620
620 You can log all input from a session either by starting IPython with the
621 You can log all input from a session either by starting IPython with the
621 command line switches -log or -logfile (see :ref:`here <command_line_options>`)
622 command line switches -log or -logfile (see :ref:`here <command_line_options>`)
622 or by activating the logging at any moment with the magic function %logstart.
623 or by activating the logging at any moment with the magic function %logstart.
623
624
624 Log files can later be reloaded with the -logplay option and IPython
625 Log files can later be reloaded with the -logplay option and IPython
625 will attempt to 'replay' the log by executing all the lines in it, thus
626 will attempt to 'replay' the log by executing all the lines in it, thus
626 restoring the state of a previous session. This feature is not quite
627 restoring the state of a previous session. This feature is not quite
627 perfect, but can still be useful in many cases.
628 perfect, but can still be useful in many cases.
628
629
629 The log files can also be used as a way to have a permanent record of
630 The log files can also be used as a way to have a permanent record of
630 any code you wrote while experimenting. Log files are regular text files
631 any code you wrote while experimenting. Log files are regular text files
631 which you can later open in your favorite text editor to extract code or
632 which you can later open in your favorite text editor to extract code or
632 to 'clean them up' before using them to replay a session.
633 to 'clean them up' before using them to replay a session.
633
634
634 The %logstart function for activating logging in mid-session is used as
635 The %logstart function for activating logging in mid-session is used as
635 follows:
636 follows:
636
637
637 %logstart [log_name [log_mode]]
638 %logstart [log_name [log_mode]]
638
639
639 If no name is given, it defaults to a file named 'log' in your
640 If no name is given, it defaults to a file named 'log' in your
640 IPYTHON_DIR directory, in 'rotate' mode (see below).
641 IPYTHON_DIR directory, in 'rotate' mode (see below).
641
642
642 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
643 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
643 history up to that point and then continues logging.
644 history up to that point and then continues logging.
644
645
645 %logstart takes a second optional parameter: logging mode. This can be
646 %logstart takes a second optional parameter: logging mode. This can be
646 one of (note that the modes are given unquoted):
647 one of (note that the modes are given unquoted):
647
648
648 * [over:] overwrite existing log_name.
649 * [over:] overwrite existing log_name.
649 * [backup:] rename (if exists) to log_name~ and start log_name.
650 * [backup:] rename (if exists) to log_name~ and start log_name.
650 * [append:] well, that says it.
651 * [append:] well, that says it.
651 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
652 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
652
653
653 The %logoff and %logon functions allow you to temporarily stop and
654 The %logoff and %logon functions allow you to temporarily stop and
654 resume logging to a file which had previously been started with
655 resume logging to a file which had previously been started with
655 %logstart. They will fail (with an explanation) if you try to use them
656 %logstart. They will fail (with an explanation) if you try to use them
656 before logging has been started.
657 before logging has been started.
657
658
658 .. _system_shell_access:
659 .. _system_shell_access:
659
660
660 System shell access
661 System shell access
661 -------------------
662 -------------------
662
663
663 Any input line beginning with a ! character is passed verbatim (minus
664 Any input line beginning with a ! character is passed verbatim (minus
664 the !, of course) to the underlying operating system. For example,
665 the !, of course) to the underlying operating system. For example,
665 typing !ls will run 'ls' in the current directory.
666 typing !ls will run 'ls' in the current directory.
666
667
667 Manual capture of command output
668 Manual capture of command output
668 --------------------------------
669 --------------------------------
669
670
670 If the input line begins with two exclamation marks, !!, the command is
671 If the input line begins with two exclamation marks, !!, the command is
671 executed but its output is captured and returned as a python list, split
672 executed but its output is captured and returned as a python list, split
672 on newlines. Any output sent by the subprocess to standard error is
673 on newlines. Any output sent by the subprocess to standard error is
673 printed separately, so that the resulting list only captures standard
674 printed separately, so that the resulting list only captures standard
674 output. The !! syntax is a shorthand for the %sx magic command.
675 output. The !! syntax is a shorthand for the %sx magic command.
675
676
676 Finally, the %sc magic (short for 'shell capture') is similar to %sx,
677 Finally, the %sc magic (short for 'shell capture') is similar to %sx,
677 but allowing more fine-grained control of the capture details, and
678 but allowing more fine-grained control of the capture details, and
678 storing the result directly into a named variable. The direct use of
679 storing the result directly into a named variable. The direct use of
679 %sc is now deprecated, and you should ise the ``var = !cmd`` syntax
680 %sc is now deprecated, and you should ise the ``var = !cmd`` syntax
680 instead.
681 instead.
681
682
682 IPython also allows you to expand the value of python variables when
683 IPython also allows you to expand the value of python variables when
683 making system calls. Any python variable or expression which you prepend
684 making system calls. Any python variable or expression which you prepend
684 with $ will get expanded before the system call is made::
685 with $ will get expanded before the system call is made::
685
686
686 In [1]: pyvar='Hello world'
687 In [1]: pyvar='Hello world'
687 In [2]: !echo "A python variable: $pyvar"
688 In [2]: !echo "A python variable: $pyvar"
688 A python variable: Hello world
689 A python variable: Hello world
689
690
690 If you want the shell to actually see a literal $, you need to type it
691 If you want the shell to actually see a literal $, you need to type it
691 twice::
692 twice::
692
693
693 In [3]: !echo "A system variable: $$HOME"
694 In [3]: !echo "A system variable: $$HOME"
694 A system variable: /home/fperez
695 A system variable: /home/fperez
695
696
696 You can pass arbitrary expressions, though you'll need to delimit them
697 You can pass arbitrary expressions, though you'll need to delimit them
697 with {} if there is ambiguity as to the extent of the expression::
698 with {} if there is ambiguity as to the extent of the expression::
698
699
699 In [5]: x=10
700 In [5]: x=10
700 In [6]: y=20
701 In [6]: y=20
701 In [13]: !echo $x+y
702 In [13]: !echo $x+y
702 10+y
703 10+y
703 In [7]: !echo ${x+y}
704 In [7]: !echo ${x+y}
704 30
705 30
705
706
706 Even object attributes can be expanded::
707 Even object attributes can be expanded::
707
708
708 In [12]: !echo $sys.argv
709 In [12]: !echo $sys.argv
709 [/home/fperez/usr/bin/ipython]
710 [/home/fperez/usr/bin/ipython]
710
711
711
712
712 System command aliases
713 System command aliases
713 ----------------------
714 ----------------------
714
715
715 The %alias magic function and the alias option in the ipythonrc
716 The %alias magic function and the alias option in the ipythonrc
716 configuration file allow you to define magic functions which are in fact
717 configuration file allow you to define magic functions which are in fact
717 system shell commands. These aliases can have parameters.
718 system shell commands. These aliases can have parameters.
718
719
719 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
720 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
720
721
721 Then, typing '%alias_name params' will execute the system command 'cmd
722 Then, typing '%alias_name params' will execute the system command 'cmd
722 params' (from your underlying operating system).
723 params' (from your underlying operating system).
723
724
724 You can also define aliases with parameters using %s specifiers (one per
725 You can also define aliases with parameters using %s specifiers (one per
725 parameter). The following example defines the %parts function as an
726 parameter). The following example defines the %parts function as an
726 alias to the command 'echo first %s second %s' where each %s will be
727 alias to the command 'echo first %s second %s' where each %s will be
727 replaced by a positional parameter to the call to %parts::
728 replaced by a positional parameter to the call to %parts::
728
729
729 In [1]: alias parts echo first %s second %s
730 In [1]: alias parts echo first %s second %s
730 In [2]: %parts A B
731 In [2]: %parts A B
731 first A second B
732 first A second B
732 In [3]: %parts A
733 In [3]: %parts A
733 Incorrect number of arguments: 2 expected.
734 Incorrect number of arguments: 2 expected.
734 parts is an alias to: 'echo first %s second %s'
735 parts is an alias to: 'echo first %s second %s'
735
736
736 If called with no parameters, %alias prints the table of currently
737 If called with no parameters, %alias prints the table of currently
737 defined aliases.
738 defined aliases.
738
739
739 The %rehash/rehashx magics allow you to load your entire $PATH as
740 The %rehash/rehashx magics allow you to load your entire $PATH as
740 ipython aliases. See their respective docstrings (or sec. 6.2
741 ipython aliases. See their respective docstrings (or sec. 6.2
741 <#sec:magic> for further details).
742 <#sec:magic> for further details).
742
743
743
744
744 .. _dreload:
745 .. _dreload:
745
746
746 Recursive reload
747 Recursive reload
747 ----------------
748 ----------------
748
749
749 The dreload function does a recursive reload of a module: changes made
750 The dreload function does a recursive reload of a module: changes made
750 to the module since you imported will actually be available without
751 to the module since you imported will actually be available without
751 having to exit.
752 having to exit.
752
753
753
754
754 Verbose and colored exception traceback printouts
755 Verbose and colored exception traceback printouts
755 -------------------------------------------------
756 -------------------------------------------------
756
757
757 IPython provides the option to see very detailed exception tracebacks,
758 IPython provides the option to see very detailed exception tracebacks,
758 which can be especially useful when debugging large programs. You can
759 which can be especially useful when debugging large programs. You can
759 run any Python file with the %run function to benefit from these
760 run any Python file with the %run function to benefit from these
760 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
761 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
761 be colored (if your terminal supports it) which makes them much easier
762 be colored (if your terminal supports it) which makes them much easier
762 to parse visually.
763 to parse visually.
763
764
764 See the magic xmode and colors functions for details (just type %magic).
765 See the magic xmode and colors functions for details (just type %magic).
765
766
766 These features are basically a terminal version of Ka-Ping Yee's cgitb
767 These features are basically a terminal version of Ka-Ping Yee's cgitb
767 module, now part of the standard Python library.
768 module, now part of the standard Python library.
768
769
769
770
770 .. _input_caching:
771 .. _input_caching:
771
772
772 Input caching system
773 Input caching system
773 --------------------
774 --------------------
774
775
775 IPython offers numbered prompts (In/Out) with input and output caching
776 IPython offers numbered prompts (In/Out) with input and output caching
776 (also referred to as 'input history'). All input is saved and can be
777 (also referred to as 'input history'). All input is saved and can be
777 retrieved as variables (besides the usual arrow key recall), in
778 retrieved as variables (besides the usual arrow key recall), in
778 addition to the %rep magic command that brings a history entry
779 addition to the %rep magic command that brings a history entry
779 up for editing on the next command line.
780 up for editing on the next command line.
780
781
781 The following GLOBAL variables always exist (so don't overwrite them!):
782 The following GLOBAL variables always exist (so don't overwrite them!):
782 _i: stores previous input. _ii: next previous. _iii: next-next previous.
783 _i: stores previous input. _ii: next previous. _iii: next-next previous.
783 _ih : a list of all input _ih[n] is the input from line n and this list
784 _ih : a list of all input _ih[n] is the input from line n and this list
784 is aliased to the global variable In. If you overwrite In with a
785 is aliased to the global variable In. If you overwrite In with a
785 variable of your own, you can remake the assignment to the internal list
786 variable of your own, you can remake the assignment to the internal list
786 with a simple 'In=_ih'.
787 with a simple 'In=_ih'.
787
788
788 Additionally, global variables named _i<n> are dynamically created (<n>
789 Additionally, global variables named _i<n> are dynamically created (<n>
789 being the prompt counter), such that
790 being the prompt counter), such that
790 _i<n> == _ih[<n>] == In[<n>].
791 _i<n> == _ih[<n>] == In[<n>].
791
792
792 For example, what you typed at prompt 14 is available as _i14, _ih[14]
793 For example, what you typed at prompt 14 is available as _i14, _ih[14]
793 and In[14].
794 and In[14].
794
795
795 This allows you to easily cut and paste multi line interactive prompts
796 This allows you to easily cut and paste multi line interactive prompts
796 by printing them out: they print like a clean string, without prompt
797 by printing them out: they print like a clean string, without prompt
797 characters. You can also manipulate them like regular variables (they
798 characters. You can also manipulate them like regular variables (they
798 are strings), modify or exec them (typing 'exec _i9' will re-execute the
799 are strings), modify or exec them (typing 'exec _i9' will re-execute the
799 contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines
800 contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines
800 9 through 13 and line 18).
801 9 through 13 and line 18).
801
802
802 You can also re-execute multiple lines of input easily by using the
803 You can also re-execute multiple lines of input easily by using the
803 magic %macro function (which automates the process and allows
804 magic %macro function (which automates the process and allows
804 re-execution without having to type 'exec' every time). The macro system
805 re-execution without having to type 'exec' every time). The macro system
805 also allows you to re-execute previous lines which include magic
806 also allows you to re-execute previous lines which include magic
806 function calls (which require special processing). Type %macro? or see
807 function calls (which require special processing). Type %macro? or see
807 sec. 6.2 <#sec:magic> for more details on the macro system.
808 sec. 6.2 <#sec:magic> for more details on the macro system.
808
809
809 A history function %hist allows you to see any part of your input
810 A history function %hist allows you to see any part of your input
810 history by printing a range of the _i variables.
811 history by printing a range of the _i variables.
811
812
812 You can also search ('grep') through your history by typing
813 You can also search ('grep') through your history by typing
813 '%hist -g somestring'. This also searches through the so called *shadow history*,
814 '%hist -g somestring'. This also searches through the so called *shadow history*,
814 which remembers all the commands (apart from multiline code blocks)
815 which remembers all the commands (apart from multiline code blocks)
815 you have ever entered. Handy for searching for svn/bzr URL's, IP adrresses
816 you have ever entered. Handy for searching for svn/bzr URL's, IP adrresses
816 etc. You can bring shadow history entries listed by '%hist -g' up for editing
817 etc. You can bring shadow history entries listed by '%hist -g' up for editing
817 (or re-execution by just pressing ENTER) with %rep command. Shadow history
818 (or re-execution by just pressing ENTER) with %rep command. Shadow history
818 entries are not available as _iNUMBER variables, and they are identified by
819 entries are not available as _iNUMBER variables, and they are identified by
819 the '0' prefix in %hist -g output. That is, history entry 12 is a normal
820 the '0' prefix in %hist -g output. That is, history entry 12 is a normal
820 history entry, but 0231 is a shadow history entry.
821 history entry, but 0231 is a shadow history entry.
821
822
822 Shadow history was added because the readline history is inherently very
823 Shadow history was added because the readline history is inherently very
823 unsafe - if you have multiple IPython sessions open, the last session
824 unsafe - if you have multiple IPython sessions open, the last session
824 to close will overwrite the history of previountly closed session. Likewise,
825 to close will overwrite the history of previountly closed session. Likewise,
825 if a crash occurs, history is never saved, whereas shadow history entries
826 if a crash occurs, history is never saved, whereas shadow history entries
826 are added after entering every command (so a command executed
827 are added after entering every command (so a command executed
827 in another IPython session is immediately available in other IPython
828 in another IPython session is immediately available in other IPython
828 sessions that are open).
829 sessions that are open).
829
830
830 To conserve space, a command can exist in shadow history only once - it doesn't
831 To conserve space, a command can exist in shadow history only once - it doesn't
831 make sense to store a common line like "cd .." a thousand times. The idea is
832 make sense to store a common line like "cd .." a thousand times. The idea is
832 mainly to provide a reliable place where valuable, hard-to-remember commands can
833 mainly to provide a reliable place where valuable, hard-to-remember commands can
833 always be retrieved, as opposed to providing an exact sequence of commands
834 always be retrieved, as opposed to providing an exact sequence of commands
834 you have entered in actual order.
835 you have entered in actual order.
835
836
836 Because shadow history has all the commands you have ever executed,
837 Because shadow history has all the commands you have ever executed,
837 time taken by %hist -g will increase oven time. If it ever starts to take
838 time taken by %hist -g will increase oven time. If it ever starts to take
838 too long (or it ends up containing sensitive information like passwords),
839 too long (or it ends up containing sensitive information like passwords),
839 clear the shadow history by `%clear shadow_nuke`.
840 clear the shadow history by `%clear shadow_nuke`.
840
841
841 Time taken to add entries to shadow history should be negligible, but
842 Time taken to add entries to shadow history should be negligible, but
842 in any case, if you start noticing performance degradation after using
843 in any case, if you start noticing performance degradation after using
843 IPython for a long time (or running a script that floods the shadow history!),
844 IPython for a long time (or running a script that floods the shadow history!),
844 you can 'compress' the shadow history by executing
845 you can 'compress' the shadow history by executing
845 `%clear shadow_compress`. In practice, this should never be necessary
846 `%clear shadow_compress`. In practice, this should never be necessary
846 in normal use.
847 in normal use.
847
848
848 .. _output_caching:
849 .. _output_caching:
849
850
850 Output caching system
851 Output caching system
851 ---------------------
852 ---------------------
852
853
853 For output that is returned from actions, a system similar to the input
854 For output that is returned from actions, a system similar to the input
854 cache exists but using _ instead of _i. Only actions that produce a
855 cache exists but using _ instead of _i. Only actions that produce a
855 result (NOT assignments, for example) are cached. If you are familiar
856 result (NOT assignments, for example) are cached. If you are familiar
856 with Mathematica, IPython's _ variables behave exactly like
857 with Mathematica, IPython's _ variables behave exactly like
857 Mathematica's % variables.
858 Mathematica's % variables.
858
859
859 The following GLOBAL variables always exist (so don't overwrite them!):
860 The following GLOBAL variables always exist (so don't overwrite them!):
860
861
861 * [_] (a single underscore) : stores previous output, like Python's
862 * [_] (a single underscore) : stores previous output, like Python's
862 default interpreter.
863 default interpreter.
863 * [__] (two underscores): next previous.
864 * [__] (two underscores): next previous.
864 * [___] (three underscores): next-next previous.
865 * [___] (three underscores): next-next previous.
865
866
866 Additionally, global variables named _<n> are dynamically created (<n>
867 Additionally, global variables named _<n> are dynamically created (<n>
867 being the prompt counter), such that the result of output <n> is always
868 being the prompt counter), such that the result of output <n> is always
868 available as _<n> (don't use the angle brackets, just the number, e.g.
869 available as _<n> (don't use the angle brackets, just the number, e.g.
869 _21).
870 _21).
870
871
871 These global variables are all stored in a global dictionary (not a
872 These global variables are all stored in a global dictionary (not a
872 list, since it only has entries for lines which returned a result)
873 list, since it only has entries for lines which returned a result)
873 available under the names _oh and Out (similar to _ih and In). So the
874 available under the names _oh and Out (similar to _ih and In). So the
874 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
875 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
875 accidentally overwrite the Out variable you can recover it by typing
876 accidentally overwrite the Out variable you can recover it by typing
876 'Out=_oh' at the prompt.
877 'Out=_oh' at the prompt.
877
878
878 This system obviously can potentially put heavy memory demands on your
879 This system obviously can potentially put heavy memory demands on your
879 system, since it prevents Python's garbage collector from removing any
880 system, since it prevents Python's garbage collector from removing any
880 previously computed results. You can control how many results are kept
881 previously computed results. You can control how many results are kept
881 in memory with the option (at the command line or in your ipythonrc
882 in memory with the option (at the command line or in your ipythonrc
882 file) cache_size. If you set it to 0, the whole system is completely
883 file) cache_size. If you set it to 0, the whole system is completely
883 disabled and the prompts revert to the classic '>>>' of normal Python.
884 disabled and the prompts revert to the classic '>>>' of normal Python.
884
885
885
886
886 Directory history
887 Directory history
887 -----------------
888 -----------------
888
889
889 Your history of visited directories is kept in the global list _dh, and
890 Your history of visited directories is kept in the global list _dh, and
890 the magic %cd command can be used to go to any entry in that list. The
891 the magic %cd command can be used to go to any entry in that list. The
891 %dhist command allows you to view this history. Do ``cd -<TAB`` to
892 %dhist command allows you to view this history. Do ``cd -<TAB`` to
892 conventiently view the directory history.
893 conventiently view the directory history.
893
894
894
895
895 Automatic parentheses and quotes
896 Automatic parentheses and quotes
896 --------------------------------
897 --------------------------------
897
898
898 These features were adapted from Nathan Gray's LazyPython. They are
899 These features were adapted from Nathan Gray's LazyPython. They are
899 meant to allow less typing for common situations.
900 meant to allow less typing for common situations.
900
901
901
902
902 Automatic parentheses
903 Automatic parentheses
903 ---------------------
904 ---------------------
904
905
905 Callable objects (i.e. functions, methods, etc) can be invoked like this
906 Callable objects (i.e. functions, methods, etc) can be invoked like this
906 (notice the commas between the arguments)::
907 (notice the commas between the arguments)::
907
908
908 >>> callable_ob arg1, arg2, arg3
909 >>> callable_ob arg1, arg2, arg3
909
910
910 and the input will be translated to this::
911 and the input will be translated to this::
911
912
912 -> callable_ob(arg1, arg2, arg3)
913 -> callable_ob(arg1, arg2, arg3)
913
914
914 You can force automatic parentheses by using '/' as the first character
915 You can force automatic parentheses by using '/' as the first character
915 of a line. For example::
916 of a line. For example::
916
917
917 >>> /globals # becomes 'globals()'
918 >>> /globals # becomes 'globals()'
918
919
919 Note that the '/' MUST be the first character on the line! This won't work::
920 Note that the '/' MUST be the first character on the line! This won't work::
920
921
921 >>> print /globals # syntax error
922 >>> print /globals # syntax error
922
923
923 In most cases the automatic algorithm should work, so you should rarely
924 In most cases the automatic algorithm should work, so you should rarely
924 need to explicitly invoke /. One notable exception is if you are trying
925 need to explicitly invoke /. One notable exception is if you are trying
925 to call a function with a list of tuples as arguments (the parenthesis
926 to call a function with a list of tuples as arguments (the parenthesis
926 will confuse IPython)::
927 will confuse IPython)::
927
928
928 In [1]: zip (1,2,3),(4,5,6) # won't work
929 In [1]: zip (1,2,3),(4,5,6) # won't work
929
930
930 but this will work::
931 but this will work::
931
932
932 In [2]: /zip (1,2,3),(4,5,6)
933 In [2]: /zip (1,2,3),(4,5,6)
933 ---> zip ((1,2,3),(4,5,6))
934 ---> zip ((1,2,3),(4,5,6))
934 Out[2]= [(1, 4), (2, 5), (3, 6)]
935 Out[2]= [(1, 4), (2, 5), (3, 6)]
935
936
936 IPython tells you that it has altered your command line by displaying
937 IPython tells you that it has altered your command line by displaying
937 the new command line preceded by ->. e.g.::
938 the new command line preceded by ->. e.g.::
938
939
939 In [18]: callable list
940 In [18]: callable list
940 ----> callable (list)
941 ----> callable (list)
941
942
942
943
943 Automatic quoting
944 Automatic quoting
944 -----------------
945 -----------------
945
946
946 You can force automatic quoting of a function's arguments by using ','
947 You can force automatic quoting of a function's arguments by using ','
947 or ';' as the first character of a line. For example::
948 or ';' as the first character of a line. For example::
948
949
949 >>> ,my_function /home/me # becomes my_function("/home/me")
950 >>> ,my_function /home/me # becomes my_function("/home/me")
950
951
951 If you use ';' instead, the whole argument is quoted as a single string
952 If you use ';' instead, the whole argument is quoted as a single string
952 (while ',' splits on whitespace)::
953 (while ',' splits on whitespace)::
953
954
954 >>> ,my_function a b c # becomes my_function("a","b","c")
955 >>> ,my_function a b c # becomes my_function("a","b","c")
955
956
956 >>> ;my_function a b c # becomes my_function("a b c")
957 >>> ;my_function a b c # becomes my_function("a b c")
957
958
958 Note that the ',' or ';' MUST be the first character on the line! This
959 Note that the ',' or ';' MUST be the first character on the line! This
959 won't work::
960 won't work::
960
961
961 >>> x = ,my_function /home/me # syntax error
962 >>> x = ,my_function /home/me # syntax error
962
963
963 IPython as your default Python environment
964 IPython as your default Python environment
964 ==========================================
965 ==========================================
965
966
966 Python honors the environment variable PYTHONSTARTUP and will execute at
967 Python honors the environment variable PYTHONSTARTUP and will execute at
967 startup the file referenced by this variable. If you put at the end of
968 startup the file referenced by this variable. If you put at the end of
968 this file the following two lines of code::
969 this file the following two lines of code::
969
970
970 import IPython
971 import IPython
971 IPython.Shell.IPShell().mainloop(sys_exit=1)
972 IPython.Shell.IPShell().mainloop(sys_exit=1)
972
973
973 then IPython will be your working environment anytime you start Python.
974 then IPython will be your working environment anytime you start Python.
974 The sys_exit=1 is needed to have IPython issue a call to sys.exit() when
975 The sys_exit=1 is needed to have IPython issue a call to sys.exit() when
975 it finishes, otherwise you'll be back at the normal Python '>>>'
976 it finishes, otherwise you'll be back at the normal Python '>>>'
976 prompt.
977 prompt.
977
978
978 This is probably useful to developers who manage multiple Python
979 This is probably useful to developers who manage multiple Python
979 versions and don't want to have correspondingly multiple IPython
980 versions and don't want to have correspondingly multiple IPython
980 versions. Note that in this mode, there is no way to pass IPython any
981 versions. Note that in this mode, there is no way to pass IPython any
981 command-line options, as those are trapped first by Python itself.
982 command-line options, as those are trapped first by Python itself.
982
983
983 .. _Embedding:
984 .. _Embedding:
984
985
985 Embedding IPython
986 Embedding IPython
986 =================
987 =================
987
988
988 It is possible to start an IPython instance inside your own Python
989 It is possible to start an IPython instance inside your own Python
989 programs. This allows you to evaluate dynamically the state of your
990 programs. This allows you to evaluate dynamically the state of your
990 code, operate with your variables, analyze them, etc. Note however that
991 code, operate with your variables, analyze them, etc. Note however that
991 any changes you make to values while in the shell do not propagate back
992 any changes you make to values while in the shell do not propagate back
992 to the running code, so it is safe to modify your values because you
993 to the running code, so it is safe to modify your values because you
993 won't break your code in bizarre ways by doing so.
994 won't break your code in bizarre ways by doing so.
994
995
995 This feature allows you to easily have a fully functional python
996 This feature allows you to easily have a fully functional python
996 environment for doing object introspection anywhere in your code with a
997 environment for doing object introspection anywhere in your code with a
997 simple function call. In some cases a simple print statement is enough,
998 simple function call. In some cases a simple print statement is enough,
998 but if you need to do more detailed analysis of a code fragment this
999 but if you need to do more detailed analysis of a code fragment this
999 feature can be very valuable.
1000 feature can be very valuable.
1000
1001
1001 It can also be useful in scientific computing situations where it is
1002 It can also be useful in scientific computing situations where it is
1002 common to need to do some automatic, computationally intensive part and
1003 common to need to do some automatic, computationally intensive part and
1003 then stop to look at data, plots, etc.
1004 then stop to look at data, plots, etc.
1004 Opening an IPython instance will give you full access to your data and
1005 Opening an IPython instance will give you full access to your data and
1005 functions, and you can resume program execution once you are done with
1006 functions, and you can resume program execution once you are done with
1006 the interactive part (perhaps to stop again later, as many times as
1007 the interactive part (perhaps to stop again later, as many times as
1007 needed).
1008 needed).
1008
1009
1009 The following code snippet is the bare minimum you need to include in
1010 The following code snippet is the bare minimum you need to include in
1010 your Python programs for this to work (detailed examples follow later)::
1011 your Python programs for this to work (detailed examples follow later)::
1011
1012
1012 from IPython.Shell import IPShellEmbed
1013 from IPython.Shell import IPShellEmbed
1013
1014
1014 ipshell = IPShellEmbed()
1015 ipshell = IPShellEmbed()
1015
1016
1016 ipshell() # this call anywhere in your program will start IPython
1017 ipshell() # this call anywhere in your program will start IPython
1017
1018
1018 You can run embedded instances even in code which is itself being run at
1019 You can run embedded instances even in code which is itself being run at
1019 the IPython interactive prompt with '%run <filename>'. Since it's easy
1020 the IPython interactive prompt with '%run <filename>'. Since it's easy
1020 to get lost as to where you are (in your top-level IPython or in your
1021 to get lost as to where you are (in your top-level IPython or in your
1021 embedded one), it's a good idea in such cases to set the in/out prompts
1022 embedded one), it's a good idea in such cases to set the in/out prompts
1022 to something different for the embedded instances. The code examples
1023 to something different for the embedded instances. The code examples
1023 below illustrate this.
1024 below illustrate this.
1024
1025
1025 You can also have multiple IPython instances in your program and open
1026 You can also have multiple IPython instances in your program and open
1026 them separately, for example with different options for data
1027 them separately, for example with different options for data
1027 presentation. If you close and open the same instance multiple times,
1028 presentation. If you close and open the same instance multiple times,
1028 its prompt counters simply continue from each execution to the next.
1029 its prompt counters simply continue from each execution to the next.
1029
1030
1030 Please look at the docstrings in the Shell.py module for more details on
1031 Please look at the docstrings in the Shell.py module for more details on
1031 the use of this system.
1032 the use of this system.
1032
1033
1033 The following sample file illustrating how to use the embedding
1034 The following sample file illustrating how to use the embedding
1034 functionality is provided in the examples directory as example-embed.py.
1035 functionality is provided in the examples directory as example-embed.py.
1035 It should be fairly self-explanatory::
1036 It should be fairly self-explanatory::
1036
1037
1037
1038
1038 #!/usr/bin/env python
1039 #!/usr/bin/env python
1039
1040
1040 """An example of how to embed an IPython shell into a running program.
1041 """An example of how to embed an IPython shell into a running program.
1041
1042
1042 Please see the documentation in the IPython.Shell module for more details.
1043 Please see the documentation in the IPython.Shell module for more details.
1043
1044
1044 The accompanying file example-embed-short.py has quick code fragments for
1045 The accompanying file example-embed-short.py has quick code fragments for
1045 embedding which you can cut and paste in your code once you understand how
1046 embedding which you can cut and paste in your code once you understand how
1046 things work.
1047 things work.
1047
1048
1048 The code in this file is deliberately extra-verbose, meant for learning."""
1049 The code in this file is deliberately extra-verbose, meant for learning."""
1049
1050
1050 # The basics to get you going:
1051 # The basics to get you going:
1051
1052
1052 # IPython sets the __IPYTHON__ variable so you can know if you have nested
1053 # IPython sets the __IPYTHON__ variable so you can know if you have nested
1053 # copies running.
1054 # copies running.
1054
1055
1055 # Try running this code both at the command line and from inside IPython (with
1056 # Try running this code both at the command line and from inside IPython (with
1056 # %run example-embed.py)
1057 # %run example-embed.py)
1057 try:
1058 try:
1058 __IPYTHON__
1059 __IPYTHON__
1059 except NameError:
1060 except NameError:
1060 nested = 0
1061 nested = 0
1061 args = ['']
1062 args = ['']
1062 else:
1063 else:
1063 print "Running nested copies of IPython."
1064 print "Running nested copies of IPython."
1064 print "The prompts for the nested copy have been modified"
1065 print "The prompts for the nested copy have been modified"
1065 nested = 1
1066 nested = 1
1066 # what the embedded instance will see as sys.argv:
1067 # what the embedded instance will see as sys.argv:
1067 args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ',
1068 args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ',
1068 '-po','Out<\\#>: ','-nosep']
1069 '-po','Out<\\#>: ','-nosep']
1069
1070
1070 # First import the embeddable shell class
1071 # First import the embeddable shell class
1071 from IPython.Shell import IPShellEmbed
1072 from IPython.Shell import IPShellEmbed
1072
1073
1073 # Now create an instance of the embeddable shell. The first argument is a
1074 # Now create an instance of the embeddable shell. The first argument is a
1074 # string with options exactly as you would type them if you were starting
1075 # string with options exactly as you would type them if you were starting
1075 # IPython at the system command line. Any parameters you want to define for
1076 # IPython at the system command line. Any parameters you want to define for
1076 # configuration can thus be specified here.
1077 # configuration can thus be specified here.
1077 ipshell = IPShellEmbed(args,
1078 ipshell = IPShellEmbed(args,
1078 banner = 'Dropping into IPython',
1079 banner = 'Dropping into IPython',
1079 exit_msg = 'Leaving Interpreter, back to program.')
1080 exit_msg = 'Leaving Interpreter, back to program.')
1080
1081
1081 # Make a second instance, you can have as many as you want.
1082 # Make a second instance, you can have as many as you want.
1082 if nested:
1083 if nested:
1083 args[1] = 'In2<\\#>'
1084 args[1] = 'In2<\\#>'
1084 else:
1085 else:
1085 args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ',
1086 args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ',
1086 '-po','Out<\\#>: ','-nosep']
1087 '-po','Out<\\#>: ','-nosep']
1087 ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.')
1088 ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.')
1088
1089
1089 print '\nHello. This is printed from the main controller program.\n'
1090 print '\nHello. This is printed from the main controller program.\n'
1090
1091
1091 # You can then call ipshell() anywhere you need it (with an optional
1092 # You can then call ipshell() anywhere you need it (with an optional
1092 # message):
1093 # message):
1093 ipshell('***Called from top level. '
1094 ipshell('***Called from top level. '
1094 'Hit Ctrl-D to exit interpreter and continue program.\n'
1095 'Hit Ctrl-D to exit interpreter and continue program.\n'
1095 'Note that if you use %kill_embedded, you can fully deactivate\n'
1096 'Note that if you use %kill_embedded, you can fully deactivate\n'
1096 'This embedded instance so it will never turn on again')
1097 'This embedded instance so it will never turn on again')
1097
1098
1098 print '\nBack in caller program, moving along...\n'
1099 print '\nBack in caller program, moving along...\n'
1099
1100
1100 #---------------------------------------------------------------------------
1101 #---------------------------------------------------------------------------
1101 # More details:
1102 # More details:
1102
1103
1103 # IPShellEmbed instances don't print the standard system banner and
1104 # IPShellEmbed instances don't print the standard system banner and
1104 # messages. The IPython banner (which actually may contain initialization
1105 # messages. The IPython banner (which actually may contain initialization
1105 # messages) is available as <instance>.IP.BANNER in case you want it.
1106 # messages) is available as <instance>.IP.BANNER in case you want it.
1106
1107
1107 # IPShellEmbed instances print the following information everytime they
1108 # IPShellEmbed instances print the following information everytime they
1108 # start:
1109 # start:
1109
1110
1110 # - A global startup banner.
1111 # - A global startup banner.
1111
1112
1112 # - A call-specific header string, which you can use to indicate where in the
1113 # - A call-specific header string, which you can use to indicate where in the
1113 # execution flow the shell is starting.
1114 # execution flow the shell is starting.
1114
1115
1115 # They also print an exit message every time they exit.
1116 # They also print an exit message every time they exit.
1116
1117
1117 # Both the startup banner and the exit message default to None, and can be set
1118 # Both the startup banner and the exit message default to None, and can be set
1118 # either at the instance constructor or at any other time with the
1119 # either at the instance constructor or at any other time with the
1119 # set_banner() and set_exit_msg() methods.
1120 # set_banner() and set_exit_msg() methods.
1120
1121
1121 # The shell instance can be also put in 'dummy' mode globally or on a per-call
1122 # The shell instance can be also put in 'dummy' mode globally or on a per-call
1122 # basis. This gives you fine control for debugging without having to change
1123 # basis. This gives you fine control for debugging without having to change
1123 # code all over the place.
1124 # code all over the place.
1124
1125
1125 # The code below illustrates all this.
1126 # The code below illustrates all this.
1126
1127
1127
1128
1128 # This is how the global banner and exit_msg can be reset at any point
1129 # This is how the global banner and exit_msg can be reset at any point
1129 ipshell.set_banner('Entering interpreter - New Banner')
1130 ipshell.set_banner('Entering interpreter - New Banner')
1130 ipshell.set_exit_msg('Leaving interpreter - New exit_msg')
1131 ipshell.set_exit_msg('Leaving interpreter - New exit_msg')
1131
1132
1132 def foo(m):
1133 def foo(m):
1133 s = 'spam'
1134 s = 'spam'
1134 ipshell('***In foo(). Try @whos, or print s or m:')
1135 ipshell('***In foo(). Try @whos, or print s or m:')
1135 print 'foo says m = ',m
1136 print 'foo says m = ',m
1136
1137
1137 def bar(n):
1138 def bar(n):
1138 s = 'eggs'
1139 s = 'eggs'
1139 ipshell('***In bar(). Try @whos, or print s or n:')
1140 ipshell('***In bar(). Try @whos, or print s or n:')
1140 print 'bar says n = ',n
1141 print 'bar says n = ',n
1141
1142
1142 # Some calls to the above functions which will trigger IPython:
1143 # Some calls to the above functions which will trigger IPython:
1143 print 'Main program calling foo("eggs")\n'
1144 print 'Main program calling foo("eggs")\n'
1144 foo('eggs')
1145 foo('eggs')
1145
1146
1146 # The shell can be put in 'dummy' mode where calls to it silently return. This
1147 # The shell can be put in 'dummy' mode where calls to it silently return. This
1147 # allows you, for example, to globally turn off debugging for a program with a
1148 # allows you, for example, to globally turn off debugging for a program with a
1148 # single call.
1149 # single call.
1149 ipshell.set_dummy_mode(1)
1150 ipshell.set_dummy_mode(1)
1150 print '\nTrying to call IPython which is now "dummy":'
1151 print '\nTrying to call IPython which is now "dummy":'
1151 ipshell()
1152 ipshell()
1152 print 'Nothing happened...'
1153 print 'Nothing happened...'
1153 # The global 'dummy' mode can still be overridden for a single call
1154 # The global 'dummy' mode can still be overridden for a single call
1154 print '\nOverriding dummy mode manually:'
1155 print '\nOverriding dummy mode manually:'
1155 ipshell(dummy=0)
1156 ipshell(dummy=0)
1156
1157
1157 # Reactivate the IPython shell
1158 # Reactivate the IPython shell
1158 ipshell.set_dummy_mode(0)
1159 ipshell.set_dummy_mode(0)
1159
1160
1160 print 'You can even have multiple embedded instances:'
1161 print 'You can even have multiple embedded instances:'
1161 ipshell2()
1162 ipshell2()
1162
1163
1163 print '\nMain program calling bar("spam")\n'
1164 print '\nMain program calling bar("spam")\n'
1164 bar('spam')
1165 bar('spam')
1165
1166
1166 print 'Main program finished. Bye!'
1167 print 'Main program finished. Bye!'
1167
1168
1168 #********************** End of file <example-embed.py> ***********************
1169 #********************** End of file <example-embed.py> ***********************
1169
1170
1170 Once you understand how the system functions, you can use the following
1171 Once you understand how the system functions, you can use the following
1171 code fragments in your programs which are ready for cut and paste::
1172 code fragments in your programs which are ready for cut and paste::
1172
1173
1173
1174
1174 """Quick code snippets for embedding IPython into other programs.
1175 """Quick code snippets for embedding IPython into other programs.
1175
1176
1176 See example-embed.py for full details, this file has the bare minimum code for
1177 See example-embed.py for full details, this file has the bare minimum code for
1177 cut and paste use once you understand how to use the system."""
1178 cut and paste use once you understand how to use the system."""
1178
1179
1179 #---------------------------------------------------------------------------
1180 #---------------------------------------------------------------------------
1180 # This code loads IPython but modifies a few things if it detects it's running
1181 # This code loads IPython but modifies a few things if it detects it's running
1181 # embedded in another IPython session (helps avoid confusion)
1182 # embedded in another IPython session (helps avoid confusion)
1182
1183
1183 try:
1184 try:
1184 __IPYTHON__
1185 __IPYTHON__
1185 except NameError:
1186 except NameError:
1186 argv = ['']
1187 argv = ['']
1187 banner = exit_msg = ''
1188 banner = exit_msg = ''
1188 else:
1189 else:
1189 # Command-line options for IPython (a list like sys.argv)
1190 # Command-line options for IPython (a list like sys.argv)
1190 argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:']
1191 argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:']
1191 banner = '*** Nested interpreter ***'
1192 banner = '*** Nested interpreter ***'
1192 exit_msg = '*** Back in main IPython ***'
1193 exit_msg = '*** Back in main IPython ***'
1193
1194
1194 # First import the embeddable shell class
1195 # First import the embeddable shell class
1195 from IPython.Shell import IPShellEmbed
1196 from IPython.Shell import IPShellEmbed
1196 # Now create the IPython shell instance. Put ipshell() anywhere in your code
1197 # Now create the IPython shell instance. Put ipshell() anywhere in your code
1197 # where you want it to open.
1198 # where you want it to open.
1198 ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg)
1199 ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg)
1199
1200
1200 #---------------------------------------------------------------------------
1201 #---------------------------------------------------------------------------
1201 # This code will load an embeddable IPython shell always with no changes for
1202 # This code will load an embeddable IPython shell always with no changes for
1202 # nested embededings.
1203 # nested embededings.
1203
1204
1204 from IPython.Shell import IPShellEmbed
1205 from IPython.Shell import IPShellEmbed
1205 ipshell = IPShellEmbed()
1206 ipshell = IPShellEmbed()
1206 # Now ipshell() will open IPython anywhere in the code.
1207 # Now ipshell() will open IPython anywhere in the code.
1207
1208
1208 #---------------------------------------------------------------------------
1209 #---------------------------------------------------------------------------
1209 # This code loads an embeddable shell only if NOT running inside
1210 # This code loads an embeddable shell only if NOT running inside
1210 # IPython. Inside IPython, the embeddable shell variable ipshell is just a
1211 # IPython. Inside IPython, the embeddable shell variable ipshell is just a
1211 # dummy function.
1212 # dummy function.
1212
1213
1213 try:
1214 try:
1214 __IPYTHON__
1215 __IPYTHON__
1215 except NameError:
1216 except NameError:
1216 from IPython.Shell import IPShellEmbed
1217 from IPython.Shell import IPShellEmbed
1217 ipshell = IPShellEmbed()
1218 ipshell = IPShellEmbed()
1218 # Now ipshell() will open IPython anywhere in the code
1219 # Now ipshell() will open IPython anywhere in the code
1219 else:
1220 else:
1220 # Define a dummy ipshell() so the same code doesn't crash inside an
1221 # Define a dummy ipshell() so the same code doesn't crash inside an
1221 # interactive IPython
1222 # interactive IPython
1222 def ipshell(): pass
1223 def ipshell(): pass
1223
1224
1224 #******************* End of file <example-embed-short.py> ********************
1225 #******************* End of file <example-embed-short.py> ********************
1225
1226
1226 Using the Python debugger (pdb)
1227 Using the Python debugger (pdb)
1227 ===============================
1228 ===============================
1228
1229
1229 Running entire programs via pdb
1230 Running entire programs via pdb
1230 -------------------------------
1231 -------------------------------
1231
1232
1232 pdb, the Python debugger, is a powerful interactive debugger which
1233 pdb, the Python debugger, is a powerful interactive debugger which
1233 allows you to step through code, set breakpoints, watch variables,
1234 allows you to step through code, set breakpoints, watch variables,
1234 etc. IPython makes it very easy to start any script under the control
1235 etc. IPython makes it very easy to start any script under the control
1235 of pdb, regardless of whether you have wrapped it into a 'main()'
1236 of pdb, regardless of whether you have wrapped it into a 'main()'
1236 function or not. For this, simply type '%run -d myscript' at an
1237 function or not. For this, simply type '%run -d myscript' at an
1237 IPython prompt. See the %run command's documentation (via '%run?' or
1238 IPython prompt. See the %run command's documentation (via '%run?' or
1238 in Sec. magic_ for more details, including how to control where pdb
1239 in Sec. magic_ for more details, including how to control where pdb
1239 will stop execution first.
1240 will stop execution first.
1240
1241
1241 For more information on the use of the pdb debugger, read the included
1242 For more information on the use of the pdb debugger, read the included
1242 pdb.doc file (part of the standard Python distribution). On a stock
1243 pdb.doc file (part of the standard Python distribution). On a stock
1243 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
1244 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
1244 easiest way to read it is by using the help() function of the pdb module
1245 easiest way to read it is by using the help() function of the pdb module
1245 as follows (in an IPython prompt):
1246 as follows (in an IPython prompt):
1246
1247
1247 In [1]: import pdb
1248 In [1]: import pdb
1248 In [2]: pdb.help()
1249 In [2]: pdb.help()
1249
1250
1250 This will load the pdb.doc document in a file viewer for you automatically.
1251 This will load the pdb.doc document in a file viewer for you automatically.
1251
1252
1252
1253
1253 Automatic invocation of pdb on exceptions
1254 Automatic invocation of pdb on exceptions
1254 -----------------------------------------
1255 -----------------------------------------
1255
1256
1256 IPython, if started with the -pdb option (or if the option is set in
1257 IPython, if started with the -pdb option (or if the option is set in
1257 your rc file) can call the Python pdb debugger every time your code
1258 your rc file) can call the Python pdb debugger every time your code
1258 triggers an uncaught exception. This feature
1259 triggers an uncaught exception. This feature
1259 can also be toggled at any time with the %pdb magic command. This can be
1260 can also be toggled at any time with the %pdb magic command. This can be
1260 extremely useful in order to find the origin of subtle bugs, because pdb
1261 extremely useful in order to find the origin of subtle bugs, because pdb
1261 opens up at the point in your code which triggered the exception, and
1262 opens up at the point in your code which triggered the exception, and
1262 while your program is at this point 'dead', all the data is still
1263 while your program is at this point 'dead', all the data is still
1263 available and you can walk up and down the stack frame and understand
1264 available and you can walk up and down the stack frame and understand
1264 the origin of the problem.
1265 the origin of the problem.
1265
1266
1266 Furthermore, you can use these debugging facilities both with the
1267 Furthermore, you can use these debugging facilities both with the
1267 embedded IPython mode and without IPython at all. For an embedded shell
1268 embedded IPython mode and without IPython at all. For an embedded shell
1268 (see sec. Embedding_), simply call the constructor with
1269 (see sec. Embedding_), simply call the constructor with
1269 '-pdb' in the argument string and automatically pdb will be called if an
1270 '-pdb' in the argument string and automatically pdb will be called if an
1270 uncaught exception is triggered by your code.
1271 uncaught exception is triggered by your code.
1271
1272
1272 For stand-alone use of the feature in your programs which do not use
1273 For stand-alone use of the feature in your programs which do not use
1273 IPython at all, put the following lines toward the top of your 'main'
1274 IPython at all, put the following lines toward the top of your 'main'
1274 routine::
1275 routine::
1275
1276
1276 import sys
1277 import sys
1277 from IPython.core import ultratb
1278 from IPython.core import ultratb
1278 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
1279 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
1279 color_scheme='Linux', call_pdb=1)
1280 color_scheme='Linux', call_pdb=1)
1280
1281
1281 The mode keyword can be either 'Verbose' or 'Plain', giving either very
1282 The mode keyword can be either 'Verbose' or 'Plain', giving either very
1282 detailed or normal tracebacks respectively. The color_scheme keyword can
1283 detailed or normal tracebacks respectively. The color_scheme keyword can
1283 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
1284 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
1284 options which can be set in IPython with -colors and -xmode.
1285 options which can be set in IPython with -colors and -xmode.
1285
1286
1286 This will give any of your programs detailed, colored tracebacks with
1287 This will give any of your programs detailed, colored tracebacks with
1287 automatic invocation of pdb.
1288 automatic invocation of pdb.
1288
1289
1289
1290
1290 Extensions for syntax processing
1291 Extensions for syntax processing
1291 ================================
1292 ================================
1292
1293
1293 This isn't for the faint of heart, because the potential for breaking
1294 This isn't for the faint of heart, because the potential for breaking
1294 things is quite high. But it can be a very powerful and useful feature.
1295 things is quite high. But it can be a very powerful and useful feature.
1295 In a nutshell, you can redefine the way IPython processes the user input
1296 In a nutshell, you can redefine the way IPython processes the user input
1296 line to accept new, special extensions to the syntax without needing to
1297 line to accept new, special extensions to the syntax without needing to
1297 change any of IPython's own code.
1298 change any of IPython's own code.
1298
1299
1299 In the IPython/extensions directory you will find some examples
1300 In the IPython/extensions directory you will find some examples
1300 supplied, which we will briefly describe now. These can be used 'as is'
1301 supplied, which we will briefly describe now. These can be used 'as is'
1301 (and both provide very useful functionality), or you can use them as a
1302 (and both provide very useful functionality), or you can use them as a
1302 starting point for writing your own extensions.
1303 starting point for writing your own extensions.
1303
1304
1304
1305
1305 Pasting of code starting with '>>> ' or '... '
1306 Pasting of code starting with '>>> ' or '... '
1306 ----------------------------------------------
1307 ----------------------------------------------
1307
1308
1308 In the python tutorial it is common to find code examples which have
1309 In the python tutorial it is common to find code examples which have
1309 been taken from real python sessions. The problem with those is that all
1310 been taken from real python sessions. The problem with those is that all
1310 the lines begin with either '>>> ' or '... ', which makes it impossible
1311 the lines begin with either '>>> ' or '... ', which makes it impossible
1311 to paste them all at once. One must instead do a line by line manual
1312 to paste them all at once. One must instead do a line by line manual
1312 copying, carefully removing the leading extraneous characters.
1313 copying, carefully removing the leading extraneous characters.
1313
1314
1314 This extension identifies those starting characters and removes them
1315 This extension identifies those starting characters and removes them
1315 from the input automatically, so that one can paste multi-line examples
1316 from the input automatically, so that one can paste multi-line examples
1316 directly into IPython, saving a lot of time. Please look at the file
1317 directly into IPython, saving a lot of time. Please look at the file
1317 InterpreterPasteInput.py in the IPython/extensions directory for details
1318 InterpreterPasteInput.py in the IPython/extensions directory for details
1318 on how this is done.
1319 on how this is done.
1319
1320
1320 IPython comes with a special profile enabling this feature, called
1321 IPython comes with a special profile enabling this feature, called
1321 tutorial. Simply start IPython via 'ipython -p tutorial' and the feature
1322 tutorial. Simply start IPython via 'ipython -p tutorial' and the feature
1322 will be available. In a normal IPython session you can activate the
1323 will be available. In a normal IPython session you can activate the
1323 feature by importing the corresponding module with:
1324 feature by importing the corresponding module with:
1324 In [1]: import IPython.extensions.InterpreterPasteInput
1325 In [1]: import IPython.extensions.InterpreterPasteInput
1325
1326
1326 The following is a 'screenshot' of how things work when this extension
1327 The following is a 'screenshot' of how things work when this extension
1327 is on, copying an example from the standard tutorial::
1328 is on, copying an example from the standard tutorial::
1328
1329
1329 IPython profile: tutorial
1330 IPython profile: tutorial
1330
1331
1331 *** Pasting of code with ">>>" or "..." has been enabled.
1332 *** Pasting of code with ">>>" or "..." has been enabled.
1332
1333
1333 In [1]: >>> def fib2(n): # return Fibonacci series up to n
1334 In [1]: >>> def fib2(n): # return Fibonacci series up to n
1334 ...: ... """Return a list containing the Fibonacci series up to
1335 ...: ... """Return a list containing the Fibonacci series up to
1335 n."""
1336 n."""
1336 ...: ... result = []
1337 ...: ... result = []
1337 ...: ... a, b = 0, 1
1338 ...: ... a, b = 0, 1
1338 ...: ... while b < n:
1339 ...: ... while b < n:
1339 ...: ... result.append(b) # see below
1340 ...: ... result.append(b) # see below
1340 ...: ... a, b = b, a+b
1341 ...: ... a, b = b, a+b
1341 ...: ... return result
1342 ...: ... return result
1342 ...:
1343 ...:
1343
1344
1344 In [2]: fib2(10)
1345 In [2]: fib2(10)
1345 Out[2]: [1, 1, 2, 3, 5, 8]
1346 Out[2]: [1, 1, 2, 3, 5, 8]
1346
1347
1347 Note that as currently written, this extension does not recognize
1348 Note that as currently written, this extension does not recognize
1348 IPython's prompts for pasting. Those are more complicated, since the
1349 IPython's prompts for pasting. Those are more complicated, since the
1349 user can change them very easily, they involve numbers and can vary in
1350 user can change them very easily, they involve numbers and can vary in
1350 length. One could however extract all the relevant information from the
1351 length. One could however extract all the relevant information from the
1351 IPython instance and build an appropriate regular expression. This is
1352 IPython instance and build an appropriate regular expression. This is
1352 left as an exercise for the reader.
1353 left as an exercise for the reader.
1353
1354
1354
1355
1355 Input of physical quantities with units
1356 Input of physical quantities with units
1356 ---------------------------------------
1357 ---------------------------------------
1357
1358
1358 The module PhysicalQInput allows a simplified form of input for physical
1359 The module PhysicalQInput allows a simplified form of input for physical
1359 quantities with units. This file is meant to be used in conjunction with
1360 quantities with units. This file is meant to be used in conjunction with
1360 the PhysicalQInteractive module (in the same directory) and
1361 the PhysicalQInteractive module (in the same directory) and
1361 Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython
1362 Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython
1362 (http://dirac.cnrs-orleans.fr/ScientificPython/).
1363 (http://dirac.cnrs-orleans.fr/ScientificPython/).
1363
1364
1364 The Physics.PhysicalQuantities module defines PhysicalQuantity objects,
1365 The Physics.PhysicalQuantities module defines PhysicalQuantity objects,
1365 but these must be declared as instances of a class. For example, to
1366 but these must be declared as instances of a class. For example, to
1366 define v as a velocity of 3 m/s, normally you would write::
1367 define v as a velocity of 3 m/s, normally you would write::
1367
1368
1368 In [1]: v = PhysicalQuantity(3,'m/s')
1369 In [1]: v = PhysicalQuantity(3,'m/s')
1369
1370
1370 Using the PhysicalQ_Input extension this can be input instead as:
1371 Using the PhysicalQ_Input extension this can be input instead as:
1371 In [1]: v = 3 m/s
1372 In [1]: v = 3 m/s
1372 which is much more convenient for interactive use (even though it is
1373 which is much more convenient for interactive use (even though it is
1373 blatantly invalid Python syntax).
1374 blatantly invalid Python syntax).
1374
1375
1375 The physics profile supplied with IPython (enabled via 'ipython -p
1376 The physics profile supplied with IPython (enabled via 'ipython -p
1376 physics') uses these extensions, which you can also activate with:
1377 physics') uses these extensions, which you can also activate with:
1377
1378
1378 from math import * # math MUST be imported BEFORE PhysicalQInteractive
1379 from math import * # math MUST be imported BEFORE PhysicalQInteractive
1379 from IPython.extensions.PhysicalQInteractive import *
1380 from IPython.extensions.PhysicalQInteractive import *
1380 import IPython.extensions.PhysicalQInput
1381 import IPython.extensions.PhysicalQInput
1381
1382
1382 .. _gui_support:
1383 .. _gui_support:
1383
1384
1384 GUI event loop support support
1385 GUI event loop support support
1385 ==============================
1386 ==============================
1386
1387
1387 .. versionadded:: 0.11
1388 .. versionadded:: 0.11
1388 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
1389 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
1389
1390
1390 IPython has excellent support for working interactively with Graphical User
1391 IPython has excellent support for working interactively with Graphical User
1391 Interface (GUI) toolkits, such as wxPython, PyQt4, PyGTK and Tk. This is
1392 Interface (GUI) toolkits, such as wxPython, PyQt4, PyGTK and Tk. This is
1392 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
1393 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
1393 is extremely robust compared to our previous threaded based version. The
1394 is extremely robust compared to our previous threaded based version. The
1394 advantages of this are:
1395 advantages of this are:
1395
1396
1396 * GUIs can be enabled and disabled dynamically at runtime.
1397 * GUIs can be enabled and disabled dynamically at runtime.
1397 * The active GUI can be switched dynamically at runtime.
1398 * The active GUI can be switched dynamically at runtime.
1398 * In some cases, multiple GUIs can run simultaneously with no problems.
1399 * In some cases, multiple GUIs can run simultaneously with no problems.
1399 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
1400 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
1400 all of these things.
1401 all of these things.
1401
1402
1402 For users, enabling GUI event loop integration is simple. You simple use the
1403 For users, enabling GUI event loop integration is simple. You simple use the
1403 ``%gui`` magic as follows::
1404 ``%gui`` magic as follows::
1404
1405
1405 %gui [-a] [GUINAME]
1406 %gui [-a] [GUINAME]
1406
1407
1407 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
1408 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
1408 arguments are ``wx``, ``qt4``, ``gtk`` and ``tk``. The ``-a`` option will
1409 arguments are ``wx``, ``qt4``, ``gtk`` and ``tk``. The ``-a`` option will
1409 create and return a running application object for the selected GUI toolkit.
1410 create and return a running application object for the selected GUI toolkit.
1410
1411
1411 Thus, to use wxPython interactively and create a running :class:`wx.App`
1412 Thus, to use wxPython interactively and create a running :class:`wx.App`
1412 object, do::
1413 object, do::
1413
1414
1414 %gui -a wx
1415 %gui -a wx
1415
1416
1416 For information on IPython's Matplotlib integration (and the ``pylab`` mode)
1417 For information on IPython's Matplotlib integration (and the ``pylab`` mode)
1417 see :ref:`this section <matplotlib_support>`.
1418 see :ref:`this section <matplotlib_support>`.
1418
1419
1419 For developers that want to use IPython's GUI event loop integration in
1420 For developers that want to use IPython's GUI event loop integration in
1420 the form of a library, these capabilities are exposed in library form
1421 the form of a library, these capabilities are exposed in library form
1421 in the :mod:`IPython.lib.inputhook`. Interested developers should see the
1422 in the :mod:`IPython.lib.inputhook`. Interested developers should see the
1422 module docstrings for more information, but there are a few points that
1423 module docstrings for more information, but there are a few points that
1423 should be mentioned here.
1424 should be mentioned here.
1424
1425
1425 First, the ``PyOSInputHook`` approach only works in command line settings
1426 First, the ``PyOSInputHook`` approach only works in command line settings
1426 where readline is activated.
1427 where readline is activated.
1427
1428
1428 Second, when using the ``PyOSInputHook`` approach, a GUI application should
1429 Second, when using the ``PyOSInputHook`` approach, a GUI application should
1429 *not* start its event loop. Instead all of this is handled by the
1430 *not* start its event loop. Instead all of this is handled by the
1430 ``PyOSInputHook``. This means that applications that are meant to be used both
1431 ``PyOSInputHook``. This means that applications that are meant to be used both
1431 in IPython and as standalone apps need to have special code to detects how the
1432 in IPython and as standalone apps need to have special code to detects how the
1432 application is being run. We highly recommend using IPython's
1433 application is being run. We highly recommend using IPython's
1433 :func:`appstart_` functions for this. Here is a simple example that shows the
1434 :func:`appstart_` functions for this. Here is a simple example that shows the
1434 recommended code that should be at the bottom of a wxPython using GUI
1435 recommended code that should be at the bottom of a wxPython using GUI
1435 application::
1436 application::
1436
1437
1437 try:
1438 try:
1438 from IPython import appstart_wx
1439 from IPython import appstart_wx
1439 appstart_wx(app)
1440 appstart_wx(app)
1440 except ImportError:
1441 except ImportError:
1441 app.MainLoop()
1442 app.MainLoop()
1442
1443
1443 This pattern should be used instead of the simple ``app.MainLoop()`` code
1444 This pattern should be used instead of the simple ``app.MainLoop()`` code
1444 that a standalone wxPython application would have.
1445 that a standalone wxPython application would have.
1445
1446
1446 Third, unlike previous versions of IPython, we no longer "hijack" (replace
1447 Third, unlike previous versions of IPython, we no longer "hijack" (replace
1447 them with no-ops) the event loops. This is done to allow applications that
1448 them with no-ops) the event loops. This is done to allow applications that
1448 actually need to run the real event loops to do so. This is often needed to
1449 actually need to run the real event loops to do so. This is often needed to
1449 process pending events at critical points.
1450 process pending events at critical points.
1450
1451
1451 Finally, we also have a number of examples in our source directory
1452 Finally, we also have a number of examples in our source directory
1452 :file:`docs/examples/lib` that demonstrate these capabilities.
1453 :file:`docs/examples/lib` that demonstrate these capabilities.
1453
1454
1454 .. _matplotlib_support:
1455 .. _matplotlib_support:
1455
1456
1456 Plotting with matplotlib
1457 Plotting with matplotlib
1457 ========================
1458 ========================
1458
1459
1459
1460
1460 `Matplotlib`_ provides high quality 2D and
1461 `Matplotlib`_ provides high quality 2D and
1461 3D plotting for Python. Matplotlib can produce plots on screen using a variety
1462 3D plotting for Python. Matplotlib can produce plots on screen using a variety
1462 of GUI toolkits, including Tk, PyGTK, PyQt4 and wxPython. It also provides a
1463 of GUI toolkits, including Tk, PyGTK, PyQt4 and wxPython. It also provides a
1463 number of commands useful for scientific computing, all with a syntax
1464 number of commands useful for scientific computing, all with a syntax
1464 compatible with that of the popular Matlab program.
1465 compatible with that of the popular Matlab program.
1465
1466
1466 Many IPython users have come to rely on IPython's ``-pylab`` mode which
1467 Many IPython users have come to rely on IPython's ``-pylab`` mode which
1467 automates the integration of Matplotlib with IPython. We are still in the
1468 automates the integration of Matplotlib with IPython. We are still in the
1468 process of working with the Matplotlib developers to finalize the new pylab
1469 process of working with the Matplotlib developers to finalize the new pylab
1469 API, but for now you can use Matplotlib interactively using the following
1470 API, but for now you can use Matplotlib interactively using the following
1470 commands::
1471 commands::
1471
1472
1472 %gui -a wx
1473 %gui -a wx
1473 import matplotlib
1474 import matplotlib
1474 matplotlib.use('wxagg')
1475 matplotlib.use('wxagg')
1475 from matplotlib import pylab
1476 from matplotlib import pylab
1476 pylab.interactive(True)
1477 pylab.interactive(True)
1477
1478
1478 All of this will soon be automated as Matplotlib beings to include
1479 All of this will soon be automated as Matplotlib beings to include
1479 new logic that uses our new GUI support.
1480 new logic that uses our new GUI support.
1480
1481
1481 .. _interactive_demos:
1482 .. _interactive_demos:
1482
1483
1483 Interactive demos with IPython
1484 Interactive demos with IPython
1484 ==============================
1485 ==============================
1485
1486
1486 IPython ships with a basic system for running scripts interactively in
1487 IPython ships with a basic system for running scripts interactively in
1487 sections, useful when presenting code to audiences. A few tags embedded
1488 sections, useful when presenting code to audiences. A few tags embedded
1488 in comments (so that the script remains valid Python code) divide a file
1489 in comments (so that the script remains valid Python code) divide a file
1489 into separate blocks, and the demo can be run one block at a time, with
1490 into separate blocks, and the demo can be run one block at a time, with
1490 IPython printing (with syntax highlighting) the block before executing
1491 IPython printing (with syntax highlighting) the block before executing
1491 it, and returning to the interactive prompt after each block. The
1492 it, and returning to the interactive prompt after each block. The
1492 interactive namespace is updated after each block is run with the
1493 interactive namespace is updated after each block is run with the
1493 contents of the demo's namespace.
1494 contents of the demo's namespace.
1494
1495
1495 This allows you to show a piece of code, run it and then execute
1496 This allows you to show a piece of code, run it and then execute
1496 interactively commands based on the variables just created. Once you
1497 interactively commands based on the variables just created. Once you
1497 want to continue, you simply execute the next block of the demo. The
1498 want to continue, you simply execute the next block of the demo. The
1498 following listing shows the markup necessary for dividing a script into
1499 following listing shows the markup necessary for dividing a script into
1499 sections for execution as a demo::
1500 sections for execution as a demo::
1500
1501
1501
1502
1502 """A simple interactive demo to illustrate the use of IPython's Demo class.
1503 """A simple interactive demo to illustrate the use of IPython's Demo class.
1503
1504
1504 Any python script can be run as a demo, but that does little more than showing
1505 Any python script can be run as a demo, but that does little more than showing
1505 it on-screen, syntax-highlighted in one shot. If you add a little simple
1506 it on-screen, syntax-highlighted in one shot. If you add a little simple
1506 markup, you can stop at specified intervals and return to the ipython prompt,
1507 markup, you can stop at specified intervals and return to the ipython prompt,
1507 resuming execution later.
1508 resuming execution later.
1508 """
1509 """
1509
1510
1510 print 'Hello, welcome to an interactive IPython demo.'
1511 print 'Hello, welcome to an interactive IPython demo.'
1511 print 'Executing this block should require confirmation before proceeding,'
1512 print 'Executing this block should require confirmation before proceeding,'
1512 print 'unless auto_all has been set to true in the demo object'
1513 print 'unless auto_all has been set to true in the demo object'
1513
1514
1514 # The mark below defines a block boundary, which is a point where IPython will
1515 # The mark below defines a block boundary, which is a point where IPython will
1515 # stop execution and return to the interactive prompt.
1516 # stop execution and return to the interactive prompt.
1516 # Note that in actual interactive execution,
1517 # Note that in actual interactive execution,
1517 # <demo> --- stop ---
1518 # <demo> --- stop ---
1518
1519
1519 x = 1
1520 x = 1
1520 y = 2
1521 y = 2
1521
1522
1522 # <demo> --- stop ---
1523 # <demo> --- stop ---
1523
1524
1524 # the mark below makes this block as silent
1525 # the mark below makes this block as silent
1525 # <demo> silent
1526 # <demo> silent
1526
1527
1527 print 'This is a silent block, which gets executed but not printed.'
1528 print 'This is a silent block, which gets executed but not printed.'
1528
1529
1529 # <demo> --- stop ---
1530 # <demo> --- stop ---
1530 # <demo> auto
1531 # <demo> auto
1531 print 'This is an automatic block.'
1532 print 'This is an automatic block.'
1532 print 'It is executed without asking for confirmation, but printed.'
1533 print 'It is executed without asking for confirmation, but printed.'
1533 z = x+y
1534 z = x+y
1534
1535
1535 print 'z=',x
1536 print 'z=',x
1536
1537
1537 # <demo> --- stop ---
1538 # <demo> --- stop ---
1538 # This is just another normal block.
1539 # This is just another normal block.
1539 print 'z is now:', z
1540 print 'z is now:', z
1540
1541
1541 print 'bye!'
1542 print 'bye!'
1542
1543
1543 In order to run a file as a demo, you must first make a Demo object out
1544 In order to run a file as a demo, you must first make a Demo object out
1544 of it. If the file is named myscript.py, the following code will make a
1545 of it. If the file is named myscript.py, the following code will make a
1545 demo::
1546 demo::
1546
1547
1547 from IPython.demo import Demo
1548 from IPython.demo import Demo
1548
1549
1549 mydemo = Demo('myscript.py')
1550 mydemo = Demo('myscript.py')
1550
1551
1551 This creates the mydemo object, whose blocks you run one at a time by
1552 This creates the mydemo object, whose blocks you run one at a time by
1552 simply calling the object with no arguments. If you have autocall active
1553 simply calling the object with no arguments. If you have autocall active
1553 in IPython (the default), all you need to do is type::
1554 in IPython (the default), all you need to do is type::
1554
1555
1555 mydemo
1556 mydemo
1556
1557
1557 and IPython will call it, executing each block. Demo objects can be
1558 and IPython will call it, executing each block. Demo objects can be
1558 restarted, you can move forward or back skipping blocks, re-execute the
1559 restarted, you can move forward or back skipping blocks, re-execute the
1559 last block, etc. Simply use the Tab key on a demo object to see its
1560 last block, etc. Simply use the Tab key on a demo object to see its
1560 methods, and call '?' on them to see their docstrings for more usage
1561 methods, and call '?' on them to see their docstrings for more usage
1561 details. In addition, the demo module itself contains a comprehensive
1562 details. In addition, the demo module itself contains a comprehensive
1562 docstring, which you can access via::
1563 docstring, which you can access via::
1563
1564
1564 from IPython import demo
1565 from IPython import demo
1565
1566
1566 demo?
1567 demo?
1567
1568
1568 Limitations: It is important to note that these demos are limited to
1569 Limitations: It is important to note that these demos are limited to
1569 fairly simple uses. In particular, you can not put division marks in
1570 fairly simple uses. In particular, you can not put division marks in
1570 indented code (loops, if statements, function definitions, etc.)
1571 indented code (loops, if statements, function definitions, etc.)
1571 Supporting something like this would basically require tracking the
1572 Supporting something like this would basically require tracking the
1572 internal execution state of the Python interpreter, so only top-level
1573 internal execution state of the Python interpreter, so only top-level
1573 divisions are allowed. If you want to be able to open an IPython
1574 divisions are allowed. If you want to be able to open an IPython
1574 instance at an arbitrary point in a program, you can use IPython's
1575 instance at an arbitrary point in a program, you can use IPython's
1575 embedding facilities, described in detail in Sec. 9
1576 embedding facilities, described in detail in Sec. 9
1576
1577
1577 .. [Matplotlib] Matplotlib. http://matplotlib.sourceforge.net
1578 .. [Matplotlib] Matplotlib. http://matplotlib.sourceforge.net
1578
1579
@@ -1,336 +1,336 b''
1 .. _tutorial:
1 .. _tutorial:
2
2
3 ======================
3 ======================
4 Quick IPython tutorial
4 Quick IPython tutorial
5 ======================
5 ======================
6
6
7 .. warning::
7 .. warning::
8
8
9 As of the 0.11 version of IPython, some of the features and APIs
9 As of the 0.11 version of IPython, some of the features and APIs
10 described in this section have been deprecated or are broken. Our plan
10 described in this section have been deprecated or are broken. Our plan
11 is to continue to support these features, but they need to be updated
11 is to continue to support these features, but they need to be updated
12 to take advantage of recent API changes. Furthermore, this section
12 to take advantage of recent API changes. Furthermore, this section
13 of the documentation need to be updated to reflect all of these changes.
13 of the documentation need to be updated to reflect all of these changes.
14
14
15 IPython can be used as an improved replacement for the Python prompt,
15 IPython can be used as an improved replacement for the Python prompt,
16 and for that you don't really need to read any more of this manual. But
16 and for that you don't really need to read any more of this manual. But
17 in this section we'll try to summarize a few tips on how to make the
17 in this section we'll try to summarize a few tips on how to make the
18 most effective use of it for everyday Python development, highlighting
18 most effective use of it for everyday Python development, highlighting
19 things you might miss in the rest of the manual (which is getting long).
19 things you might miss in the rest of the manual (which is getting long).
20 We'll give references to parts in the manual which provide more detail
20 We'll give references to parts in the manual which provide more detail
21 when appropriate.
21 when appropriate.
22
22
23 The following article by Jeremy Jones provides an introductory tutorial
23 The following article by Jeremy Jones provides an introductory tutorial
24 about IPython: http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html
24 about IPython: http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html
25
25
26 Highlights
26 Highlights
27 ==========
27 ==========
28
28
29 Tab completion
29 Tab completion
30 --------------
30 --------------
31
31
32 TAB-completion, especially for attributes, is a convenient way to explore the
32 TAB-completion, especially for attributes, is a convenient way to explore the
33 structure of any object you're dealing with. Simply type object_name.<TAB> and
33 structure of any object you're dealing with. Simply type object_name.<TAB> and
34 a list of the object's attributes will be printed (see :ref:`the readline
34 a list of the object's attributes will be printed (see :ref:`the readline
35 section <readline>` for more). Tab completion also works on file and directory
35 section <readline>` for more). Tab completion also works on file and directory
36 names, which combined with IPython's alias system allows you to do from within
36 names, which combined with IPython's alias system allows you to do from within
37 IPython many of the things you normally would need the system shell for.
37 IPython many of the things you normally would need the system shell for.
38
38
39 Explore your objects
39 Explore your objects
40 --------------------
40 --------------------
41
41
42 Typing object_name? will print all sorts of details about any object,
42 Typing object_name? will print all sorts of details about any object,
43 including docstrings, function definition lines (for call arguments) and
43 including docstrings, function definition lines (for call arguments) and
44 constructor details for classes. The magic commands %pdoc, %pdef, %psource
44 constructor details for classes. The magic commands %pdoc, %pdef, %psource
45 and %pfile will respectively print the docstring, function definition line,
45 and %pfile will respectively print the docstring, function definition line,
46 full source code and the complete file for any object (when they can be
46 full source code and the complete file for any object (when they can be
47 found). If automagic is on (it is by default), you don't need to type the '%'
47 found). If automagic is on (it is by default), you don't need to type the '%'
48 explicitly. See :ref:`this section <dynamic_object_info>` for more.
48 explicitly. See :ref:`this section <dynamic_object_info>` for more.
49
49
50 The `%run` magic command
50 The `%run` magic command
51 ------------------------
51 ------------------------
52
52
53 The %run magic command allows you to run any python script and load all of its
53 The %run magic command allows you to run any python script and load all of its
54 data directly into the interactive namespace. Since the file is re-read from
54 data directly into the interactive namespace. Since the file is re-read from
55 disk each time, changes you make to it are reflected immediately (in contrast
55 disk each time, changes you make to it are reflected immediately (in contrast
56 to the behavior of import). I rarely use import for code I am testing, relying
56 to the behavior of import). I rarely use import for code I am testing, relying
57 on %run instead. See :ref:`this section <magic>` for more on this and other
57 on %run instead. See :ref:`this section <magic>` for more on this and other
58 magic commands, or type the name of any magic command and ? to get details on
58 magic commands, or type the name of any magic command and ? to get details on
59 it. See also :ref:`this section <dreload>` for a recursive reload command. %run
59 it. See also :ref:`this section <dreload>` for a recursive reload command. %run
60 also has special flags for timing the execution of your scripts (-t) and for
60 also has special flags for timing the execution of your scripts (-t) and for
61 executing them under the control of either Python's pdb debugger (-d) or
61 executing them under the control of either Python's pdb debugger (-d) or
62 profiler (-p). With all of these, %run can be used as the main tool for
62 profiler (-p). With all of these, %run can be used as the main tool for
63 efficient interactive development of code which you write in your editor of
63 efficient interactive development of code which you write in your editor of
64 choice.
64 choice.
65
65
66 Debug a Python script
66 Debug a Python script
67 ---------------------
67 ---------------------
68
68
69 Use the Python debugger, pdb. The %pdb command allows you to toggle on and off
69 Use the Python debugger, pdb. The %pdb command allows you to toggle on and off
70 the automatic invocation of an IPython-enhanced pdb debugger (with coloring,
70 the automatic invocation of an IPython-enhanced pdb debugger (with coloring,
71 tab completion and more) at any uncaught exception. The advantage of this is
71 tab completion and more) at any uncaught exception. The advantage of this is
72 that pdb starts inside the function where the exception occurred, with all data
72 that pdb starts inside the function where the exception occurred, with all data
73 still available. You can print variables, see code, execute statements and even
73 still available. You can print variables, see code, execute statements and even
74 walk up and down the call stack to track down the true source of the problem
74 walk up and down the call stack to track down the true source of the problem
75 (which often is many layers in the stack above where the exception gets
75 (which often is many layers in the stack above where the exception gets
76 triggered). Running programs with %run and pdb active can be an efficient to
76 triggered). Running programs with %run and pdb active can be an efficient to
77 develop and debug code, in many cases eliminating the need for print statements
77 develop and debug code, in many cases eliminating the need for print statements
78 or external debugging tools. I often simply put a 1/0 in a place where I want
78 or external debugging tools. I often simply put a 1/0 in a place where I want
79 to take a look so that pdb gets called, quickly view whatever variables I need
79 to take a look so that pdb gets called, quickly view whatever variables I need
80 to or test various pieces of code and then remove the 1/0. Note also that '%run
80 to or test various pieces of code and then remove the 1/0. Note also that '%run
81 -d' activates pdb and automatically sets initial breakpoints for you to step
81 -d' activates pdb and automatically sets initial breakpoints for you to step
82 through your code, watch variables, etc. The :ref:`output caching section
82 through your code, watch variables, etc. The :ref:`output caching section
83 <output_caching>` has more details.
83 <output_caching>` has more details.
84
84
85 Use the output cache
85 Use the output cache
86 --------------------
86 --------------------
87
87
88 All output results are automatically stored in a global dictionary named Out
88 All output results are automatically stored in a global dictionary named Out
89 and variables named _1, _2, etc. alias them. For example, the result of input
89 and variables named _1, _2, etc. alias them. For example, the result of input
90 line 4 is available either as Out[4] or as _4. Additionally, three variables
90 line 4 is available either as Out[4] or as _4. Additionally, three variables
91 named _, __ and ___ are always kept updated with the for the last three
91 named _, __ and ___ are always kept updated with the for the last three
92 results. This allows you to recall any previous result and further use it for
92 results. This allows you to recall any previous result and further use it for
93 new calculations. See :ref:`the output caching section <output_caching>` for
93 new calculations. See :ref:`the output caching section <output_caching>` for
94 more.
94 more.
95
95
96 Suppress output
96 Suppress output
97 ---------------
97 ---------------
98
98
99 Put a ';' at the end of a line to suppress the printing of output. This is
99 Put a ';' at the end of a line to suppress the printing of output. This is
100 useful when doing calculations which generate long output you are not
100 useful when doing calculations which generate long output you are not
101 interested in seeing. The _* variables and the Out[] list do get updated with
101 interested in seeing. The _* variables and the Out[] list do get updated with
102 the contents of the output, even if it is not printed. You can thus still
102 the contents of the output, even if it is not printed. You can thus still
103 access the generated results this way for further processing.
103 access the generated results this way for further processing.
104
104
105 Input cache
105 Input cache
106 -----------
106 -----------
107
107
108 A similar system exists for caching input. All input is stored in a global
108 A similar system exists for caching input. All input is stored in a global
109 list called In , so you can re-execute lines 22 through 28 plus line 34 by
109 list called In , so you can re-execute lines 22 through 28 plus line 34 by
110 typing 'exec In[22:29]+In[34]' (using Python slicing notation). If you need
110 typing 'exec In[22:29]+In[34]' (using Python slicing notation). If you need
111 to execute the same set of lines often, you can assign them to a macro with
111 to execute the same set of lines often, you can assign them to a macro with
112 the %macro function. See :ref:`here <input_caching>` for more.
112 the %macro function. See :ref:`here <input_caching>` for more.
113
113
114 Use your input history
114 Use your input history
115 ----------------------
115 ----------------------
116
116
117 The %hist command can show you all previous input, without line numbers if
117 The %hist command can show you all previous input, without line numbers if
118 desired (option -n) so you can directly copy and paste code either back in
118 desired (option -n) so you can directly copy and paste code either back in
119 IPython or in a text editor. You can also save all your history by turning on
119 IPython or in a text editor. You can also save all your history by turning on
120 logging via %logstart; these logs can later be either reloaded as IPython
120 logging via %logstart; these logs can later be either reloaded as IPython
121 sessions or used as code for your programs.
121 sessions or used as code for your programs.
122
122
123 In particular, note taht the %rep magic function can repeat a command or get a
123 In particular, note taht the %rep magic function can repeat a command or get a
124 command to the input line for further editing::
124 command to the input line for further editing::
125
125
126 $ l = ["hei", "vaan"]
126 $ l = ["hei", "vaan"]
127 $ "".join(l)
127 $ "".join(l)
128 ==> heivaan
128 ==> heivaan
129 $ %rep
129 $ %rep
130 $ heivaan_ <== cursor blinking
130 $ heivaan_ <== cursor blinking
131
131
132 For more details, type ``%rep?`` as usual.
132 For more details, type ``%rep?`` as usual.
133
133
134 Define your own system aliases
134 Define your own system aliases
135 ------------------------------
135 ------------------------------
136
136
137 Even though IPython gives you access to your system shell via the ! prefix,
137 Even though IPython gives you access to your system shell via the ! prefix,
138 it is convenient to have aliases to the system commands you use most often.
138 it is convenient to have aliases to the system commands you use most often.
139 This allows you to work seamlessly from inside IPython with the same commands
139 This allows you to work seamlessly from inside IPython with the same commands
140 you are used to in your system shell. IPython comes with some pre-defined
140 you are used to in your system shell. IPython comes with some pre-defined
141 aliases and a complete system for changing directories, both via a stack (see
141 aliases and a complete system for changing directories, both via a stack (see
142 %pushd, %popd and %dhist) and via direct %cd. The latter keeps a history of
142 %pushd, %popd and %dhist) and via direct %cd. The latter keeps a history of
143 visited directories and allows you to go to any previously visited one.
143 visited directories and allows you to go to any previously visited one.
144
144
145 Call system shell commands
145 Call system shell commands
146 --------------------------
146 --------------------------
147
147
148 Use Python to manipulate the results of system commands. The '!!' special
148 Use Python to manipulate the results of system commands. The '!!' special
149 syntax, and the %sc and %sx magic commands allow you to capture system output
149 syntax, and the %sc and %sx magic commands allow you to capture system output
150 into Python variables.
150 into Python variables.
151
151
152 Use Python variables when calling the shell
152 Use Python variables when calling the shell
153 -------------------------------------------
153 -------------------------------------------
154
154
155 Expand python variables when calling the shell (either via '!' and '!!' or via
155 Expand python variables when calling the shell (either via '!' and '!!' or via
156 aliases) by prepending a $ in front of them. You can also expand complete
156 aliases) by prepending a $ in front of them. You can also expand complete
157 python expressions. See :ref:`our shell section <system_shell_access>` for
157 python expressions. See :ref:`our shell section <system_shell_access>` for
158 more details.
158 more details.
159
159
160 Use profiles
160 Use profiles
161 ------------
161 ------------
162
162
163 Use profiles to maintain different configurations (modules to load, function
163 Use profiles to maintain different configurations (modules to load, function
164 definitions, option settings) for particular tasks. You can then have
164 definitions, option settings) for particular tasks. You can then have
165 customized versions of IPython for specific purposes. :ref:`This section
165 customized versions of IPython for specific purposes. :ref:`This section
166 <profiles>` has more details.
166 <profiles>` has more details.
167
167
168
168
169 Embed IPython in your programs
169 Embed IPython in your programs
170 ------------------------------
170 ------------------------------
171
171
172 A few lines of code are enough to load a complete IPython inside your own
172 A few lines of code are enough to load a complete IPython inside your own
173 programs, giving you the ability to work with your data interactively after
173 programs, giving you the ability to work with your data interactively after
174 automatic processing has been completed. See :ref:`here <embedding>` for more.
174 automatic processing has been completed. See :ref:`here <embedding>` for more.
175
175
176 Use the Python profiler
176 Use the Python profiler
177 -----------------------
177 -----------------------
178
178
179 When dealing with performance issues, the %run command with a -p option
179 When dealing with performance issues, the %run command with a -p option
180 allows you to run complete programs under the control of the Python profiler.
180 allows you to run complete programs under the control of the Python profiler.
181 The %prun command does a similar job for single Python expressions (like
181 The %prun command does a similar job for single Python expressions (like
182 function calls).
182 function calls).
183
183
184 Use IPython to present interactive demos
184 Use IPython to present interactive demos
185 ----------------------------------------
185 ----------------------------------------
186
186
187 Use the IPython.demo.Demo class to load any Python script as an interactive
187 Use the IPython.demo.Demo class to load any Python script as an interactive
188 demo. With a minimal amount of simple markup, you can control the execution of
188 demo. With a minimal amount of simple markup, you can control the execution of
189 the script, stopping as needed. See :ref:`here <interactive_demos>` for more.
189 the script, stopping as needed. See :ref:`here <interactive_demos>` for more.
190
190
191 Run doctests
191 Run doctests
192 ------------
192 ------------
193
193
194 Run your doctests from within IPython for development and debugging. The
194 Run your doctests from within IPython for development and debugging. The
195 special %doctest_mode command toggles a mode where the prompt, output and
195 special %doctest_mode command toggles a mode where the prompt, output and
196 exceptions display matches as closely as possible that of the default Python
196 exceptions display matches as closely as possible that of the default Python
197 interpreter. In addition, this mode allows you to directly paste in code that
197 interpreter. In addition, this mode allows you to directly paste in code that
198 contains leading '>>>' prompts, even if they have extra leading whitespace
198 contains leading '>>>' prompts, even if they have extra leading whitespace
199 (as is common in doctest files). This combined with the '%history -tn' call
199 (as is common in doctest files). This combined with the '%history -tn' call
200 to see your translated history (with these extra prompts removed and no line
200 to see your translated history (with these extra prompts removed and no line
201 numbers) allows for an easy doctest workflow, where you can go from doctest
201 numbers) allows for an easy doctest workflow, where you can go from doctest
202 to interactive execution to pasting into valid Python code as needed.
202 to interactive execution to pasting into valid Python code as needed.
203
203
204 Source code handling tips
204 Source code handling tips
205 =========================
205 =========================
206
206
207 IPython is a line-oriented program, without full control of the
207 IPython is a line-oriented program, without full control of the
208 terminal. Therefore, it doesn't support true multiline editing. However,
208 terminal. Therefore, it doesn't support true multiline editing. However,
209 it has a number of useful tools to help you in dealing effectively with
209 it has a number of useful tools to help you in dealing effectively with
210 more complex editing.
210 more complex editing.
211
211
212 The %edit command gives a reasonable approximation of multiline editing,
212 The %edit command gives a reasonable approximation of multiline editing,
213 by invoking your favorite editor on the spot. IPython will execute the
213 by invoking your favorite editor on the spot. IPython will execute the
214 code you type in there as if it were typed interactively. Type %edit?
214 code you type in there as if it were typed interactively. Type %edit?
215 for the full details on the edit command.
215 for the full details on the edit command.
216
216
217 If you have typed various commands during a session, which you'd like to
217 If you have typed various commands during a session, which you'd like to
218 reuse, IPython provides you with a number of tools. Start by using %hist
218 reuse, IPython provides you with a number of tools. Start by using %hist
219 to see your input history, so you can see the line numbers of all input.
219 to see your input history, so you can see the line numbers of all input.
220 Let us say that you'd like to reuse lines 10 through 20, plus lines 24
220 Let us say that you'd like to reuse lines 10 through 20, plus lines 24
221 and 28. All the commands below can operate on these with the syntax::
221 and 28. All the commands below can operate on these with the syntax::
222
222
223 %command 10-20 24 28
223 %command 10-20 24 28
224
224
225 where the command given can be:
225 where the command given can be:
226
226
227 * %macro <macroname>: this stores the lines into a variable which,
227 * %macro <macroname>: this stores the lines into a variable which,
228 when called at the prompt, re-executes the input. Macros can be
228 when called at the prompt, re-executes the input. Macros can be
229 edited later using '%edit macroname', and they can be stored
229 edited later using '%edit macroname', and they can be stored
230 persistently across sessions with '%store macroname' (the storage
230 persistently across sessions with '%store macroname' (the storage
231 system is per-profile). The combination of quick macros,
231 system is per-profile). The combination of quick macros,
232 persistent storage and editing, allows you to easily refine
232 persistent storage and editing, allows you to easily refine
233 quick-and-dirty interactive input into permanent utilities, always
233 quick-and-dirty interactive input into permanent utilities, always
234 available both in IPython and as files for general reuse.
234 available both in IPython and as files for general reuse.
235 * %edit: this will open a text editor with those lines pre-loaded
235 * %edit: this will open a text editor with those lines pre-loaded
236 for further modification. It will then execute the resulting
236 for further modification. It will then execute the resulting
237 file's contents as if you had typed it at the prompt.
237 file's contents as if you had typed it at the prompt.
238 * %save <filename>: this saves the lines directly to a named file on
238 * %save <filename>: this saves the lines directly to a named file on
239 disk.
239 disk.
240
240
241 While %macro saves input lines into memory for interactive re-execution,
241 While %macro saves input lines into memory for interactive re-execution,
242 sometimes you'd like to save your input directly to a file. The %save
242 sometimes you'd like to save your input directly to a file. The %save
243 magic does this: its input sytnax is the same as %macro, but it saves
243 magic does this: its input sytnax is the same as %macro, but it saves
244 your input directly to a Python file. Note that the %logstart command
244 your input directly to a Python file. Note that the %logstart command
245 also saves input, but it logs all input to disk (though you can
245 also saves input, but it logs all input to disk (though you can
246 temporarily suspend it and reactivate it with %logoff/%logon); %save
246 temporarily suspend it and reactivate it with %logoff/%logon); %save
247 allows you to select which lines of input you need to save.
247 allows you to select which lines of input you need to save.
248
248
249
249
250 Lightweight 'version control'
250 Lightweight 'version control'
251 =============================
251 =============================
252
252
253 When you call %edit with no arguments, IPython opens an empty editor
253 When you call %edit with no arguments, IPython opens an empty editor
254 with a temporary file, and it returns the contents of your editing
254 with a temporary file, and it returns the contents of your editing
255 session as a string variable. Thanks to IPython's output caching
255 session as a string variable. Thanks to IPython's output caching
256 mechanism, this is automatically stored::
256 mechanism, this is automatically stored::
257
257
258 In [1]: %edit
258 In [1]: %edit
259
259
260 IPython will make a temporary file named: /tmp/ipython_edit_yR-HCN.py
260 IPython will make a temporary file named: /tmp/ipython_edit_yR-HCN.py
261
261
262 Editing... done. Executing edited code...
262 Editing... done. Executing edited code...
263
263
264 hello - this is a temporary file
264 hello - this is a temporary file
265
265
266 Out[1]: "print 'hello - this is a temporary file'\n"
266 Out[1]: "print 'hello - this is a temporary file'\n"
267
267
268 Now, if you call '%edit -p', IPython tries to open an editor with the
268 Now, if you call '%edit -p', IPython tries to open an editor with the
269 same data as the last time you used %edit. So if you haven't used %edit
269 same data as the last time you used %edit. So if you haven't used %edit
270 in the meantime, this same contents will reopen; however, it will be
270 in the meantime, this same contents will reopen; however, it will be
271 done in a new file. This means that if you make changes and you later
271 done in a new file. This means that if you make changes and you later
272 want to find an old version, you can always retrieve it by using its
272 want to find an old version, you can always retrieve it by using its
273 output number, via '%edit _NN', where NN is the number of the output
273 output number, via '%edit _NN', where NN is the number of the output
274 prompt.
274 prompt.
275
275
276 Continuing with the example above, this should illustrate this idea::
276 Continuing with the example above, this should illustrate this idea::
277
277
278 In [2]: edit -p
278 In [2]: edit -p
279
279
280 IPython will make a temporary file named: /tmp/ipython_edit_nA09Qk.py
280 IPython will make a temporary file named: /tmp/ipython_edit_nA09Qk.py
281
281
282 Editing... done. Executing edited code...
282 Editing... done. Executing edited code...
283
283
284 hello - now I made some changes
284 hello - now I made some changes
285
285
286 Out[2]: "print 'hello - now I made some changes'\n"
286 Out[2]: "print 'hello - now I made some changes'\n"
287
287
288 In [3]: edit _1
288 In [3]: edit _1
289
289
290 IPython will make a temporary file named: /tmp/ipython_edit_gy6-zD.py
290 IPython will make a temporary file named: /tmp/ipython_edit_gy6-zD.py
291
291
292 Editing... done. Executing edited code...
292 Editing... done. Executing edited code...
293
293
294 hello - this is a temporary file
294 hello - this is a temporary file
295
295
296 IPython version control at work :)
296 IPython version control at work :)
297
297
298 Out[3]: "print 'hello - this is a temporary file'\nprint 'IPython version control at work :)'\n"
298 Out[3]: "print 'hello - this is a temporary file'\nprint 'IPython version control at work :)'\n"
299
299
300
300
301 This section was written after a contribution by Alexander Belchenko on
301 This section was written after a contribution by Alexander Belchenko on
302 the IPython user list.
302 the IPython user list.
303
303
304
304
305 Effective logging
305 Effective logging
306 =================
306 =================
307
307
308 A very useful suggestion sent in by Robert Kern follows:
308 A very useful suggestion sent in by Robert Kern follows:
309
309
310 I recently happened on a nifty way to keep tidy per-project log files. I
310 I recently happened on a nifty way to keep tidy per-project log files. I
311 made a profile for my project (which is called "parkfield")::
311 made a profile for my project (which is called "parkfield")::
312
312
313 include ipythonrc
313 include ipythonrc
314
314
315 # cancel earlier logfile invocation:
315 # cancel earlier logfile invocation:
316
316
317 logfile ''
317 logfile ''
318
318
319 execute import time
319 execute import time
320
320
321 execute __cmd = '/Users/kern/research/logfiles/parkfield-%s.log rotate'
321 execute __cmd = '/Users/kern/research/logfiles/parkfield-%s.log rotate'
322
322
323 execute __IP.magic_logstart(__cmd % time.strftime('%Y-%m-%d'))
323 execute __IP.magic_logstart(__cmd % time.strftime('%Y-%m-%d'))
324
324
325 I also added a shell alias for convenience::
325 I also added a shell alias for convenience::
326
326
327 alias parkfield="ipython -pylab -profile parkfield"
327 alias parkfield="ipython --pylab profile=parkfield"
328
328
329 Now I have a nice little directory with everything I ever type in,
329 Now I have a nice little directory with everything I ever type in,
330 organized by project and date.
330 organized by project and date.
331
331
332 Contribute your own: If you have your own favorite tip on using IPython
332 Contribute your own: If you have your own favorite tip on using IPython
333 efficiently for a certain task (especially things which can't be done in
333 efficiently for a certain task (especially things which can't be done in
334 the normal Python interpreter), don't hesitate to send it!
334 the normal Python interpreter), don't hesitate to send it!
335
335
336
336
General Comments 0
You need to be logged in to leave comments. Login now