##// END OF EJS Templates
Update doc references to .config/ipython
Thomas Kluyver -
Show More
@@ -1,535 +1,531 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.
7 This section describes the IPython configuration system.
8
8
9 The following discussion is for users who want to configure
9 The following discussion is for users who want to configure
10 IPython to their liking. Developers who want to know how they can
10 IPython to their liking. Developers who want to know how they can
11 enable their objects to take advantage of the configuration system
11 enable their objects to take advantage of the configuration system
12 should consult the :ref:`developer guide <developer_guide>`
12 should consult the :ref:`developer guide <developer_guide>`
13
13
14 The main concepts
14 The main concepts
15 =================
15 =================
16
16
17 There are a number of abstractions that the IPython configuration system uses.
17 There are a number of abstractions that the IPython configuration system uses.
18 Each of these abstractions is represented by a Python class.
18 Each of these abstractions is represented by a Python class.
19
19
20 Configuration object: :class:`~IPython.config.loader.Config`
20 Configuration object: :class:`~IPython.config.loader.Config`
21 A configuration object is a simple dictionary-like class that holds
21 A configuration object is a simple dictionary-like class that holds
22 configuration attributes and sub-configuration objects. These classes
22 configuration attributes and sub-configuration objects. These classes
23 support dotted attribute style access (``Foo.bar``) in addition to the
23 support dotted attribute style access (``Foo.bar``) in addition to the
24 regular dictionary style access (``Foo['bar']``). Configuration objects
24 regular dictionary style access (``Foo['bar']``). Configuration objects
25 are smart. They know how to merge themselves with other configuration
25 are smart. They know how to merge themselves with other configuration
26 objects and they automatically create sub-configuration objects.
26 objects and they automatically create sub-configuration objects.
27
27
28 Application: :class:`~IPython.config.application.Application`
28 Application: :class:`~IPython.config.application.Application`
29 An application is a process that does a specific job. The most obvious
29 An application is a process that does a specific job. The most obvious
30 application is the :command:`ipython` command line program. Each
30 application is the :command:`ipython` command line program. Each
31 application reads *one or more* configuration files and a single set of
31 application reads *one or more* configuration files and a single set of
32 command line options
32 command line options
33 and then produces a master configuration object for the application. This
33 and then produces a master configuration object for the application. This
34 configuration object is then passed to the configurable objects that the
34 configuration object is then passed to the configurable objects that the
35 application creates. These configurable objects implement the actual logic
35 application creates. These configurable objects implement the actual logic
36 of the application and know how to configure themselves given the
36 of the application and know how to configure themselves given the
37 configuration object.
37 configuration object.
38
38
39 Applications always have a `log` attribute that is a configured Logger.
39 Applications always have a `log` attribute that is a configured Logger.
40 This allows centralized logging configuration per-application.
40 This allows centralized logging configuration per-application.
41
41
42 Configurable: :class:`~IPython.config.configurable.Configurable`
42 Configurable: :class:`~IPython.config.configurable.Configurable`
43 A configurable is a regular Python class that serves as a base class for
43 A configurable is a regular Python class that serves as a base class for
44 all main classes in an application. The
44 all main classes in an application. The
45 :class:`~IPython.config.configurable.Configurable` base class is
45 :class:`~IPython.config.configurable.Configurable` base class is
46 lightweight and only does one things.
46 lightweight and only does one things.
47
47
48 This :class:`~IPython.config.configurable.Configurable` is a subclass
48 This :class:`~IPython.config.configurable.Configurable` is a subclass
49 of :class:`~IPython.utils.traitlets.HasTraits` that knows how to configure
49 of :class:`~IPython.utils.traitlets.HasTraits` that knows how to configure
50 itself. Class level traits with the metadata ``config=True`` become
50 itself. Class level traits with the metadata ``config=True`` become
51 values that can be configured from the command line and configuration
51 values that can be configured from the command line and configuration
52 files.
52 files.
53
53
54 Developers create :class:`~IPython.config.configurable.Configurable`
54 Developers create :class:`~IPython.config.configurable.Configurable`
55 subclasses that implement all of the logic in the application. Each of
55 subclasses that implement all of the logic in the application. Each of
56 these subclasses has its own configuration information that controls how
56 these subclasses has its own configuration information that controls how
57 instances are created.
57 instances are created.
58
58
59 Singletons: :class:`~IPython.config.configurable.SingletonConfigurable`
59 Singletons: :class:`~IPython.config.configurable.SingletonConfigurable`
60 Any object for which there is a single canonical instance. These are
60 Any object for which there is a single canonical instance. These are
61 just like Configurables, except they have a class method
61 just like Configurables, except they have a class method
62 :meth:`~IPython.config.configurable.SingletonConfigurable.instance`,
62 :meth:`~IPython.config.configurable.SingletonConfigurable.instance`,
63 that returns the current active instance (or creates one if it
63 that returns the current active instance (or creates one if it
64 does not exist). Examples of singletons include
64 does not exist). Examples of singletons include
65 :class:`~IPython.config.application.Application`s and
65 :class:`~IPython.config.application.Application`s and
66 :class:`~IPython.core.interactiveshell.InteractiveShell`. This lets
66 :class:`~IPython.core.interactiveshell.InteractiveShell`. This lets
67 objects easily connect to the current running Application without passing
67 objects easily connect to the current running Application without passing
68 objects around everywhere. For instance, to get the current running
68 objects around everywhere. For instance, to get the current running
69 Application instance, simply do: ``app = Application.instance()``.
69 Application instance, simply do: ``app = Application.instance()``.
70
70
71
71
72 .. note::
72 .. note::
73
73
74 Singletons are not strictly enforced - you can have many instances
74 Singletons are not strictly enforced - you can have many instances
75 of a given singleton class, but the :meth:`instance` method will always
75 of a given singleton class, but the :meth:`instance` method will always
76 return the same one.
76 return the same one.
77
77
78 Having described these main concepts, we can now state the main idea in our
78 Having described these main concepts, we can now state the main idea in our
79 configuration system: *"configuration" allows the default values of class
79 configuration system: *"configuration" allows the default values of class
80 attributes to be controlled on a class by class basis*. Thus all instances of
80 attributes to be controlled on a class by class basis*. Thus all instances of
81 a given class are configured in the same way. Furthermore, if two instances
81 a given class are configured in the same way. Furthermore, if two instances
82 need to be configured differently, they need to be instances of two different
82 need to be configured differently, they need to be instances of two different
83 classes. While this model may seem a bit restrictive, we have found that it
83 classes. While this model may seem a bit restrictive, we have found that it
84 expresses most things that need to be configured extremely well. However, it
84 expresses most things that need to be configured extremely well. However, it
85 is possible to create two instances of the same class that have different
85 is possible to create two instances of the same class that have different
86 trait values. This is done by overriding the configuration.
86 trait values. This is done by overriding the configuration.
87
87
88 Now, we show what our configuration objects and files look like.
88 Now, we show what our configuration objects and files look like.
89
89
90 Configuration objects and files
90 Configuration objects and files
91 ===============================
91 ===============================
92
92
93 A configuration file is simply a pure Python file that sets the attributes
93 A configuration file is simply a pure Python file that sets the attributes
94 of a global, pre-created configuration object. This configuration object is a
94 of a global, pre-created configuration object. This configuration object is a
95 :class:`~IPython.config.loader.Config` instance. While in a configuration
95 :class:`~IPython.config.loader.Config` instance. While in a configuration
96 file, to get a reference to this object, simply call the :func:`get_config`
96 file, to get a reference to this object, simply call the :func:`get_config`
97 function. We inject this function into the global namespace that the
97 function. We inject this function into the global namespace that the
98 configuration file is executed in.
98 configuration file is executed in.
99
99
100 Here is an example of a super simple configuration file that does nothing::
100 Here is an example of a super simple configuration file that does nothing::
101
101
102 c = get_config()
102 c = get_config()
103
103
104 Once you get a reference to the configuration object, you simply set
104 Once you get a reference to the configuration object, you simply set
105 attributes on it. All you have to know is:
105 attributes on it. All you have to know is:
106
106
107 * The name of each attribute.
107 * The name of each attribute.
108 * The type of each attribute.
108 * The type of each attribute.
109
109
110 The answers to these two questions are provided by the various
110 The answers to these two questions are provided by the various
111 :class:`~IPython.config.configurable.Configurable` subclasses that an
111 :class:`~IPython.config.configurable.Configurable` subclasses that an
112 application uses. Let's look at how this would work for a simple configurable
112 application uses. Let's look at how this would work for a simple configurable
113 subclass::
113 subclass::
114
114
115 # Sample configurable:
115 # Sample configurable:
116 from IPython.config.configurable import Configurable
116 from IPython.config.configurable import Configurable
117 from IPython.utils.traitlets import Int, Float, Unicode, Bool
117 from IPython.utils.traitlets import Int, Float, Unicode, Bool
118
118
119 class MyClass(Configurable):
119 class MyClass(Configurable):
120 name = Unicode(u'defaultname', config=True)
120 name = Unicode(u'defaultname', config=True)
121 ranking = Int(0, config=True)
121 ranking = Int(0, config=True)
122 value = Float(99.0)
122 value = Float(99.0)
123 # The rest of the class implementation would go here..
123 # The rest of the class implementation would go here..
124
124
125 In this example, we see that :class:`MyClass` has three attributes, two
125 In this example, we see that :class:`MyClass` has three attributes, two
126 of whom (``name``, ``ranking``) can be configured. All of the attributes
126 of whom (``name``, ``ranking``) can be configured. All of the attributes
127 are given types and default values. If a :class:`MyClass` is instantiated,
127 are given types and default values. If a :class:`MyClass` is instantiated,
128 but not configured, these default values will be used. But let's see how
128 but not configured, these default values will be used. But let's see how
129 to configure this class in a configuration file::
129 to configure this class in a configuration file::
130
130
131 # Sample config file
131 # Sample config file
132 c = get_config()
132 c = get_config()
133
133
134 c.MyClass.name = 'coolname'
134 c.MyClass.name = 'coolname'
135 c.MyClass.ranking = 10
135 c.MyClass.ranking = 10
136
136
137 After this configuration file is loaded, the values set in it will override
137 After this configuration file is loaded, the values set in it will override
138 the class defaults anytime a :class:`MyClass` is created. Furthermore,
138 the class defaults anytime a :class:`MyClass` is created. Furthermore,
139 these attributes will be type checked and validated anytime they are set.
139 these attributes will be type checked and validated anytime they are set.
140 This type checking is handled by the :mod:`IPython.utils.traitlets` module,
140 This type checking is handled by the :mod:`IPython.utils.traitlets` module,
141 which provides the :class:`Unicode`, :class:`Int` and :class:`Float` types.
141 which provides the :class:`Unicode`, :class:`Int` and :class:`Float` types.
142 In addition to these traitlets, the :mod:`IPython.utils.traitlets` provides
142 In addition to these traitlets, the :mod:`IPython.utils.traitlets` provides
143 traitlets for a number of other types.
143 traitlets for a number of other types.
144
144
145 .. note::
145 .. note::
146
146
147 Underneath the hood, the :class:`Configurable` base class is a subclass of
147 Underneath the hood, the :class:`Configurable` base class is a subclass of
148 :class:`IPython.utils.traitlets.HasTraits`. The
148 :class:`IPython.utils.traitlets.HasTraits`. The
149 :mod:`IPython.utils.traitlets` module is a lightweight version of
149 :mod:`IPython.utils.traitlets` module is a lightweight version of
150 :mod:`enthought.traits`. Our implementation is a pure Python subset
150 :mod:`enthought.traits`. Our implementation is a pure Python subset
151 (mostly API compatible) of :mod:`enthought.traits` that does not have any
151 (mostly API compatible) of :mod:`enthought.traits` that does not have any
152 of the automatic GUI generation capabilities. Our plan is to achieve 100%
152 of the automatic GUI generation capabilities. Our plan is to achieve 100%
153 API compatibility to enable the actual :mod:`enthought.traits` to
153 API compatibility to enable the actual :mod:`enthought.traits` to
154 eventually be used instead. Currently, we cannot use
154 eventually be used instead. Currently, we cannot use
155 :mod:`enthought.traits` as we are committed to the core of IPython being
155 :mod:`enthought.traits` as we are committed to the core of IPython being
156 pure Python.
156 pure Python.
157
157
158 It should be very clear at this point what the naming convention is for
158 It should be very clear at this point what the naming convention is for
159 configuration attributes::
159 configuration attributes::
160
160
161 c.ClassName.attribute_name = attribute_value
161 c.ClassName.attribute_name = attribute_value
162
162
163 Here, ``ClassName`` is the name of the class whose configuration attribute you
163 Here, ``ClassName`` is the name of the class whose configuration attribute you
164 want to set, ``attribute_name`` is the name of the attribute you want to set
164 want to set, ``attribute_name`` is the name of the attribute you want to set
165 and ``attribute_value`` the the value you want it to have. The ``ClassName``
165 and ``attribute_value`` the the value you want it to have. The ``ClassName``
166 attribute of ``c`` is not the actual class, but instead is another
166 attribute of ``c`` is not the actual class, but instead is another
167 :class:`~IPython.config.loader.Config` instance.
167 :class:`~IPython.config.loader.Config` instance.
168
168
169 .. note::
169 .. note::
170
170
171 The careful reader may wonder how the ``ClassName`` (``MyClass`` in
171 The careful reader may wonder how the ``ClassName`` (``MyClass`` in
172 the above example) attribute of the configuration object ``c`` gets
172 the above example) attribute of the configuration object ``c`` gets
173 created. These attributes are created on the fly by the
173 created. These attributes are created on the fly by the
174 :class:`~IPython.config.loader.Config` instance, using a simple naming
174 :class:`~IPython.config.loader.Config` instance, using a simple naming
175 convention. Any attribute of a :class:`~IPython.config.loader.Config`
175 convention. Any attribute of a :class:`~IPython.config.loader.Config`
176 instance whose name begins with an uppercase character is assumed to be a
176 instance whose name begins with an uppercase character is assumed to be a
177 sub-configuration and a new empty :class:`~IPython.config.loader.Config`
177 sub-configuration and a new empty :class:`~IPython.config.loader.Config`
178 instance is dynamically created for that attribute. This allows deeply
178 instance is dynamically created for that attribute. This allows deeply
179 hierarchical information created easily (``c.Foo.Bar.value``) on the fly.
179 hierarchical information created easily (``c.Foo.Bar.value``) on the fly.
180
180
181 Configuration files inheritance
181 Configuration files inheritance
182 ===============================
182 ===============================
183
183
184 Let's say you want to have different configuration files for various purposes.
184 Let's say you want to have different configuration files for various purposes.
185 Our configuration system makes it easy for one configuration file to inherit
185 Our configuration system makes it easy for one configuration file to inherit
186 the information in another configuration file. The :func:`load_subconfig`
186 the information in another configuration file. The :func:`load_subconfig`
187 command can be used in a configuration file for this purpose. Here is a simple
187 command can be used in a configuration file for this purpose. Here is a simple
188 example that loads all of the values from the file :file:`base_config.py`::
188 example that loads all of the values from the file :file:`base_config.py`::
189
189
190 # base_config.py
190 # base_config.py
191 c = get_config()
191 c = get_config()
192 c.MyClass.name = 'coolname'
192 c.MyClass.name = 'coolname'
193 c.MyClass.ranking = 100
193 c.MyClass.ranking = 100
194
194
195 into the configuration file :file:`main_config.py`::
195 into the configuration file :file:`main_config.py`::
196
196
197 # main_config.py
197 # main_config.py
198 c = get_config()
198 c = get_config()
199
199
200 # Load everything from base_config.py
200 # Load everything from base_config.py
201 load_subconfig('base_config.py')
201 load_subconfig('base_config.py')
202
202
203 # Now override one of the values
203 # Now override one of the values
204 c.MyClass.name = 'bettername'
204 c.MyClass.name = 'bettername'
205
205
206 In a situation like this the :func:`load_subconfig` makes sure that the
206 In a situation like this the :func:`load_subconfig` makes sure that the
207 search path for sub-configuration files is inherited from that of the parent.
207 search path for sub-configuration files is inherited from that of the parent.
208 Thus, you can typically put the two in the same directory and everything will
208 Thus, you can typically put the two in the same directory and everything will
209 just work.
209 just work.
210
210
211 You can also load configuration files by profile, for instance:
211 You can also load configuration files by profile, for instance:
212
212
213 .. sourcecode:: python
213 .. sourcecode:: python
214
214
215 load_subconfig('ipython_config.py', profile='default')
215 load_subconfig('ipython_config.py', profile='default')
216
216
217 to inherit your default configuration as a starting point.
217 to inherit your default configuration as a starting point.
218
218
219
219
220 Class based configuration inheritance
220 Class based configuration inheritance
221 =====================================
221 =====================================
222
222
223 There is another aspect of configuration where inheritance comes into play.
223 There is another aspect of configuration where inheritance comes into play.
224 Sometimes, your classes will have an inheritance hierarchy that you want
224 Sometimes, your classes will have an inheritance hierarchy that you want
225 to be reflected in the configuration system. Here is a simple example::
225 to be reflected in the configuration system. Here is a simple example::
226
226
227 from IPython.config.configurable import Configurable
227 from IPython.config.configurable import Configurable
228 from IPython.utils.traitlets import Int, Float, Unicode, Bool
228 from IPython.utils.traitlets import Int, Float, Unicode, Bool
229
229
230 class Foo(Configurable):
230 class Foo(Configurable):
231 name = Unicode(u'fooname', config=True)
231 name = Unicode(u'fooname', config=True)
232 value = Float(100.0, config=True)
232 value = Float(100.0, config=True)
233
233
234 class Bar(Foo):
234 class Bar(Foo):
235 name = Unicode(u'barname', config=True)
235 name = Unicode(u'barname', config=True)
236 othervalue = Int(0, config=True)
236 othervalue = Int(0, config=True)
237
237
238 Now, we can create a configuration file to configure instances of :class:`Foo`
238 Now, we can create a configuration file to configure instances of :class:`Foo`
239 and :class:`Bar`::
239 and :class:`Bar`::
240
240
241 # config file
241 # config file
242 c = get_config()
242 c = get_config()
243
243
244 c.Foo.name = u'bestname'
244 c.Foo.name = u'bestname'
245 c.Bar.othervalue = 10
245 c.Bar.othervalue = 10
246
246
247 This class hierarchy and configuration file accomplishes the following:
247 This class hierarchy and configuration file accomplishes the following:
248
248
249 * The default value for :attr:`Foo.name` and :attr:`Bar.name` will be
249 * The default value for :attr:`Foo.name` and :attr:`Bar.name` will be
250 'bestname'. Because :class:`Bar` is a :class:`Foo` subclass it also
250 'bestname'. Because :class:`Bar` is a :class:`Foo` subclass it also
251 picks up the configuration information for :class:`Foo`.
251 picks up the configuration information for :class:`Foo`.
252 * The default value for :attr:`Foo.value` and :attr:`Bar.value` will be
252 * The default value for :attr:`Foo.value` and :attr:`Bar.value` will be
253 ``100.0``, which is the value specified as the class default.
253 ``100.0``, which is the value specified as the class default.
254 * The default value for :attr:`Bar.othervalue` will be 10 as set in the
254 * The default value for :attr:`Bar.othervalue` will be 10 as set in the
255 configuration file. Because :class:`Foo` is the parent of :class:`Bar`
255 configuration file. Because :class:`Foo` is the parent of :class:`Bar`
256 it doesn't know anything about the :attr:`othervalue` attribute.
256 it doesn't know anything about the :attr:`othervalue` attribute.
257
257
258
258
259 .. _ipython_dir:
259 .. _ipython_dir:
260
260
261 Configuration file location
261 Configuration file location
262 ===========================
262 ===========================
263
263
264 So where should you put your configuration files? IPython uses "profiles" for
264 So where should you put your configuration files? IPython uses "profiles" for
265 configuration, and by default, all profiles will be stored in the so called
265 configuration, and by default, all profiles will be stored in the so called
266 "IPython directory". The location of this directory is determined by the
266 "IPython directory". The location of this directory is determined by the
267 following algorithm:
267 following algorithm:
268
268
269 * If the ``ipython-dir`` command line flag is given, its value is used.
269 * If the ``ipython-dir`` command line flag is given, its value is used.
270
270
271 * If not, the value returned by :func:`IPython.utils.path.get_ipython_dir`
271 * If not, the value returned by :func:`IPython.utils.path.get_ipython_dir`
272 is used. This function will first look at the :envvar:`IPYTHONDIR`
272 is used. This function will first look at the :envvar:`IPYTHONDIR`
273 environment variable and then default to a platform-specific default.
273 environment variable and then default to :file:`~/.ipython`.
274 Historical support for the :envvar:`IPYTHON_DIR` environment variable will
274 Historical support for the :envvar:`IPYTHON_DIR` environment variable will
275 be removed in a future release.
275 be removed in a future release.
276
276
277 On posix systems (Linux, Unix, etc.), IPython respects the ``$XDG_CONFIG_HOME``
277 For most users, the configuration directory will be :file:`~/.ipython`.
278 part of the `XDG Base Directory`_ specification. If ``$XDG_CONFIG_HOME`` is
278
279 defined and exists ( ``XDG_CONFIG_HOME`` has a default interpretation of
279 Previous versions of IPython on Linux would use the XDG config directory,
280 :file:`$HOME/.config`), then IPython's config directory will be located in
280 creating :file:`~/.config/ipython` by default. We have decided to go
281 :file:`$XDG_CONFIG_HOME/ipython`. If users still have an IPython directory
281 back to :file:`~/.ipython` for consistency among systems. IPython will
282 in :file:`$HOME/.ipython`, then that will be used. in preference to the
282 issue a warning if it finds the XDG location, and will move it to the new
283 system default.
283 location if there isn't already a directory there.
284
285 For most users, the default value will simply be something like
286 :file:`$HOME/.config/ipython` on Linux, or :file:`$HOME/.ipython`
287 elsewhere.
288
284
289 Once the location of the IPython directory has been determined, you need to know
285 Once the location of the IPython directory has been determined, you need to know
290 which profile you are using. For users with a single configuration, this will
286 which profile you are using. For users with a single configuration, this will
291 simply be 'default', and will be located in
287 simply be 'default', and will be located in
292 :file:`<IPYTHONDIR>/profile_default`.
288 :file:`<IPYTHONDIR>/profile_default`.
293
289
294 The next thing you need to know is what to call your configuration file. The
290 The next thing you need to know is what to call your configuration file. The
295 basic idea is that each application has its own default configuration filename.
291 basic idea is that each application has its own default configuration filename.
296 The default named used by the :command:`ipython` command line program is
292 The default named used by the :command:`ipython` command line program is
297 :file:`ipython_config.py`, and *all* IPython applications will use this file.
293 :file:`ipython_config.py`, and *all* IPython applications will use this file.
298 Other applications, such as the parallel :command:`ipcluster` scripts or the
294 Other applications, such as the parallel :command:`ipcluster` scripts or the
299 QtConsole will load their own config files *after* :file:`ipython_config.py`. To
295 QtConsole will load their own config files *after* :file:`ipython_config.py`. To
300 load a particular configuration file instead of the default, the name can be
296 load a particular configuration file instead of the default, the name can be
301 overridden by the ``config_file`` command line flag.
297 overridden by the ``config_file`` command line flag.
302
298
303 To generate the default configuration files, do::
299 To generate the default configuration files, do::
304
300
305 $ ipython profile create
301 $ ipython profile create
306
302
307 and you will have a default :file:`ipython_config.py` in your IPython directory
303 and you will have a default :file:`ipython_config.py` in your IPython directory
308 under :file:`profile_default`. If you want the default config files for the
304 under :file:`profile_default`. If you want the default config files for the
309 :mod:`IPython.parallel` applications, add ``--parallel`` to the end of the
305 :mod:`IPython.parallel` applications, add ``--parallel`` to the end of the
310 command-line args.
306 command-line args.
311
307
312
308
313 Locating these files
309 Locating these files
314 --------------------
310 --------------------
315
311
316 From the command-line, you can quickly locate the IPYTHONDIR or a specific
312 From the command-line, you can quickly locate the IPYTHONDIR or a specific
317 profile with:
313 profile with:
318
314
319 .. sourcecode:: bash
315 .. sourcecode:: bash
320
316
321 $ ipython locate
317 $ ipython locate
322 /home/you/.ipython
318 /home/you/.ipython
323
319
324 $ ipython locate profile foo
320 $ ipython locate profile foo
325 /home/you/.ipython/profile_foo
321 /home/you/.ipython/profile_foo
326
322
327 These map to the utility functions: :func:`IPython.utils.path.get_ipython_dir`
323 These map to the utility functions: :func:`IPython.utils.path.get_ipython_dir`
328 and :func:`IPython.utils.path.locate_profile` respectively.
324 and :func:`IPython.utils.path.locate_profile` respectively.
329
325
330
326
331 .. _Profiles:
327 .. _Profiles:
332
328
333 Profiles
329 Profiles
334 ========
330 ========
335
331
336 A profile is a directory containing configuration and runtime files, such as
332 A profile is a directory containing configuration and runtime files, such as
337 logs, connection info for the parallel apps, and your IPython command history.
333 logs, connection info for the parallel apps, and your IPython command history.
338
334
339 The idea is that users often want to maintain a set of configuration files for
335 The idea is that users often want to maintain a set of configuration files for
340 different purposes: one for doing numerical computing with NumPy and SciPy and
336 different purposes: one for doing numerical computing with NumPy and SciPy and
341 another for doing symbolic computing with SymPy. Profiles make it easy to keep a
337 another for doing symbolic computing with SymPy. Profiles make it easy to keep a
342 separate configuration files, logs, and histories for each of these purposes.
338 separate configuration files, logs, and histories for each of these purposes.
343
339
344 Let's start by showing how a profile is used:
340 Let's start by showing how a profile is used:
345
341
346 .. code-block:: bash
342 .. code-block:: bash
347
343
348 $ ipython --profile=sympy
344 $ ipython --profile=sympy
349
345
350 This tells the :command:`ipython` command line program to get its configuration
346 This tells the :command:`ipython` command line program to get its configuration
351 from the "sympy" profile. The file names for various profiles do not change. The
347 from the "sympy" profile. The file names for various profiles do not change. The
352 only difference is that profiles are named in a special way. In the case above,
348 only difference is that profiles are named in a special way. In the case above,
353 the "sympy" profile means looking for :file:`ipython_config.py` in :file:`<IPYTHONDIR>/profile_sympy`.
349 the "sympy" profile means looking for :file:`ipython_config.py` in :file:`<IPYTHONDIR>/profile_sympy`.
354
350
355 The general pattern is this: simply create a new profile with:
351 The general pattern is this: simply create a new profile with:
356
352
357 .. code-block:: bash
353 .. code-block:: bash
358
354
359 $ ipython profile create <name>
355 $ ipython profile create <name>
360
356
361 which adds a directory called ``profile_<name>`` to your IPython directory. Then
357 which adds a directory called ``profile_<name>`` to your IPython directory. Then
362 you can load this profile by adding ``--profile=<name>`` to your command line
358 you can load this profile by adding ``--profile=<name>`` to your command line
363 options. Profiles are supported by all IPython applications.
359 options. Profiles are supported by all IPython applications.
364
360
365 IPython ships with some sample profiles in :file:`IPython/config/profile`. If
361 IPython ships with some sample profiles in :file:`IPython/config/profile`. If
366 you create profiles with the name of one of our shipped profiles, these config
362 you create profiles with the name of one of our shipped profiles, these config
367 files will be copied over instead of starting with the automatically generated
363 files will be copied over instead of starting with the automatically generated
368 config files.
364 config files.
369
365
370 Security Files
366 Security Files
371 --------------
367 --------------
372
368
373 If you are using the notebook, qtconsole, or parallel code, IPython stores
369 If you are using the notebook, qtconsole, or parallel code, IPython stores
374 connection information in small JSON files in the active profile's security
370 connection information in small JSON files in the active profile's security
375 directory. This directory is made private, so only you can see the files inside. If
371 directory. This directory is made private, so only you can see the files inside. If
376 you need to move connection files around to other computers, this is where they will
372 you need to move connection files around to other computers, this is where they will
377 be. If you want your code to be able to open security files by name, we have a
373 be. If you want your code to be able to open security files by name, we have a
378 convenience function :func:`IPython.utils.path.get_security_file`, which will return
374 convenience function :func:`IPython.utils.path.get_security_file`, which will return
379 the absolute path to a security file from its filename and [optionally] profile
375 the absolute path to a security file from its filename and [optionally] profile
380 name.
376 name.
381
377
382 .. _startup_files:
378 .. _startup_files:
383
379
384 Startup Files
380 Startup Files
385 -------------
381 -------------
386
382
387 If you want some code to be run at the beginning of every IPython session with
383 If you want some code to be run at the beginning of every IPython session with
388 a particular profile, the easiest way is to add Python (``.py``) or
384 a particular profile, the easiest way is to add Python (``.py``) or
389 IPython (``.ipy``) scripts to your :file:`<profile>/startup` directory. Files
385 IPython (``.ipy``) scripts to your :file:`<profile>/startup` directory. Files
390 in this directory will always be executed as soon as the IPython shell is
386 in this directory will always be executed as soon as the IPython shell is
391 constructed, and before any other code or scripts you have specified. If you
387 constructed, and before any other code or scripts you have specified. If you
392 have multiple files in the startup directory, they will be run in
388 have multiple files in the startup directory, they will be run in
393 lexicographical order, so you can control the ordering by adding a '00-'
389 lexicographical order, so you can control the ordering by adding a '00-'
394 prefix.
390 prefix.
395
391
396
392
397 .. _commandline:
393 .. _commandline:
398
394
399 Command-line arguments
395 Command-line arguments
400 ======================
396 ======================
401
397
402 IPython exposes *all* configurable options on the command-line. The command-line
398 IPython exposes *all* configurable options on the command-line. The command-line
403 arguments are generated from the Configurable traits of the classes associated
399 arguments are generated from the Configurable traits of the classes associated
404 with a given Application. Configuring IPython from the command-line may look
400 with a given Application. Configuring IPython from the command-line may look
405 very similar to an IPython config file
401 very similar to an IPython config file
406
402
407 IPython applications use a parser called
403 IPython applications use a parser called
408 :class:`~IPython.config.loader.KeyValueLoader` to load values into a Config
404 :class:`~IPython.config.loader.KeyValueLoader` to load values into a Config
409 object. Values are assigned in much the same way as in a config file:
405 object. Values are assigned in much the same way as in a config file:
410
406
411 .. code-block:: bash
407 .. code-block:: bash
412
408
413 $ ipython --InteractiveShell.use_readline=False --BaseIPythonApplication.profile='myprofile'
409 $ ipython --InteractiveShell.use_readline=False --BaseIPythonApplication.profile='myprofile'
414
410
415 Is the same as adding:
411 Is the same as adding:
416
412
417 .. sourcecode:: python
413 .. sourcecode:: python
418
414
419 c.InteractiveShell.use_readline=False
415 c.InteractiveShell.use_readline=False
420 c.BaseIPythonApplication.profile='myprofile'
416 c.BaseIPythonApplication.profile='myprofile'
421
417
422 to your config file. Key/Value arguments *always* take a value, separated by '='
418 to your config file. Key/Value arguments *always* take a value, separated by '='
423 and no spaces.
419 and no spaces.
424
420
425 Common Arguments
421 Common Arguments
426 ----------------
422 ----------------
427
423
428 Since the strictness and verbosity of the KVLoader above are not ideal for everyday
424 Since the strictness and verbosity of the KVLoader above are not ideal for everyday
429 use, common arguments can be specified as flags_ or aliases_.
425 use, common arguments can be specified as flags_ or aliases_.
430
426
431 Flags and Aliases are handled by :mod:`argparse` instead, allowing for more flexible
427 Flags and Aliases are handled by :mod:`argparse` instead, allowing for more flexible
432 parsing. In general, flags and aliases are prefixed by ``--``, except for those
428 parsing. In general, flags and aliases are prefixed by ``--``, except for those
433 that are single characters, in which case they can be specified with a single ``-``, e.g.:
429 that are single characters, in which case they can be specified with a single ``-``, e.g.:
434
430
435 .. code-block:: bash
431 .. code-block:: bash
436
432
437 $ ipython -i -c "import numpy; x=numpy.linspace(0,1)" --profile testing --colors=lightbg
433 $ ipython -i -c "import numpy; x=numpy.linspace(0,1)" --profile testing --colors=lightbg
438
434
439 Aliases
435 Aliases
440 *******
436 *******
441
437
442 For convenience, applications have a mapping of commonly used traits, so you don't have
438 For convenience, applications have a mapping of commonly used traits, so you don't have
443 to specify the whole class name:
439 to specify the whole class name:
444
440
445 .. code-block:: bash
441 .. code-block:: bash
446
442
447 $ ipython --profile myprofile
443 $ ipython --profile myprofile
448 # and
444 # and
449 $ ipython --profile='myprofile'
445 $ ipython --profile='myprofile'
450 # are equivalent to
446 # are equivalent to
451 $ ipython --BaseIPythonApplication.profile='myprofile'
447 $ ipython --BaseIPythonApplication.profile='myprofile'
452
448
453 Flags
449 Flags
454 *****
450 *****
455
451
456 Applications can also be passed **flags**. Flags are options that take no
452 Applications can also be passed **flags**. Flags are options that take no
457 arguments. They are simply wrappers for
453 arguments. They are simply wrappers for
458 setting one or more configurables with predefined values, often True/False.
454 setting one or more configurables with predefined values, often True/False.
459
455
460 For instance:
456 For instance:
461
457
462 .. code-block:: bash
458 .. code-block:: bash
463
459
464 $ ipcontroller --debug
460 $ ipcontroller --debug
465 # is equivalent to
461 # is equivalent to
466 $ ipcontroller --Application.log_level=DEBUG
462 $ ipcontroller --Application.log_level=DEBUG
467 # and
463 # and
468 $ ipython --matploitlib
464 $ ipython --matploitlib
469 # is equivalent to
465 # is equivalent to
470 $ ipython --matplotlib auto
466 $ ipython --matplotlib auto
471 # or
467 # or
472 $ ipython --no-banner
468 $ ipython --no-banner
473 # is equivalent to
469 # is equivalent to
474 $ ipython --TerminalIPythonApp.display_banner=False
470 $ ipython --TerminalIPythonApp.display_banner=False
475
471
476 Subcommands
472 Subcommands
477 -----------
473 -----------
478
474
479
475
480 Some IPython applications have **subcommands**. Subcommands are modeled after
476 Some IPython applications have **subcommands**. Subcommands are modeled after
481 :command:`git`, and are called with the form :command:`command subcommand
477 :command:`git`, and are called with the form :command:`command subcommand
482 [...args]`. Currently, the QtConsole is a subcommand of terminal IPython:
478 [...args]`. Currently, the QtConsole is a subcommand of terminal IPython:
483
479
484 .. code-block:: bash
480 .. code-block:: bash
485
481
486 $ ipython qtconsole --profile myprofile
482 $ ipython qtconsole --profile myprofile
487
483
488 and :command:`ipcluster` is simply a wrapper for its various subcommands (start,
484 and :command:`ipcluster` is simply a wrapper for its various subcommands (start,
489 stop, engines).
485 stop, engines).
490
486
491 .. code-block:: bash
487 .. code-block:: bash
492
488
493 $ ipcluster start --profile=myprofile -n 4
489 $ ipcluster start --profile=myprofile -n 4
494
490
495
491
496 To see a list of the available aliases, flags, and subcommands for an IPython application, simply pass ``-h`` or ``--help``. And to see the full list of configurable options (*very* long), pass ``--help-all``.
492 To see a list of the available aliases, flags, and subcommands for an IPython application, simply pass ``-h`` or ``--help``. And to see the full list of configurable options (*very* long), pass ``--help-all``.
497
493
498
494
499 Design requirements
495 Design requirements
500 ===================
496 ===================
501
497
502 Here are the main requirements we wanted our configuration system to have:
498 Here are the main requirements we wanted our configuration system to have:
503
499
504 * Support for hierarchical configuration information.
500 * Support for hierarchical configuration information.
505
501
506 * Full integration with command line option parsers. Often, you want to read
502 * Full integration with command line option parsers. Often, you want to read
507 a configuration file, but then override some of the values with command line
503 a configuration file, but then override some of the values with command line
508 options. Our configuration system automates this process and allows each
504 options. Our configuration system automates this process and allows each
509 command line option to be linked to a particular attribute in the
505 command line option to be linked to a particular attribute in the
510 configuration hierarchy that it will override.
506 configuration hierarchy that it will override.
511
507
512 * Configuration files that are themselves valid Python code. This accomplishes
508 * Configuration files that are themselves valid Python code. This accomplishes
513 many things. First, it becomes possible to put logic in your configuration
509 many things. First, it becomes possible to put logic in your configuration
514 files that sets attributes based on your operating system, network setup,
510 files that sets attributes based on your operating system, network setup,
515 Python version, etc. Second, Python has a super simple syntax for accessing
511 Python version, etc. Second, Python has a super simple syntax for accessing
516 hierarchical data structures, namely regular attribute access
512 hierarchical data structures, namely regular attribute access
517 (``Foo.Bar.Bam.name``). Third, using Python makes it easy for users to
513 (``Foo.Bar.Bam.name``). Third, using Python makes it easy for users to
518 import configuration attributes from one configuration file to another.
514 import configuration attributes from one configuration file to another.
519 Fourth, even though Python is dynamically typed, it does have types that can
515 Fourth, even though Python is dynamically typed, it does have types that can
520 be checked at runtime. Thus, a ``1`` in a config file is the integer '1',
516 be checked at runtime. Thus, a ``1`` in a config file is the integer '1',
521 while a ``'1'`` is a string.
517 while a ``'1'`` is a string.
522
518
523 * A fully automated method for getting the configuration information to the
519 * A fully automated method for getting the configuration information to the
524 classes that need it at runtime. Writing code that walks a configuration
520 classes that need it at runtime. Writing code that walks a configuration
525 hierarchy to extract a particular attribute is painful. When you have
521 hierarchy to extract a particular attribute is painful. When you have
526 complex configuration information with hundreds of attributes, this makes
522 complex configuration information with hundreds of attributes, this makes
527 you want to cry.
523 you want to cry.
528
524
529 * Type checking and validation that doesn't require the entire configuration
525 * Type checking and validation that doesn't require the entire configuration
530 hierarchy to be specified statically before runtime. Python is a very
526 hierarchy to be specified statically before runtime. Python is a very
531 dynamic language and you don't always know everything that needs to be
527 dynamic language and you don't always know everything that needs to be
532 configured when a program starts.
528 configured when a program starts.
533
529
534
530
535 .. _`XDG Base Directory`: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
531 .. _`XDG Base Directory`: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
@@ -1,1164 +1,1164 b''
1 =================
1 =================
2 IPython reference
2 IPython reference
3 =================
3 =================
4
4
5 .. _command_line_options:
5 .. _command_line_options:
6
6
7 Command-line usage
7 Command-line usage
8 ==================
8 ==================
9
9
10 You start IPython with the command::
10 You start IPython with the command::
11
11
12 $ ipython [options] files
12 $ ipython [options] files
13
13
14 .. note::
14 .. note::
15
15
16 For IPython on Python 3, use ``ipython3`` in place of ``ipython``.
16 For IPython on Python 3, use ``ipython3`` in place of ``ipython``.
17
17
18 If invoked with no options, it executes all the files listed in sequence
18 If invoked with no options, it executes all the files listed in sequence
19 and drops you into the interpreter while still acknowledging any options
19 and drops you into the interpreter while still acknowledging any options
20 you may have set in your ipython_config.py. This behavior is different from
20 you may have set in your ipython_config.py. This behavior is different from
21 standard Python, which when called as python -i will only execute one
21 standard Python, which when called as python -i will only execute one
22 file and ignore your configuration setup.
22 file and ignore your configuration setup.
23
23
24 Please note that some of the configuration options are not available at
24 Please note that some of the configuration options are not available at
25 the command line, simply because they are not practical here. Look into
25 the command line, simply because they are not practical here. Look into
26 your configuration files for details on those. There are separate configuration
26 your configuration files for details on those. There are separate configuration
27 files for each profile, and the files look like "ipython_config.py" or
27 files for each profile, and the files look like "ipython_config.py" or
28 "ipython_config_<frontendname>.py". Profile directories look like
28 "ipython_config_<frontendname>.py". Profile directories look like
29 "profile_profilename" and are typically installed in the IPYTHONDIR directory.
29 "profile_profilename" and are typically installed in the IPYTHONDIR directory,
30 For Linux users, this will be $HOME/.config/ipython, and for other users it
30 which defaults to :file:`$HOME/.ipython`. For Windows users, :envvar:`HOME`
31 will be $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and
31 resolves to :file:`C:\\Documents and Settings\\YourUserName` in most
32 Settings\\YourUserName in most instances.
32 instances.
33
33
34
34
35 Eventloop integration
35 Eventloop integration
36 ---------------------
36 ---------------------
37
37
38 Previously IPython had command line options for controlling GUI event loop
38 Previously IPython had command line options for controlling GUI event loop
39 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
39 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
40 version 0.11, these have been removed. Please see the new ``%gui``
40 version 0.11, these have been removed. Please see the new ``%gui``
41 magic command or :ref:`this section <gui_support>` for details on the new
41 magic command or :ref:`this section <gui_support>` for details on the new
42 interface, or specify the gui at the commandline::
42 interface, or specify the gui at the commandline::
43
43
44 $ ipython --gui=qt
44 $ ipython --gui=qt
45
45
46
46
47 Command-line Options
47 Command-line Options
48 --------------------
48 --------------------
49
49
50 To see the options IPython accepts, use ``ipython --help`` (and you probably
50 To see the options IPython accepts, use ``ipython --help`` (and you probably
51 should run the output through a pager such as ``ipython --help | less`` for
51 should run the output through a pager such as ``ipython --help | less`` for
52 more convenient reading). This shows all the options that have a single-word
52 more convenient reading). This shows all the options that have a single-word
53 alias to control them, but IPython lets you configure all of its objects from
53 alias to control them, but IPython lets you configure all of its objects from
54 the command-line by passing the full class name and a corresponding value; type
54 the command-line by passing the full class name and a corresponding value; type
55 ``ipython --help-all`` to see this full list. For example::
55 ``ipython --help-all`` to see this full list. For example::
56
56
57 ipython --matplotlib qt
57 ipython --matplotlib qt
58
58
59 is equivalent to::
59 is equivalent to::
60
60
61 ipython --TerminalIPythonApp.matplotlib='qt'
61 ipython --TerminalIPythonApp.matplotlib='qt'
62
62
63 Note that in the second form, you *must* use the equal sign, as the expression
63 Note that in the second form, you *must* use the equal sign, as the expression
64 is evaluated as an actual Python assignment. While in the above example the
64 is evaluated as an actual Python assignment. While in the above example the
65 short form is more convenient, only the most common options have a short form,
65 short form is more convenient, only the most common options have a short form,
66 while any configurable variable in IPython can be set at the command-line by
66 while any configurable variable in IPython can be set at the command-line by
67 using the long form. This long form is the same syntax used in the
67 using the long form. This long form is the same syntax used in the
68 configuration files, if you want to set these options permanently.
68 configuration files, if you want to set these options permanently.
69
69
70
70
71 Interactive use
71 Interactive use
72 ===============
72 ===============
73
73
74 IPython is meant to work as a drop-in replacement for the standard interactive
74 IPython is meant to work as a drop-in replacement for the standard interactive
75 interpreter. As such, any code which is valid python should execute normally
75 interpreter. As such, any code which is valid python should execute normally
76 under IPython (cases where this is not true should be reported as bugs). It
76 under IPython (cases where this is not true should be reported as bugs). It
77 does, however, offer many features which are not available at a standard python
77 does, however, offer many features which are not available at a standard python
78 prompt. What follows is a list of these.
78 prompt. What follows is a list of these.
79
79
80
80
81 Caution for Windows users
81 Caution for Windows users
82 -------------------------
82 -------------------------
83
83
84 Windows, unfortunately, uses the '\\' character as a path separator. This is a
84 Windows, unfortunately, uses the '\\' character as a path separator. This is a
85 terrible choice, because '\\' also represents the escape character in most
85 terrible choice, because '\\' also represents the escape character in most
86 modern programming languages, including Python. For this reason, using '/'
86 modern programming languages, including Python. For this reason, using '/'
87 character is recommended if you have problems with ``\``. However, in Windows
87 character is recommended if you have problems with ``\``. However, in Windows
88 commands '/' flags options, so you can not use it for the root directory. This
88 commands '/' flags options, so you can not use it for the root directory. This
89 means that paths beginning at the root must be typed in a contrived manner
89 means that paths beginning at the root must be typed in a contrived manner
90 like: ``%copy \opt/foo/bar.txt \tmp``
90 like: ``%copy \opt/foo/bar.txt \tmp``
91
91
92 .. _magic:
92 .. _magic:
93
93
94 Magic command system
94 Magic command system
95 --------------------
95 --------------------
96
96
97 IPython will treat any line whose first character is a % as a special
97 IPython will treat any line whose first character is a % as a special
98 call to a 'magic' function. These allow you to control the behavior of
98 call to a 'magic' function. These allow you to control the behavior of
99 IPython itself, plus a lot of system-type features. They are all
99 IPython itself, plus a lot of system-type features. They are all
100 prefixed with a % character, but parameters are given without
100 prefixed with a % character, but parameters are given without
101 parentheses or quotes.
101 parentheses or quotes.
102
102
103 Lines that begin with ``%%`` signal a *cell magic*: they take as arguments not
103 Lines that begin with ``%%`` signal a *cell magic*: they take as arguments not
104 only the rest of the current line, but all lines below them as well, in the
104 only the rest of the current line, but all lines below them as well, in the
105 current execution block. Cell magics can in fact make arbitrary modifications
105 current execution block. Cell magics can in fact make arbitrary modifications
106 to the input they receive, which need not even be valid Python code at all.
106 to the input they receive, which need not even be valid Python code at all.
107 They receive the whole block as a single string.
107 They receive the whole block as a single string.
108
108
109 As a line magic example, the ``%cd`` magic works just like the OS command of
109 As a line magic example, the ``%cd`` magic works just like the OS command of
110 the same name::
110 the same name::
111
111
112 In [8]: %cd
112 In [8]: %cd
113 /home/fperez
113 /home/fperez
114
114
115 The following uses the builtin ``timeit`` in cell mode::
115 The following uses the builtin ``timeit`` in cell mode::
116
116
117 In [10]: %%timeit x = range(10000)
117 In [10]: %%timeit x = range(10000)
118 ...: min(x)
118 ...: min(x)
119 ...: max(x)
119 ...: max(x)
120 ...:
120 ...:
121 1000 loops, best of 3: 438 us per loop
121 1000 loops, best of 3: 438 us per loop
122
122
123 In this case, ``x = range(10000)`` is called as the line argument, and the
123 In this case, ``x = range(10000)`` is called as the line argument, and the
124 block with ``min(x)`` and ``max(x)`` is called as the cell body. The
124 block with ``min(x)`` and ``max(x)`` is called as the cell body. The
125 ``timeit`` magic receives both.
125 ``timeit`` magic receives both.
126
126
127 If you have 'automagic' enabled (as it by default), you don't need to type in
127 If you have 'automagic' enabled (as it by default), you don't need to type in
128 the single ``%`` explicitly for line magics; IPython will scan its internal
128 the single ``%`` explicitly for line magics; IPython will scan its internal
129 list of magic functions and call one if it exists. With automagic on you can
129 list of magic functions and call one if it exists. With automagic on you can
130 then just type ``cd mydir`` to go to directory 'mydir'::
130 then just type ``cd mydir`` to go to directory 'mydir'::
131
131
132 In [9]: cd mydir
132 In [9]: cd mydir
133 /home/fperez/mydir
133 /home/fperez/mydir
134
134
135 Note that cell magics *always* require an explicit ``%%`` prefix, automagic
135 Note that cell magics *always* require an explicit ``%%`` prefix, automagic
136 calling only works for line magics.
136 calling only works for line magics.
137
137
138 The automagic system has the lowest possible precedence in name searches, so
138 The automagic system has the lowest possible precedence in name searches, so
139 defining an identifier with the same name as an existing magic function will
139 defining an identifier with the same name as an existing magic function will
140 shadow it for automagic use. You can still access the shadowed magic function
140 shadow it for automagic use. You can still access the shadowed magic function
141 by explicitly using the ``%`` character at the beginning of the line.
141 by explicitly using the ``%`` character at the beginning of the line.
142
142
143 An example (with automagic on) should clarify all this:
143 An example (with automagic on) should clarify all this:
144
144
145 .. sourcecode:: ipython
145 .. sourcecode:: ipython
146
146
147 In [1]: cd ipython # %cd is called by automagic
147 In [1]: cd ipython # %cd is called by automagic
148 /home/fperez/ipython
148 /home/fperez/ipython
149
149
150 In [2]: cd=1 # now cd is just a variable
150 In [2]: cd=1 # now cd is just a variable
151
151
152 In [3]: cd .. # and doesn't work as a function anymore
152 In [3]: cd .. # and doesn't work as a function anymore
153 File "<ipython-input-3-9fedb3aff56c>", line 1
153 File "<ipython-input-3-9fedb3aff56c>", line 1
154 cd ..
154 cd ..
155 ^
155 ^
156 SyntaxError: invalid syntax
156 SyntaxError: invalid syntax
157
157
158
158
159 In [4]: %cd .. # but %cd always works
159 In [4]: %cd .. # but %cd always works
160 /home/fperez
160 /home/fperez
161
161
162 In [5]: del cd # if you remove the cd variable, automagic works again
162 In [5]: del cd # if you remove the cd variable, automagic works again
163
163
164 In [6]: cd ipython
164 In [6]: cd ipython
165
165
166 /home/fperez/ipython
166 /home/fperez/ipython
167
167
168 Defining your own magics
168 Defining your own magics
169 ++++++++++++++++++++++++
169 ++++++++++++++++++++++++
170
170
171 There are two main ways to define your own magic functions: from standalone
171 There are two main ways to define your own magic functions: from standalone
172 functions and by inheriting from a base class provided by IPython:
172 functions and by inheriting from a base class provided by IPython:
173 :class:`IPython.core.magic.Magics`. Below we show code you can place in a file
173 :class:`IPython.core.magic.Magics`. Below we show code you can place in a file
174 that you load from your configuration, such as any file in the ``startup``
174 that you load from your configuration, such as any file in the ``startup``
175 subdirectory of your default IPython profile.
175 subdirectory of your default IPython profile.
176
176
177 First, let us see the simplest case. The following shows how to create a line
177 First, let us see the simplest case. The following shows how to create a line
178 magic, a cell one and one that works in both modes, using just plain functions:
178 magic, a cell one and one that works in both modes, using just plain functions:
179
179
180 .. sourcecode:: python
180 .. sourcecode:: python
181
181
182 from IPython.core.magic import (register_line_magic, register_cell_magic,
182 from IPython.core.magic import (register_line_magic, register_cell_magic,
183 register_line_cell_magic)
183 register_line_cell_magic)
184
184
185 @register_line_magic
185 @register_line_magic
186 def lmagic(line):
186 def lmagic(line):
187 "my line magic"
187 "my line magic"
188 return line
188 return line
189
189
190 @register_cell_magic
190 @register_cell_magic
191 def cmagic(line, cell):
191 def cmagic(line, cell):
192 "my cell magic"
192 "my cell magic"
193 return line, cell
193 return line, cell
194
194
195 @register_line_cell_magic
195 @register_line_cell_magic
196 def lcmagic(line, cell=None):
196 def lcmagic(line, cell=None):
197 "Magic that works both as %lcmagic and as %%lcmagic"
197 "Magic that works both as %lcmagic and as %%lcmagic"
198 if cell is None:
198 if cell is None:
199 print "Called as line magic"
199 print "Called as line magic"
200 return line
200 return line
201 else:
201 else:
202 print "Called as cell magic"
202 print "Called as cell magic"
203 return line, cell
203 return line, cell
204
204
205 # We delete these to avoid name conflicts for automagic to work
205 # We delete these to avoid name conflicts for automagic to work
206 del lmagic, lcmagic
206 del lmagic, lcmagic
207
207
208
208
209 You can also create magics of all three kinds by inheriting from the
209 You can also create magics of all three kinds by inheriting from the
210 :class:`IPython.core.magic.Magics` class. This lets you create magics that can
210 :class:`IPython.core.magic.Magics` class. This lets you create magics that can
211 potentially hold state in between calls, and that have full access to the main
211 potentially hold state in between calls, and that have full access to the main
212 IPython object:
212 IPython object:
213
213
214 .. sourcecode:: python
214 .. sourcecode:: python
215
215
216 # This code can be put in any Python module, it does not require IPython
216 # This code can be put in any Python module, it does not require IPython
217 # itself to be running already. It only creates the magics subclass but
217 # itself to be running already. It only creates the magics subclass but
218 # doesn't instantiate it yet.
218 # doesn't instantiate it yet.
219 from IPython.core.magic import (Magics, magics_class, line_magic,
219 from IPython.core.magic import (Magics, magics_class, line_magic,
220 cell_magic, line_cell_magic)
220 cell_magic, line_cell_magic)
221
221
222 # The class MUST call this class decorator at creation time
222 # The class MUST call this class decorator at creation time
223 @magics_class
223 @magics_class
224 class MyMagics(Magics):
224 class MyMagics(Magics):
225
225
226 @line_magic
226 @line_magic
227 def lmagic(self, line):
227 def lmagic(self, line):
228 "my line magic"
228 "my line magic"
229 print "Full access to the main IPython object:", self.shell
229 print "Full access to the main IPython object:", self.shell
230 print "Variables in the user namespace:", self.shell.user_ns.keys()
230 print "Variables in the user namespace:", self.shell.user_ns.keys()
231 return line
231 return line
232
232
233 @cell_magic
233 @cell_magic
234 def cmagic(self, line, cell):
234 def cmagic(self, line, cell):
235 "my cell magic"
235 "my cell magic"
236 return line, cell
236 return line, cell
237
237
238 @line_cell_magic
238 @line_cell_magic
239 def lcmagic(self, line, cell=None):
239 def lcmagic(self, line, cell=None):
240 "Magic that works both as %lcmagic and as %%lcmagic"
240 "Magic that works both as %lcmagic and as %%lcmagic"
241 if cell is None:
241 if cell is None:
242 print "Called as line magic"
242 print "Called as line magic"
243 return line
243 return line
244 else:
244 else:
245 print "Called as cell magic"
245 print "Called as cell magic"
246 return line, cell
246 return line, cell
247
247
248
248
249 # In order to actually use these magics, you must register them with a
249 # In order to actually use these magics, you must register them with a
250 # running IPython. This code must be placed in a file that is loaded once
250 # running IPython. This code must be placed in a file that is loaded once
251 # IPython is up and running:
251 # IPython is up and running:
252 ip = get_ipython()
252 ip = get_ipython()
253 # You can register the class itself without instantiating it. IPython will
253 # You can register the class itself without instantiating it. IPython will
254 # call the default constructor on it.
254 # call the default constructor on it.
255 ip.register_magics(MyMagics)
255 ip.register_magics(MyMagics)
256
256
257 If you want to create a class with a different constructor that holds
257 If you want to create a class with a different constructor that holds
258 additional state, then you should always call the parent constructor and
258 additional state, then you should always call the parent constructor and
259 instantiate the class yourself before registration:
259 instantiate the class yourself before registration:
260
260
261 .. sourcecode:: python
261 .. sourcecode:: python
262
262
263 @magics_class
263 @magics_class
264 class StatefulMagics(Magics):
264 class StatefulMagics(Magics):
265 "Magics that hold additional state"
265 "Magics that hold additional state"
266
266
267 def __init__(self, shell, data):
267 def __init__(self, shell, data):
268 # You must call the parent constructor
268 # You must call the parent constructor
269 super(StatefulMagics, self).__init__(shell)
269 super(StatefulMagics, self).__init__(shell)
270 self.data = data
270 self.data = data
271
271
272 # etc...
272 # etc...
273
273
274 # This class must then be registered with a manually created instance,
274 # This class must then be registered with a manually created instance,
275 # since its constructor has different arguments from the default:
275 # since its constructor has different arguments from the default:
276 ip = get_ipython()
276 ip = get_ipython()
277 magics = StatefulMagics(ip, some_data)
277 magics = StatefulMagics(ip, some_data)
278 ip.register_magics(magics)
278 ip.register_magics(magics)
279
279
280
280
281 In earlier versions, IPython had an API for the creation of line magics (cell
281 In earlier versions, IPython had an API for the creation of line magics (cell
282 magics did not exist at the time) that required you to create functions with a
282 magics did not exist at the time) that required you to create functions with a
283 method-looking signature and to manually pass both the function and the name.
283 method-looking signature and to manually pass both the function and the name.
284 While this API is no longer recommended, it remains indefinitely supported for
284 While this API is no longer recommended, it remains indefinitely supported for
285 backwards compatibility purposes. With the old API, you'd create a magic as
285 backwards compatibility purposes. With the old API, you'd create a magic as
286 follows:
286 follows:
287
287
288 .. sourcecode:: python
288 .. sourcecode:: python
289
289
290 def func(self, line):
290 def func(self, line):
291 print "Line magic called with line:", line
291 print "Line magic called with line:", line
292 print "IPython object:", self.shell
292 print "IPython object:", self.shell
293
293
294 ip = get_ipython()
294 ip = get_ipython()
295 # Declare this function as the magic %mycommand
295 # Declare this function as the magic %mycommand
296 ip.define_magic('mycommand', func)
296 ip.define_magic('mycommand', func)
297
297
298 Type ``%magic`` for more information, including a list of all available magic
298 Type ``%magic`` for more information, including a list of all available magic
299 functions at any time and their docstrings. You can also type
299 functions at any time and their docstrings. You can also type
300 ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for
300 ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for
301 information on the '?' system) to get information about any particular magic
301 information on the '?' system) to get information about any particular magic
302 function you are interested in.
302 function you are interested in.
303
303
304 The API documentation for the :mod:`IPython.core.magic` module contains the full
304 The API documentation for the :mod:`IPython.core.magic` module contains the full
305 docstrings of all currently available magic commands.
305 docstrings of all currently available magic commands.
306
306
307
307
308 Access to the standard Python help
308 Access to the standard Python help
309 ----------------------------------
309 ----------------------------------
310
310
311 Simply type ``help()`` to access Python's standard help system. You can
311 Simply type ``help()`` to access Python's standard help system. You can
312 also type ``help(object)`` for information about a given object, or
312 also type ``help(object)`` for information about a given object, or
313 ``help('keyword')`` for information on a keyword. You may need to configure your
313 ``help('keyword')`` for information on a keyword. You may need to configure your
314 PYTHONDOCS environment variable for this feature to work correctly.
314 PYTHONDOCS environment variable for this feature to work correctly.
315
315
316 .. _dynamic_object_info:
316 .. _dynamic_object_info:
317
317
318 Dynamic object information
318 Dynamic object information
319 --------------------------
319 --------------------------
320
320
321 Typing ``?word`` or ``word?`` prints detailed information about an object. If
321 Typing ``?word`` or ``word?`` prints detailed information about an object. If
322 certain strings in the object are too long (e.g. function signatures) they get
322 certain strings in the object are too long (e.g. function signatures) they get
323 snipped in the center for brevity. This system gives access variable types and
323 snipped in the center for brevity. This system gives access variable types and
324 values, docstrings, function prototypes and other useful information.
324 values, docstrings, function prototypes and other useful information.
325
325
326 If the information will not fit in the terminal, it is displayed in a pager
326 If the information will not fit in the terminal, it is displayed in a pager
327 (``less`` if available, otherwise a basic internal pager).
327 (``less`` if available, otherwise a basic internal pager).
328
328
329 Typing ``??word`` or ``word??`` gives access to the full information, including
329 Typing ``??word`` or ``word??`` gives access to the full information, including
330 the source code where possible. Long strings are not snipped.
330 the source code where possible. Long strings are not snipped.
331
331
332 The following magic functions are particularly useful for gathering
332 The following magic functions are particularly useful for gathering
333 information about your working environment. You can get more details by
333 information about your working environment. You can get more details by
334 typing ``%magic`` or querying them individually (``%function_name?``);
334 typing ``%magic`` or querying them individually (``%function_name?``);
335 this is just a summary:
335 this is just a summary:
336
336
337 * **%pdoc <object>**: Print (or run through a pager if too long) the
337 * **%pdoc <object>**: Print (or run through a pager if too long) the
338 docstring for an object. If the given object is a class, it will
338 docstring for an object. If the given object is a class, it will
339 print both the class and the constructor docstrings.
339 print both the class and the constructor docstrings.
340 * **%pdef <object>**: Print the call signature for any callable
340 * **%pdef <object>**: Print the call signature for any callable
341 object. If the object is a class, print the constructor information.
341 object. If the object is a class, print the constructor information.
342 * **%psource <object>**: Print (or run through a pager if too long)
342 * **%psource <object>**: Print (or run through a pager if too long)
343 the source code for an object.
343 the source code for an object.
344 * **%pfile <object>**: Show the entire source file where an object was
344 * **%pfile <object>**: Show the entire source file where an object was
345 defined via a pager, opening it at the line where the object
345 defined via a pager, opening it at the line where the object
346 definition begins.
346 definition begins.
347 * **%who/%whos**: These functions give information about identifiers
347 * **%who/%whos**: These functions give information about identifiers
348 you have defined interactively (not things you loaded or defined
348 you have defined interactively (not things you loaded or defined
349 in your configuration files). %who just prints a list of
349 in your configuration files). %who just prints a list of
350 identifiers and %whos prints a table with some basic details about
350 identifiers and %whos prints a table with some basic details about
351 each identifier.
351 each identifier.
352
352
353 Note that the dynamic object information functions (?/??, ``%pdoc``,
353 Note that the dynamic object information functions (?/??, ``%pdoc``,
354 ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as
354 ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as
355 directly on variables. For example, after doing ``import os``, you can use
355 directly on variables. For example, after doing ``import os``, you can use
356 ``os.path.abspath??``.
356 ``os.path.abspath??``.
357
357
358 .. _readline:
358 .. _readline:
359
359
360 Readline-based features
360 Readline-based features
361 -----------------------
361 -----------------------
362
362
363 These features require the GNU readline library, so they won't work if your
363 These features require the GNU readline library, so they won't work if your
364 Python installation lacks readline support. We will first describe the default
364 Python installation lacks readline support. We will first describe the default
365 behavior IPython uses, and then how to change it to suit your preferences.
365 behavior IPython uses, and then how to change it to suit your preferences.
366
366
367
367
368 Command line completion
368 Command line completion
369 +++++++++++++++++++++++
369 +++++++++++++++++++++++
370
370
371 At any time, hitting TAB will complete any available python commands or
371 At any time, hitting TAB will complete any available python commands or
372 variable names, and show you a list of the possible completions if
372 variable names, and show you a list of the possible completions if
373 there's no unambiguous one. It will also complete filenames in the
373 there's no unambiguous one. It will also complete filenames in the
374 current directory if no python names match what you've typed so far.
374 current directory if no python names match what you've typed so far.
375
375
376
376
377 Search command history
377 Search command history
378 ++++++++++++++++++++++
378 ++++++++++++++++++++++
379
379
380 IPython provides two ways for searching through previous input and thus
380 IPython provides two ways for searching through previous input and thus
381 reduce the need for repetitive typing:
381 reduce the need for repetitive typing:
382
382
383 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
383 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
384 (next,down) to search through only the history items that match
384 (next,down) to search through only the history items that match
385 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
385 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
386 prompt, they just behave like normal arrow keys.
386 prompt, they just behave like normal arrow keys.
387 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
387 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
388 searches your history for lines that contain what you've typed so
388 searches your history for lines that contain what you've typed so
389 far, completing as much as it can.
389 far, completing as much as it can.
390
390
391
391
392 Persistent command history across sessions
392 Persistent command history across sessions
393 ++++++++++++++++++++++++++++++++++++++++++
393 ++++++++++++++++++++++++++++++++++++++++++
394
394
395 IPython will save your input history when it leaves and reload it next
395 IPython will save your input history when it leaves and reload it next
396 time you restart it. By default, the history file is named
396 time you restart it. By default, the history file is named
397 $IPYTHONDIR/profile_<name>/history.sqlite. This allows you to keep
397 $IPYTHONDIR/profile_<name>/history.sqlite. This allows you to keep
398 separate histories related to various tasks: commands related to
398 separate histories related to various tasks: commands related to
399 numerical work will not be clobbered by a system shell history, for
399 numerical work will not be clobbered by a system shell history, for
400 example.
400 example.
401
401
402
402
403 Autoindent
403 Autoindent
404 ++++++++++
404 ++++++++++
405
405
406 IPython can recognize lines ending in ':' and indent the next line,
406 IPython can recognize lines ending in ':' and indent the next line,
407 while also un-indenting automatically after 'raise' or 'return'.
407 while also un-indenting automatically after 'raise' or 'return'.
408
408
409 This feature uses the readline library, so it will honor your
409 This feature uses the readline library, so it will honor your
410 :file:`~/.inputrc` configuration (or whatever file your INPUTRC variable points
410 :file:`~/.inputrc` configuration (or whatever file your INPUTRC variable points
411 to). Adding the following lines to your :file:`.inputrc` file can make
411 to). Adding the following lines to your :file:`.inputrc` file can make
412 indenting/unindenting more convenient (M-i indents, M-u unindents)::
412 indenting/unindenting more convenient (M-i indents, M-u unindents)::
413
413
414 # if you don't already have a ~/.inputrc file, you need this include:
414 # if you don't already have a ~/.inputrc file, you need this include:
415 $include /etc/inputrc
415 $include /etc/inputrc
416
416
417 $if Python
417 $if Python
418 "\M-i": " "
418 "\M-i": " "
419 "\M-u": "\d\d\d\d"
419 "\M-u": "\d\d\d\d"
420 $endif
420 $endif
421
421
422 Note that there are 4 spaces between the quote marks after "M-i" above.
422 Note that there are 4 spaces between the quote marks after "M-i" above.
423
423
424 .. warning::
424 .. warning::
425
425
426 Setting the above indents will cause problems with unicode text entry in
426 Setting the above indents will cause problems with unicode text entry in
427 the terminal.
427 the terminal.
428
428
429 .. warning::
429 .. warning::
430
430
431 Autoindent is ON by default, but it can cause problems with the pasting of
431 Autoindent is ON by default, but it can cause problems with the pasting of
432 multi-line indented code (the pasted code gets re-indented on each line). A
432 multi-line indented code (the pasted code gets re-indented on each line). A
433 magic function %autoindent allows you to toggle it on/off at runtime. You
433 magic function %autoindent allows you to toggle it on/off at runtime. You
434 can also disable it permanently on in your :file:`ipython_config.py` file
434 can also disable it permanently on in your :file:`ipython_config.py` file
435 (set TerminalInteractiveShell.autoindent=False).
435 (set TerminalInteractiveShell.autoindent=False).
436
436
437 If you want to paste multiple lines in the terminal, it is recommended that
437 If you want to paste multiple lines in the terminal, it is recommended that
438 you use ``%paste``.
438 you use ``%paste``.
439
439
440
440
441 Customizing readline behavior
441 Customizing readline behavior
442 +++++++++++++++++++++++++++++
442 +++++++++++++++++++++++++++++
443
443
444 All these features are based on the GNU readline library, which has an
444 All these features are based on the GNU readline library, which has an
445 extremely customizable interface. Normally, readline is configured via a
445 extremely customizable interface. Normally, readline is configured via a
446 file which defines the behavior of the library; the details of the
446 file which defines the behavior of the library; the details of the
447 syntax for this can be found in the readline documentation available
447 syntax for this can be found in the readline documentation available
448 with your system or on the Internet. IPython doesn't read this file (if
448 with your system or on the Internet. IPython doesn't read this file (if
449 it exists) directly, but it does support passing to readline valid
449 it exists) directly, but it does support passing to readline valid
450 options via a simple interface. In brief, you can customize readline by
450 options via a simple interface. In brief, you can customize readline by
451 setting the following options in your configuration file (note
451 setting the following options in your configuration file (note
452 that these options can not be specified at the command line):
452 that these options can not be specified at the command line):
453
453
454 * **readline_parse_and_bind**: this holds a list of strings to be executed
454 * **readline_parse_and_bind**: this holds a list of strings to be executed
455 via a readline.parse_and_bind() command. The syntax for valid commands
455 via a readline.parse_and_bind() command. The syntax for valid commands
456 of this kind can be found by reading the documentation for the GNU
456 of this kind can be found by reading the documentation for the GNU
457 readline library, as these commands are of the kind which readline
457 readline library, as these commands are of the kind which readline
458 accepts in its configuration file.
458 accepts in its configuration file.
459 * **readline_remove_delims**: a string of characters to be removed
459 * **readline_remove_delims**: a string of characters to be removed
460 from the default word-delimiters list used by readline, so that
460 from the default word-delimiters list used by readline, so that
461 completions may be performed on strings which contain them. Do not
461 completions may be performed on strings which contain them. Do not
462 change the default value unless you know what you're doing.
462 change the default value unless you know what you're doing.
463
463
464 You will find the default values in your configuration file.
464 You will find the default values in your configuration file.
465
465
466
466
467 Session logging and restoring
467 Session logging and restoring
468 -----------------------------
468 -----------------------------
469
469
470 You can log all input from a session either by starting IPython with the
470 You can log all input from a session either by starting IPython with the
471 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
471 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
472 or by activating the logging at any moment with the magic function %logstart.
472 or by activating the logging at any moment with the magic function %logstart.
473
473
474 Log files can later be reloaded by running them as scripts and IPython
474 Log files can later be reloaded by running them as scripts and IPython
475 will attempt to 'replay' the log by executing all the lines in it, thus
475 will attempt to 'replay' the log by executing all the lines in it, thus
476 restoring the state of a previous session. This feature is not quite
476 restoring the state of a previous session. This feature is not quite
477 perfect, but can still be useful in many cases.
477 perfect, but can still be useful in many cases.
478
478
479 The log files can also be used as a way to have a permanent record of
479 The log files can also be used as a way to have a permanent record of
480 any code you wrote while experimenting. Log files are regular text files
480 any code you wrote while experimenting. Log files are regular text files
481 which you can later open in your favorite text editor to extract code or
481 which you can later open in your favorite text editor to extract code or
482 to 'clean them up' before using them to replay a session.
482 to 'clean them up' before using them to replay a session.
483
483
484 The `%logstart` function for activating logging in mid-session is used as
484 The `%logstart` function for activating logging in mid-session is used as
485 follows::
485 follows::
486
486
487 %logstart [log_name [log_mode]]
487 %logstart [log_name [log_mode]]
488
488
489 If no name is given, it defaults to a file named 'ipython_log.py' in your
489 If no name is given, it defaults to a file named 'ipython_log.py' in your
490 current working directory, in 'rotate' mode (see below).
490 current working directory, in 'rotate' mode (see below).
491
491
492 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
492 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
493 history up to that point and then continues logging.
493 history up to that point and then continues logging.
494
494
495 %logstart takes a second optional parameter: logging mode. This can be
495 %logstart takes a second optional parameter: logging mode. This can be
496 one of (note that the modes are given unquoted):
496 one of (note that the modes are given unquoted):
497
497
498 * [over:] overwrite existing log_name.
498 * [over:] overwrite existing log_name.
499 * [backup:] rename (if exists) to log_name~ and start log_name.
499 * [backup:] rename (if exists) to log_name~ and start log_name.
500 * [append:] well, that says it.
500 * [append:] well, that says it.
501 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
501 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
502
502
503 The %logoff and %logon functions allow you to temporarily stop and
503 The %logoff and %logon functions allow you to temporarily stop and
504 resume logging to a file which had previously been started with
504 resume logging to a file which had previously been started with
505 %logstart. They will fail (with an explanation) if you try to use them
505 %logstart. They will fail (with an explanation) if you try to use them
506 before logging has been started.
506 before logging has been started.
507
507
508 .. _system_shell_access:
508 .. _system_shell_access:
509
509
510 System shell access
510 System shell access
511 -------------------
511 -------------------
512
512
513 Any input line beginning with a ! character is passed verbatim (minus
513 Any input line beginning with a ! character is passed verbatim (minus
514 the !, of course) to the underlying operating system. For example,
514 the !, of course) to the underlying operating system. For example,
515 typing ``!ls`` will run 'ls' in the current directory.
515 typing ``!ls`` will run 'ls' in the current directory.
516
516
517 Manual capture of command output
517 Manual capture of command output
518 --------------------------------
518 --------------------------------
519
519
520 You can assign the result of a system command to a Python variable with the
520 You can assign the result of a system command to a Python variable with the
521 syntax ``myfiles = !ls``. This gets machine readable output from stdout
521 syntax ``myfiles = !ls``. This gets machine readable output from stdout
522 (e.g. without colours), and splits on newlines. To explicitly get this sort of
522 (e.g. without colours), and splits on newlines. To explicitly get this sort of
523 output without assigning to a variable, use two exclamation marks (``!!ls``) or
523 output without assigning to a variable, use two exclamation marks (``!!ls``) or
524 the ``%sx`` magic command.
524 the ``%sx`` magic command.
525
525
526 The captured list has some convenience features. ``myfiles.n`` or ``myfiles.s``
526 The captured list has some convenience features. ``myfiles.n`` or ``myfiles.s``
527 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
527 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
528 produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items.
528 produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items.
529 See :ref:`string_lists` for details.
529 See :ref:`string_lists` for details.
530
530
531 IPython also allows you to expand the value of python variables when
531 IPython also allows you to expand the value of python variables when
532 making system calls. Wrap variables or expressions in {braces}::
532 making system calls. Wrap variables or expressions in {braces}::
533
533
534 In [1]: pyvar = 'Hello world'
534 In [1]: pyvar = 'Hello world'
535 In [2]: !echo "A python variable: {pyvar}"
535 In [2]: !echo "A python variable: {pyvar}"
536 A python variable: Hello world
536 A python variable: Hello world
537 In [3]: import math
537 In [3]: import math
538 In [4]: x = 8
538 In [4]: x = 8
539 In [5]: !echo {math.factorial(x)}
539 In [5]: !echo {math.factorial(x)}
540 40320
540 40320
541
541
542 For simple cases, you can alternatively prepend $ to a variable name::
542 For simple cases, you can alternatively prepend $ to a variable name::
543
543
544 In [6]: !echo $sys.argv
544 In [6]: !echo $sys.argv
545 [/home/fperez/usr/bin/ipython]
545 [/home/fperez/usr/bin/ipython]
546 In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $
546 In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $
547 A system variable: /home/fperez
547 A system variable: /home/fperez
548
548
549 System command aliases
549 System command aliases
550 ----------------------
550 ----------------------
551
551
552 The %alias magic function allows you to define magic functions which are in fact
552 The %alias magic function allows you to define magic functions which are in fact
553 system shell commands. These aliases can have parameters.
553 system shell commands. These aliases can have parameters.
554
554
555 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
555 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
556
556
557 Then, typing ``alias_name params`` will execute the system command 'cmd
557 Then, typing ``alias_name params`` will execute the system command 'cmd
558 params' (from your underlying operating system).
558 params' (from your underlying operating system).
559
559
560 You can also define aliases with parameters using %s specifiers (one per
560 You can also define aliases with parameters using %s specifiers (one per
561 parameter). The following example defines the parts function as an
561 parameter). The following example defines the parts function as an
562 alias to the command 'echo first %s second %s' where each %s will be
562 alias to the command 'echo first %s second %s' where each %s will be
563 replaced by a positional parameter to the call to %parts::
563 replaced by a positional parameter to the call to %parts::
564
564
565 In [1]: %alias parts echo first %s second %s
565 In [1]: %alias parts echo first %s second %s
566 In [2]: parts A B
566 In [2]: parts A B
567 first A second B
567 first A second B
568 In [3]: parts A
568 In [3]: parts A
569 ERROR: Alias <parts> requires 2 arguments, 1 given.
569 ERROR: Alias <parts> requires 2 arguments, 1 given.
570
570
571 If called with no parameters, %alias prints the table of currently
571 If called with no parameters, %alias prints the table of currently
572 defined aliases.
572 defined aliases.
573
573
574 The %rehashx magic allows you to load your entire $PATH as
574 The %rehashx magic allows you to load your entire $PATH as
575 ipython aliases. See its docstring for further details.
575 ipython aliases. See its docstring for further details.
576
576
577
577
578 .. _dreload:
578 .. _dreload:
579
579
580 Recursive reload
580 Recursive reload
581 ----------------
581 ----------------
582
582
583 The :mod:`IPython.lib.deepreload` module allows you to recursively reload a
583 The :mod:`IPython.lib.deepreload` module allows you to recursively reload a
584 module: changes made to any of its dependencies will be reloaded without
584 module: changes made to any of its dependencies will be reloaded without
585 having to exit. To start using it, do::
585 having to exit. To start using it, do::
586
586
587 from IPython.lib.deepreload import reload as dreload
587 from IPython.lib.deepreload import reload as dreload
588
588
589
589
590 Verbose and colored exception traceback printouts
590 Verbose and colored exception traceback printouts
591 -------------------------------------------------
591 -------------------------------------------------
592
592
593 IPython provides the option to see very detailed exception tracebacks,
593 IPython provides the option to see very detailed exception tracebacks,
594 which can be especially useful when debugging large programs. You can
594 which can be especially useful when debugging large programs. You can
595 run any Python file with the %run function to benefit from these
595 run any Python file with the %run function to benefit from these
596 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
596 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
597 be colored (if your terminal supports it) which makes them much easier
597 be colored (if your terminal supports it) which makes them much easier
598 to parse visually.
598 to parse visually.
599
599
600 See the magic xmode and colors functions for details (just type %magic).
600 See the magic xmode and colors functions for details (just type %magic).
601
601
602 These features are basically a terminal version of Ka-Ping Yee's cgitb
602 These features are basically a terminal version of Ka-Ping Yee's cgitb
603 module, now part of the standard Python library.
603 module, now part of the standard Python library.
604
604
605
605
606 .. _input_caching:
606 .. _input_caching:
607
607
608 Input caching system
608 Input caching system
609 --------------------
609 --------------------
610
610
611 IPython offers numbered prompts (In/Out) with input and output caching
611 IPython offers numbered prompts (In/Out) with input and output caching
612 (also referred to as 'input history'). All input is saved and can be
612 (also referred to as 'input history'). All input is saved and can be
613 retrieved as variables (besides the usual arrow key recall), in
613 retrieved as variables (besides the usual arrow key recall), in
614 addition to the %rep magic command that brings a history entry
614 addition to the %rep magic command that brings a history entry
615 up for editing on the next command line.
615 up for editing on the next command line.
616
616
617 The following GLOBAL variables always exist (so don't overwrite them!):
617 The following GLOBAL variables always exist (so don't overwrite them!):
618
618
619 * _i, _ii, _iii: store previous, next previous and next-next previous inputs.
619 * _i, _ii, _iii: store previous, next previous and next-next previous inputs.
620 * In, _ih : a list of all inputs; _ih[n] is the input from line n. If you
620 * In, _ih : a list of all inputs; _ih[n] is the input from line n. If you
621 overwrite In with a variable of your own, you can remake the assignment to the
621 overwrite In with a variable of your own, you can remake the assignment to the
622 internal list with a simple ``In=_ih``.
622 internal list with a simple ``In=_ih``.
623
623
624 Additionally, global variables named _i<n> are dynamically created (<n>
624 Additionally, global variables named _i<n> are dynamically created (<n>
625 being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``.
625 being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``.
626
626
627 For example, what you typed at prompt 14 is available as _i14, _ih[14]
627 For example, what you typed at prompt 14 is available as _i14, _ih[14]
628 and In[14].
628 and In[14].
629
629
630 This allows you to easily cut and paste multi line interactive prompts
630 This allows you to easily cut and paste multi line interactive prompts
631 by printing them out: they print like a clean string, without prompt
631 by printing them out: they print like a clean string, without prompt
632 characters. You can also manipulate them like regular variables (they
632 characters. You can also manipulate them like regular variables (they
633 are strings), modify or exec them (typing ``exec _i9`` will re-execute the
633 are strings), modify or exec them (typing ``exec _i9`` will re-execute the
634 contents of input prompt 9.
634 contents of input prompt 9.
635
635
636 You can also re-execute multiple lines of input easily by using the
636 You can also re-execute multiple lines of input easily by using the
637 magic %rerun or %macro functions. The macro system also allows you to re-execute
637 magic %rerun or %macro functions. The macro system also allows you to re-execute
638 previous lines which include magic function calls (which require special
638 previous lines which include magic function calls (which require special
639 processing). Type %macro? for more details on the macro system.
639 processing). Type %macro? for more details on the macro system.
640
640
641 A history function %hist allows you to see any part of your input
641 A history function %hist allows you to see any part of your input
642 history by printing a range of the _i variables.
642 history by printing a range of the _i variables.
643
643
644 You can also search ('grep') through your history by typing
644 You can also search ('grep') through your history by typing
645 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
645 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
646 etc. You can bring history entries listed by '%hist -g' up for editing
646 etc. You can bring history entries listed by '%hist -g' up for editing
647 with the %recall command, or run them immediately with %rerun.
647 with the %recall command, or run them immediately with %rerun.
648
648
649 .. _output_caching:
649 .. _output_caching:
650
650
651 Output caching system
651 Output caching system
652 ---------------------
652 ---------------------
653
653
654 For output that is returned from actions, a system similar to the input
654 For output that is returned from actions, a system similar to the input
655 cache exists but using _ instead of _i. Only actions that produce a
655 cache exists but using _ instead of _i. Only actions that produce a
656 result (NOT assignments, for example) are cached. If you are familiar
656 result (NOT assignments, for example) are cached. If you are familiar
657 with Mathematica, IPython's _ variables behave exactly like
657 with Mathematica, IPython's _ variables behave exactly like
658 Mathematica's % variables.
658 Mathematica's % variables.
659
659
660 The following GLOBAL variables always exist (so don't overwrite them!):
660 The following GLOBAL variables always exist (so don't overwrite them!):
661
661
662 * [_] (a single underscore) : stores previous output, like Python's
662 * [_] (a single underscore) : stores previous output, like Python's
663 default interpreter.
663 default interpreter.
664 * [__] (two underscores): next previous.
664 * [__] (two underscores): next previous.
665 * [___] (three underscores): next-next previous.
665 * [___] (three underscores): next-next previous.
666
666
667 Additionally, global variables named _<n> are dynamically created (<n>
667 Additionally, global variables named _<n> are dynamically created (<n>
668 being the prompt counter), such that the result of output <n> is always
668 being the prompt counter), such that the result of output <n> is always
669 available as _<n> (don't use the angle brackets, just the number, e.g.
669 available as _<n> (don't use the angle brackets, just the number, e.g.
670 _21).
670 _21).
671
671
672 These variables are also stored in a global dictionary (not a
672 These variables are also stored in a global dictionary (not a
673 list, since it only has entries for lines which returned a result)
673 list, since it only has entries for lines which returned a result)
674 available under the names _oh and Out (similar to _ih and In). So the
674 available under the names _oh and Out (similar to _ih and In). So the
675 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
675 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
676 accidentally overwrite the Out variable you can recover it by typing
676 accidentally overwrite the Out variable you can recover it by typing
677 'Out=_oh' at the prompt.
677 'Out=_oh' at the prompt.
678
678
679 This system obviously can potentially put heavy memory demands on your
679 This system obviously can potentially put heavy memory demands on your
680 system, since it prevents Python's garbage collector from removing any
680 system, since it prevents Python's garbage collector from removing any
681 previously computed results. You can control how many results are kept
681 previously computed results. You can control how many results are kept
682 in memory with the option (at the command line or in your configuration
682 in memory with the option (at the command line or in your configuration
683 file) cache_size. If you set it to 0, the whole system is completely
683 file) cache_size. If you set it to 0, the whole system is completely
684 disabled and the prompts revert to the classic '>>>' of normal Python.
684 disabled and the prompts revert to the classic '>>>' of normal Python.
685
685
686
686
687 Directory history
687 Directory history
688 -----------------
688 -----------------
689
689
690 Your history of visited directories is kept in the global list _dh, and
690 Your history of visited directories is kept in the global list _dh, and
691 the magic %cd command can be used to go to any entry in that list. The
691 the magic %cd command can be used to go to any entry in that list. The
692 %dhist command allows you to view this history. Do ``cd -<TAB>`` to
692 %dhist command allows you to view this history. Do ``cd -<TAB>`` to
693 conveniently view the directory history.
693 conveniently view the directory history.
694
694
695
695
696 Automatic parentheses and quotes
696 Automatic parentheses and quotes
697 --------------------------------
697 --------------------------------
698
698
699 These features were adapted from Nathan Gray's LazyPython. They are
699 These features were adapted from Nathan Gray's LazyPython. They are
700 meant to allow less typing for common situations.
700 meant to allow less typing for common situations.
701
701
702
702
703 Automatic parentheses
703 Automatic parentheses
704 +++++++++++++++++++++
704 +++++++++++++++++++++
705
705
706 Callable objects (i.e. functions, methods, etc) can be invoked like this
706 Callable objects (i.e. functions, methods, etc) can be invoked like this
707 (notice the commas between the arguments)::
707 (notice the commas between the arguments)::
708
708
709 In [1]: callable_ob arg1, arg2, arg3
709 In [1]: callable_ob arg1, arg2, arg3
710 ------> callable_ob(arg1, arg2, arg3)
710 ------> callable_ob(arg1, arg2, arg3)
711
711
712 You can force automatic parentheses by using '/' as the first character
712 You can force automatic parentheses by using '/' as the first character
713 of a line. For example::
713 of a line. For example::
714
714
715 In [2]: /globals # becomes 'globals()'
715 In [2]: /globals # becomes 'globals()'
716
716
717 Note that the '/' MUST be the first character on the line! This won't work::
717 Note that the '/' MUST be the first character on the line! This won't work::
718
718
719 In [3]: print /globals # syntax error
719 In [3]: print /globals # syntax error
720
720
721 In most cases the automatic algorithm should work, so you should rarely
721 In most cases the automatic algorithm should work, so you should rarely
722 need to explicitly invoke /. One notable exception is if you are trying
722 need to explicitly invoke /. One notable exception is if you are trying
723 to call a function with a list of tuples as arguments (the parenthesis
723 to call a function with a list of tuples as arguments (the parenthesis
724 will confuse IPython)::
724 will confuse IPython)::
725
725
726 In [4]: zip (1,2,3),(4,5,6) # won't work
726 In [4]: zip (1,2,3),(4,5,6) # won't work
727
727
728 but this will work::
728 but this will work::
729
729
730 In [5]: /zip (1,2,3),(4,5,6)
730 In [5]: /zip (1,2,3),(4,5,6)
731 ------> zip ((1,2,3),(4,5,6))
731 ------> zip ((1,2,3),(4,5,6))
732 Out[5]: [(1, 4), (2, 5), (3, 6)]
732 Out[5]: [(1, 4), (2, 5), (3, 6)]
733
733
734 IPython tells you that it has altered your command line by displaying
734 IPython tells you that it has altered your command line by displaying
735 the new command line preceded by ->. e.g.::
735 the new command line preceded by ->. e.g.::
736
736
737 In [6]: callable list
737 In [6]: callable list
738 ------> callable(list)
738 ------> callable(list)
739
739
740
740
741 Automatic quoting
741 Automatic quoting
742 +++++++++++++++++
742 +++++++++++++++++
743
743
744 You can force automatic quoting of a function's arguments by using ','
744 You can force automatic quoting of a function's arguments by using ','
745 or ';' as the first character of a line. For example::
745 or ';' as the first character of a line. For example::
746
746
747 In [1]: ,my_function /home/me # becomes my_function("/home/me")
747 In [1]: ,my_function /home/me # becomes my_function("/home/me")
748
748
749 If you use ';' the whole argument is quoted as a single string, while ',' splits
749 If you use ';' the whole argument is quoted as a single string, while ',' splits
750 on whitespace::
750 on whitespace::
751
751
752 In [2]: ,my_function a b c # becomes my_function("a","b","c")
752 In [2]: ,my_function a b c # becomes my_function("a","b","c")
753
753
754 In [3]: ;my_function a b c # becomes my_function("a b c")
754 In [3]: ;my_function a b c # becomes my_function("a b c")
755
755
756 Note that the ',' or ';' MUST be the first character on the line! This
756 Note that the ',' or ';' MUST be the first character on the line! This
757 won't work::
757 won't work::
758
758
759 In [4]: x = ,my_function /home/me # syntax error
759 In [4]: x = ,my_function /home/me # syntax error
760
760
761 IPython as your default Python environment
761 IPython as your default Python environment
762 ==========================================
762 ==========================================
763
763
764 Python honors the environment variable PYTHONSTARTUP and will execute at
764 Python honors the environment variable PYTHONSTARTUP and will execute at
765 startup the file referenced by this variable. If you put the following code at
765 startup the file referenced by this variable. If you put the following code at
766 the end of that file, then IPython will be your working environment anytime you
766 the end of that file, then IPython will be your working environment anytime you
767 start Python::
767 start Python::
768
768
769 from IPython.frontend.terminal.ipapp import launch_new_instance
769 from IPython.frontend.terminal.ipapp import launch_new_instance
770 launch_new_instance()
770 launch_new_instance()
771 raise SystemExit
771 raise SystemExit
772
772
773 The ``raise SystemExit`` is needed to exit Python when
773 The ``raise SystemExit`` is needed to exit Python when
774 it finishes, otherwise you'll be back at the normal Python '>>>'
774 it finishes, otherwise you'll be back at the normal Python '>>>'
775 prompt.
775 prompt.
776
776
777 This is probably useful to developers who manage multiple Python
777 This is probably useful to developers who manage multiple Python
778 versions and don't want to have correspondingly multiple IPython
778 versions and don't want to have correspondingly multiple IPython
779 versions. Note that in this mode, there is no way to pass IPython any
779 versions. Note that in this mode, there is no way to pass IPython any
780 command-line options, as those are trapped first by Python itself.
780 command-line options, as those are trapped first by Python itself.
781
781
782 .. _Embedding:
782 .. _Embedding:
783
783
784 Embedding IPython
784 Embedding IPython
785 =================
785 =================
786
786
787 You can start a regular IPython session with
787 You can start a regular IPython session with
788
788
789 .. sourcecode:: python
789 .. sourcecode:: python
790
790
791 import IPython
791 import IPython
792 IPython.start_ipython()
792 IPython.start_ipython()
793
793
794 at any point in your program. This will load IPython configuration,
794 at any point in your program. This will load IPython configuration,
795 startup files, and everything, just as if it were a normal IPython session.
795 startup files, and everything, just as if it were a normal IPython session.
796 In addition to this,
796 In addition to this,
797 it is possible to embed an IPython instance inside your own Python programs.
797 it is possible to embed an IPython instance inside your own Python programs.
798 This allows you to evaluate dynamically the state of your code,
798 This allows you to evaluate dynamically the state of your code,
799 operate with your variables, analyze them, etc. Note however that
799 operate with your variables, analyze them, etc. Note however that
800 any changes you make to values while in the shell do not propagate back
800 any changes you make to values while in the shell do not propagate back
801 to the running code, so it is safe to modify your values because you
801 to the running code, so it is safe to modify your values because you
802 won't break your code in bizarre ways by doing so.
802 won't break your code in bizarre ways by doing so.
803
803
804 .. note::
804 .. note::
805
805
806 At present, embedding IPython cannot be done from inside IPython.
806 At present, embedding IPython cannot be done from inside IPython.
807 Run the code samples below outside IPython.
807 Run the code samples below outside IPython.
808
808
809 This feature allows you to easily have a fully functional python
809 This feature allows you to easily have a fully functional python
810 environment for doing object introspection anywhere in your code with a
810 environment for doing object introspection anywhere in your code with a
811 simple function call. In some cases a simple print statement is enough,
811 simple function call. In some cases a simple print statement is enough,
812 but if you need to do more detailed analysis of a code fragment this
812 but if you need to do more detailed analysis of a code fragment this
813 feature can be very valuable.
813 feature can be very valuable.
814
814
815 It can also be useful in scientific computing situations where it is
815 It can also be useful in scientific computing situations where it is
816 common to need to do some automatic, computationally intensive part and
816 common to need to do some automatic, computationally intensive part and
817 then stop to look at data, plots, etc.
817 then stop to look at data, plots, etc.
818 Opening an IPython instance will give you full access to your data and
818 Opening an IPython instance will give you full access to your data and
819 functions, and you can resume program execution once you are done with
819 functions, and you can resume program execution once you are done with
820 the interactive part (perhaps to stop again later, as many times as
820 the interactive part (perhaps to stop again later, as many times as
821 needed).
821 needed).
822
822
823 The following code snippet is the bare minimum you need to include in
823 The following code snippet is the bare minimum you need to include in
824 your Python programs for this to work (detailed examples follow later)::
824 your Python programs for this to work (detailed examples follow later)::
825
825
826 from IPython import embed
826 from IPython import embed
827
827
828 embed() # this call anywhere in your program will start IPython
828 embed() # this call anywhere in your program will start IPython
829
829
830 .. note::
830 .. note::
831
831
832 As of 0.13, you can embed an IPython *kernel*, for use with qtconsole,
832 As of 0.13, you can embed an IPython *kernel*, for use with qtconsole,
833 etc. via ``IPython.embed_kernel()`` instead of ``IPython.embed()``.
833 etc. via ``IPython.embed_kernel()`` instead of ``IPython.embed()``.
834 It should function just the same as regular embed, but you connect
834 It should function just the same as regular embed, but you connect
835 an external frontend rather than IPython starting up in the local
835 an external frontend rather than IPython starting up in the local
836 terminal.
836 terminal.
837
837
838 You can run embedded instances even in code which is itself being run at
838 You can run embedded instances even in code which is itself being run at
839 the IPython interactive prompt with '%run <filename>'. Since it's easy
839 the IPython interactive prompt with '%run <filename>'. Since it's easy
840 to get lost as to where you are (in your top-level IPython or in your
840 to get lost as to where you are (in your top-level IPython or in your
841 embedded one), it's a good idea in such cases to set the in/out prompts
841 embedded one), it's a good idea in such cases to set the in/out prompts
842 to something different for the embedded instances. The code examples
842 to something different for the embedded instances. The code examples
843 below illustrate this.
843 below illustrate this.
844
844
845 You can also have multiple IPython instances in your program and open
845 You can also have multiple IPython instances in your program and open
846 them separately, for example with different options for data
846 them separately, for example with different options for data
847 presentation. If you close and open the same instance multiple times,
847 presentation. If you close and open the same instance multiple times,
848 its prompt counters simply continue from each execution to the next.
848 its prompt counters simply continue from each execution to the next.
849
849
850 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
850 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
851 module for more details on the use of this system.
851 module for more details on the use of this system.
852
852
853 The following sample file illustrating how to use the embedding
853 The following sample file illustrating how to use the embedding
854 functionality is provided in the examples directory as example-embed.py.
854 functionality is provided in the examples directory as example-embed.py.
855 It should be fairly self-explanatory:
855 It should be fairly self-explanatory:
856
856
857 .. literalinclude:: ../../../examples/core/example-embed.py
857 .. literalinclude:: ../../../examples/core/example-embed.py
858 :language: python
858 :language: python
859
859
860 Once you understand how the system functions, you can use the following
860 Once you understand how the system functions, you can use the following
861 code fragments in your programs which are ready for cut and paste:
861 code fragments in your programs which are ready for cut and paste:
862
862
863 .. literalinclude:: ../../../examples/core/example-embed-short.py
863 .. literalinclude:: ../../../examples/core/example-embed-short.py
864 :language: python
864 :language: python
865
865
866 Using the Python debugger (pdb)
866 Using the Python debugger (pdb)
867 ===============================
867 ===============================
868
868
869 Running entire programs via pdb
869 Running entire programs via pdb
870 -------------------------------
870 -------------------------------
871
871
872 pdb, the Python debugger, is a powerful interactive debugger which
872 pdb, the Python debugger, is a powerful interactive debugger which
873 allows you to step through code, set breakpoints, watch variables,
873 allows you to step through code, set breakpoints, watch variables,
874 etc. IPython makes it very easy to start any script under the control
874 etc. IPython makes it very easy to start any script under the control
875 of pdb, regardless of whether you have wrapped it into a 'main()'
875 of pdb, regardless of whether you have wrapped it into a 'main()'
876 function or not. For this, simply type '%run -d myscript' at an
876 function or not. For this, simply type '%run -d myscript' at an
877 IPython prompt. See the %run command's documentation (via '%run?' or
877 IPython prompt. See the %run command's documentation (via '%run?' or
878 in Sec. magic_ for more details, including how to control where pdb
878 in Sec. magic_ for more details, including how to control where pdb
879 will stop execution first.
879 will stop execution first.
880
880
881 For more information on the use of the pdb debugger, read the included
881 For more information on the use of the pdb debugger, read the included
882 pdb.doc file (part of the standard Python distribution). On a stock
882 pdb.doc file (part of the standard Python distribution). On a stock
883 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
883 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
884 easiest way to read it is by using the help() function of the pdb module
884 easiest way to read it is by using the help() function of the pdb module
885 as follows (in an IPython prompt)::
885 as follows (in an IPython prompt)::
886
886
887 In [1]: import pdb
887 In [1]: import pdb
888 In [2]: pdb.help()
888 In [2]: pdb.help()
889
889
890 This will load the pdb.doc document in a file viewer for you automatically.
890 This will load the pdb.doc document in a file viewer for you automatically.
891
891
892
892
893 Automatic invocation of pdb on exceptions
893 Automatic invocation of pdb on exceptions
894 -----------------------------------------
894 -----------------------------------------
895
895
896 IPython, if started with the ``--pdb`` option (or if the option is set in
896 IPython, if started with the ``--pdb`` option (or if the option is set in
897 your config file) can call the Python pdb debugger every time your code
897 your config file) can call the Python pdb debugger every time your code
898 triggers an uncaught exception. This feature
898 triggers an uncaught exception. This feature
899 can also be toggled at any time with the %pdb magic command. This can be
899 can also be toggled at any time with the %pdb magic command. This can be
900 extremely useful in order to find the origin of subtle bugs, because pdb
900 extremely useful in order to find the origin of subtle bugs, because pdb
901 opens up at the point in your code which triggered the exception, and
901 opens up at the point in your code which triggered the exception, and
902 while your program is at this point 'dead', all the data is still
902 while your program is at this point 'dead', all the data is still
903 available and you can walk up and down the stack frame and understand
903 available and you can walk up and down the stack frame and understand
904 the origin of the problem.
904 the origin of the problem.
905
905
906 Furthermore, you can use these debugging facilities both with the
906 Furthermore, you can use these debugging facilities both with the
907 embedded IPython mode and without IPython at all. For an embedded shell
907 embedded IPython mode and without IPython at all. For an embedded shell
908 (see sec. Embedding_), simply call the constructor with
908 (see sec. Embedding_), simply call the constructor with
909 ``--pdb`` in the argument string and pdb will automatically be called if an
909 ``--pdb`` in the argument string and pdb will automatically be called if an
910 uncaught exception is triggered by your code.
910 uncaught exception is triggered by your code.
911
911
912 For stand-alone use of the feature in your programs which do not use
912 For stand-alone use of the feature in your programs which do not use
913 IPython at all, put the following lines toward the top of your 'main'
913 IPython at all, put the following lines toward the top of your 'main'
914 routine::
914 routine::
915
915
916 import sys
916 import sys
917 from IPython.core import ultratb
917 from IPython.core import ultratb
918 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
918 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
919 color_scheme='Linux', call_pdb=1)
919 color_scheme='Linux', call_pdb=1)
920
920
921 The mode keyword can be either 'Verbose' or 'Plain', giving either very
921 The mode keyword can be either 'Verbose' or 'Plain', giving either very
922 detailed or normal tracebacks respectively. The color_scheme keyword can
922 detailed or normal tracebacks respectively. The color_scheme keyword can
923 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
923 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
924 options which can be set in IPython with ``--colors`` and ``--xmode``.
924 options which can be set in IPython with ``--colors`` and ``--xmode``.
925
925
926 This will give any of your programs detailed, colored tracebacks with
926 This will give any of your programs detailed, colored tracebacks with
927 automatic invocation of pdb.
927 automatic invocation of pdb.
928
928
929
929
930 Extensions for syntax processing
930 Extensions for syntax processing
931 ================================
931 ================================
932
932
933 This isn't for the faint of heart, because the potential for breaking
933 This isn't for the faint of heart, because the potential for breaking
934 things is quite high. But it can be a very powerful and useful feature.
934 things is quite high. But it can be a very powerful and useful feature.
935 In a nutshell, you can redefine the way IPython processes the user input
935 In a nutshell, you can redefine the way IPython processes the user input
936 line to accept new, special extensions to the syntax without needing to
936 line to accept new, special extensions to the syntax without needing to
937 change any of IPython's own code.
937 change any of IPython's own code.
938
938
939 In the IPython/extensions directory you will find some examples
939 In the IPython/extensions directory you will find some examples
940 supplied, which we will briefly describe now. These can be used 'as is'
940 supplied, which we will briefly describe now. These can be used 'as is'
941 (and both provide very useful functionality), or you can use them as a
941 (and both provide very useful functionality), or you can use them as a
942 starting point for writing your own extensions.
942 starting point for writing your own extensions.
943
943
944 .. _pasting_with_prompts:
944 .. _pasting_with_prompts:
945
945
946 Pasting of code starting with Python or IPython prompts
946 Pasting of code starting with Python or IPython prompts
947 -------------------------------------------------------
947 -------------------------------------------------------
948
948
949 IPython is smart enough to filter out input prompts, be they plain Python ones
949 IPython is smart enough to filter out input prompts, be they plain Python ones
950 (``>>>`` and ``...``) or IPython ones (``In [N]:`` and ``...:``). You can
950 (``>>>`` and ``...``) or IPython ones (``In [N]:`` and ``...:``). You can
951 therefore copy and paste from existing interactive sessions without worry.
951 therefore copy and paste from existing interactive sessions without worry.
952
952
953 The following is a 'screenshot' of how things work, copying an example from the
953 The following is a 'screenshot' of how things work, copying an example from the
954 standard Python tutorial::
954 standard Python tutorial::
955
955
956 In [1]: >>> # Fibonacci series:
956 In [1]: >>> # Fibonacci series:
957
957
958 In [2]: ... # the sum of two elements defines the next
958 In [2]: ... # the sum of two elements defines the next
959
959
960 In [3]: ... a, b = 0, 1
960 In [3]: ... a, b = 0, 1
961
961
962 In [4]: >>> while b < 10:
962 In [4]: >>> while b < 10:
963 ...: ... print b
963 ...: ... print b
964 ...: ... a, b = b, a+b
964 ...: ... a, b = b, a+b
965 ...:
965 ...:
966 1
966 1
967 1
967 1
968 2
968 2
969 3
969 3
970 5
970 5
971 8
971 8
972
972
973 And pasting from IPython sessions works equally well::
973 And pasting from IPython sessions works equally well::
974
974
975 In [1]: In [5]: def f(x):
975 In [1]: In [5]: def f(x):
976 ...: ...: "A simple function"
976 ...: ...: "A simple function"
977 ...: ...: return x**2
977 ...: ...: return x**2
978 ...: ...:
978 ...: ...:
979
979
980 In [2]: f(3)
980 In [2]: f(3)
981 Out[2]: 9
981 Out[2]: 9
982
982
983 .. _gui_support:
983 .. _gui_support:
984
984
985 GUI event loop support
985 GUI event loop support
986 ======================
986 ======================
987
987
988 .. versionadded:: 0.11
988 .. versionadded:: 0.11
989 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
989 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
990
990
991 IPython has excellent support for working interactively with Graphical User
991 IPython has excellent support for working interactively with Graphical User
992 Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is
992 Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is
993 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
993 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
994 is extremely robust compared to our previous thread-based version. The
994 is extremely robust compared to our previous thread-based version. The
995 advantages of this are:
995 advantages of this are:
996
996
997 * GUIs can be enabled and disabled dynamically at runtime.
997 * GUIs can be enabled and disabled dynamically at runtime.
998 * The active GUI can be switched dynamically at runtime.
998 * The active GUI can be switched dynamically at runtime.
999 * In some cases, multiple GUIs can run simultaneously with no problems.
999 * In some cases, multiple GUIs can run simultaneously with no problems.
1000 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
1000 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
1001 all of these things.
1001 all of these things.
1002
1002
1003 For users, enabling GUI event loop integration is simple. You simple use the
1003 For users, enabling GUI event loop integration is simple. You simple use the
1004 ``%gui`` magic as follows::
1004 ``%gui`` magic as follows::
1005
1005
1006 %gui [GUINAME]
1006 %gui [GUINAME]
1007
1007
1008 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
1008 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
1009 arguments are ``wx``, ``qt``, ``gtk`` and ``tk``.
1009 arguments are ``wx``, ``qt``, ``gtk`` and ``tk``.
1010
1010
1011 Thus, to use wxPython interactively and create a running :class:`wx.App`
1011 Thus, to use wxPython interactively and create a running :class:`wx.App`
1012 object, do::
1012 object, do::
1013
1013
1014 %gui wx
1014 %gui wx
1015
1015
1016 For information on IPython's matplotlib_ integration (and the ``matplotlib``
1016 For information on IPython's matplotlib_ integration (and the ``matplotlib``
1017 mode) see :ref:`this section <matplotlib_support>`.
1017 mode) see :ref:`this section <matplotlib_support>`.
1018
1018
1019 For developers that want to use IPython's GUI event loop integration in the
1019 For developers that want to use IPython's GUI event loop integration in the
1020 form of a library, these capabilities are exposed in library form in the
1020 form of a library, these capabilities are exposed in library form in the
1021 :mod:`IPython.lib.inputhook` and :mod:`IPython.lib.guisupport` modules.
1021 :mod:`IPython.lib.inputhook` and :mod:`IPython.lib.guisupport` modules.
1022 Interested developers should see the module docstrings for more information,
1022 Interested developers should see the module docstrings for more information,
1023 but there are a few points that should be mentioned here.
1023 but there are a few points that should be mentioned here.
1024
1024
1025 First, the ``PyOSInputHook`` approach only works in command line settings
1025 First, the ``PyOSInputHook`` approach only works in command line settings
1026 where readline is activated. The integration with various eventloops
1026 where readline is activated. The integration with various eventloops
1027 is handled somewhat differently (and more simply) when using the standalone
1027 is handled somewhat differently (and more simply) when using the standalone
1028 kernel, as in the qtconsole and notebook.
1028 kernel, as in the qtconsole and notebook.
1029
1029
1030 Second, when using the ``PyOSInputHook`` approach, a GUI application should
1030 Second, when using the ``PyOSInputHook`` approach, a GUI application should
1031 *not* start its event loop. Instead all of this is handled by the
1031 *not* start its event loop. Instead all of this is handled by the
1032 ``PyOSInputHook``. This means that applications that are meant to be used both
1032 ``PyOSInputHook``. This means that applications that are meant to be used both
1033 in IPython and as standalone apps need to have special code to detects how the
1033 in IPython and as standalone apps need to have special code to detects how the
1034 application is being run. We highly recommend using IPython's support for this.
1034 application is being run. We highly recommend using IPython's support for this.
1035 Since the details vary slightly between toolkits, we point you to the various
1035 Since the details vary slightly between toolkits, we point you to the various
1036 examples in our source directory :file:`examples/lib` that demonstrate
1036 examples in our source directory :file:`examples/lib` that demonstrate
1037 these capabilities.
1037 these capabilities.
1038
1038
1039 Third, unlike previous versions of IPython, we no longer "hijack" (replace
1039 Third, unlike previous versions of IPython, we no longer "hijack" (replace
1040 them with no-ops) the event loops. This is done to allow applications that
1040 them with no-ops) the event loops. This is done to allow applications that
1041 actually need to run the real event loops to do so. This is often needed to
1041 actually need to run the real event loops to do so. This is often needed to
1042 process pending events at critical points.
1042 process pending events at critical points.
1043
1043
1044 Finally, we also have a number of examples in our source directory
1044 Finally, we also have a number of examples in our source directory
1045 :file:`examples/lib` that demonstrate these capabilities.
1045 :file:`examples/lib` that demonstrate these capabilities.
1046
1046
1047 PyQt and PySide
1047 PyQt and PySide
1048 ---------------
1048 ---------------
1049
1049
1050 .. attempt at explanation of the complete mess that is Qt support
1050 .. attempt at explanation of the complete mess that is Qt support
1051
1051
1052 When you use ``--gui=qt`` or ``--matplotlib=qt``, IPython can work with either
1052 When you use ``--gui=qt`` or ``--matplotlib=qt``, IPython can work with either
1053 PyQt4 or PySide. There are three options for configuration here, because
1053 PyQt4 or PySide. There are three options for configuration here, because
1054 PyQt4 has two APIs for QString and QVariant - v1, which is the default on
1054 PyQt4 has two APIs for QString and QVariant - v1, which is the default on
1055 Python 2, and the more natural v2, which is the only API supported by PySide.
1055 Python 2, and the more natural v2, which is the only API supported by PySide.
1056 v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole
1056 v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole
1057 uses v2, but you can still use any interface in your code, since the
1057 uses v2, but you can still use any interface in your code, since the
1058 Qt frontend is in a different process.
1058 Qt frontend is in a different process.
1059
1059
1060 The default will be to import PyQt4 without configuration of the APIs, thus
1060 The default will be to import PyQt4 without configuration of the APIs, thus
1061 matching what most applications would expect. It will fall back of PySide if
1061 matching what most applications would expect. It will fall back of PySide if
1062 PyQt4 is unavailable.
1062 PyQt4 is unavailable.
1063
1063
1064 If specified, IPython will respect the environment variable ``QT_API`` used
1064 If specified, IPython will respect the environment variable ``QT_API`` used
1065 by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires
1065 by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires
1066 PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used,
1066 PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used,
1067 and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for
1067 and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for
1068 QString and QVariant, so ETS codes like MayaVi will also work with IPython.
1068 QString and QVariant, so ETS codes like MayaVi will also work with IPython.
1069
1069
1070 If you launch IPython in matplotlib mode with ``ipython --matplotlib=qt``,
1070 If you launch IPython in matplotlib mode with ``ipython --matplotlib=qt``,
1071 then IPython will ask matplotlib which Qt library to use (only if QT_API is
1071 then IPython will ask matplotlib which Qt library to use (only if QT_API is
1072 *not set*), via the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or
1072 *not set*), via the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or
1073 older, then IPython will always use PyQt4 without setting the v2 APIs, since
1073 older, then IPython will always use PyQt4 without setting the v2 APIs, since
1074 neither v2 PyQt nor PySide work.
1074 neither v2 PyQt nor PySide work.
1075
1075
1076 .. warning::
1076 .. warning::
1077
1077
1078 Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set
1078 Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set
1079 to work with IPython's qt integration, because otherwise PyQt4 will be
1079 to work with IPython's qt integration, because otherwise PyQt4 will be
1080 loaded in an incompatible mode.
1080 loaded in an incompatible mode.
1081
1081
1082 It also means that you must *not* have ``QT_API`` set if you want to
1082 It also means that you must *not* have ``QT_API`` set if you want to
1083 use ``--gui=qt`` with code that requires PyQt4 API v1.
1083 use ``--gui=qt`` with code that requires PyQt4 API v1.
1084
1084
1085
1085
1086 .. _matplotlib_support:
1086 .. _matplotlib_support:
1087
1087
1088 Plotting with matplotlib
1088 Plotting with matplotlib
1089 ========================
1089 ========================
1090
1090
1091 matplotlib_ provides high quality 2D and 3D plotting for Python. matplotlib_
1091 matplotlib_ provides high quality 2D and 3D plotting for Python. matplotlib_
1092 can produce plots on screen using a variety of GUI toolkits, including Tk,
1092 can produce plots on screen using a variety of GUI toolkits, including Tk,
1093 PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for
1093 PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for
1094 scientific computing, all with a syntax compatible with that of the popular
1094 scientific computing, all with a syntax compatible with that of the popular
1095 Matlab program.
1095 Matlab program.
1096
1096
1097 To start IPython with matplotlib support, use the ``--matplotlib`` switch. If
1097 To start IPython with matplotlib support, use the ``--matplotlib`` switch. If
1098 IPython is already running, you can run the ``%matplotlib`` magic. If no
1098 IPython is already running, you can run the ``%matplotlib`` magic. If no
1099 arguments are given, IPython will automatically detect your choice of
1099 arguments are given, IPython will automatically detect your choice of
1100 matplotlib backend. You can also request a specific backend with
1100 matplotlib backend. You can also request a specific backend with
1101 ``%matplotlib backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx',
1101 ``%matplotlib backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx',
1102 'gtk', 'osx'. In the web notebook and Qt console, 'inline' is also a valid
1102 'gtk', 'osx'. In the web notebook and Qt console, 'inline' is also a valid
1103 backend value, which produces static figures inlined inside the application
1103 backend value, which produces static figures inlined inside the application
1104 window instead of matplotlib's interactive figures that live in separate
1104 window instead of matplotlib's interactive figures that live in separate
1105 windows.
1105 windows.
1106
1106
1107 .. _interactive_demos:
1107 .. _interactive_demos:
1108
1108
1109 Interactive demos with IPython
1109 Interactive demos with IPython
1110 ==============================
1110 ==============================
1111
1111
1112 IPython ships with a basic system for running scripts interactively in
1112 IPython ships with a basic system for running scripts interactively in
1113 sections, useful when presenting code to audiences. A few tags embedded
1113 sections, useful when presenting code to audiences. A few tags embedded
1114 in comments (so that the script remains valid Python code) divide a file
1114 in comments (so that the script remains valid Python code) divide a file
1115 into separate blocks, and the demo can be run one block at a time, with
1115 into separate blocks, and the demo can be run one block at a time, with
1116 IPython printing (with syntax highlighting) the block before executing
1116 IPython printing (with syntax highlighting) the block before executing
1117 it, and returning to the interactive prompt after each block. The
1117 it, and returning to the interactive prompt after each block. The
1118 interactive namespace is updated after each block is run with the
1118 interactive namespace is updated after each block is run with the
1119 contents of the demo's namespace.
1119 contents of the demo's namespace.
1120
1120
1121 This allows you to show a piece of code, run it and then execute
1121 This allows you to show a piece of code, run it and then execute
1122 interactively commands based on the variables just created. Once you
1122 interactively commands based on the variables just created. Once you
1123 want to continue, you simply execute the next block of the demo. The
1123 want to continue, you simply execute the next block of the demo. The
1124 following listing shows the markup necessary for dividing a script into
1124 following listing shows the markup necessary for dividing a script into
1125 sections for execution as a demo:
1125 sections for execution as a demo:
1126
1126
1127 .. literalinclude:: ../../../examples/lib/example-demo.py
1127 .. literalinclude:: ../../../examples/lib/example-demo.py
1128 :language: python
1128 :language: python
1129
1129
1130 In order to run a file as a demo, you must first make a Demo object out
1130 In order to run a file as a demo, you must first make a Demo object out
1131 of it. If the file is named myscript.py, the following code will make a
1131 of it. If the file is named myscript.py, the following code will make a
1132 demo::
1132 demo::
1133
1133
1134 from IPython.lib.demo import Demo
1134 from IPython.lib.demo import Demo
1135
1135
1136 mydemo = Demo('myscript.py')
1136 mydemo = Demo('myscript.py')
1137
1137
1138 This creates the mydemo object, whose blocks you run one at a time by
1138 This creates the mydemo object, whose blocks you run one at a time by
1139 simply calling the object with no arguments. If you have autocall active
1139 simply calling the object with no arguments. If you have autocall active
1140 in IPython (the default), all you need to do is type::
1140 in IPython (the default), all you need to do is type::
1141
1141
1142 mydemo
1142 mydemo
1143
1143
1144 and IPython will call it, executing each block. Demo objects can be
1144 and IPython will call it, executing each block. Demo objects can be
1145 restarted, you can move forward or back skipping blocks, re-execute the
1145 restarted, you can move forward or back skipping blocks, re-execute the
1146 last block, etc. Simply use the Tab key on a demo object to see its
1146 last block, etc. Simply use the Tab key on a demo object to see its
1147 methods, and call '?' on them to see their docstrings for more usage
1147 methods, and call '?' on them to see their docstrings for more usage
1148 details. In addition, the demo module itself contains a comprehensive
1148 details. In addition, the demo module itself contains a comprehensive
1149 docstring, which you can access via::
1149 docstring, which you can access via::
1150
1150
1151 from IPython.lib import demo
1151 from IPython.lib import demo
1152
1152
1153 demo?
1153 demo?
1154
1154
1155 Limitations: It is important to note that these demos are limited to
1155 Limitations: It is important to note that these demos are limited to
1156 fairly simple uses. In particular, you cannot break up sections within
1156 fairly simple uses. In particular, you cannot break up sections within
1157 indented code (loops, if statements, function definitions, etc.)
1157 indented code (loops, if statements, function definitions, etc.)
1158 Supporting something like this would basically require tracking the
1158 Supporting something like this would basically require tracking the
1159 internal execution state of the Python interpreter, so only top-level
1159 internal execution state of the Python interpreter, so only top-level
1160 divisions are allowed. If you want to be able to open an IPython
1160 divisions are allowed. If you want to be able to open an IPython
1161 instance at an arbitrary point in a program, you can use IPython's
1161 instance at an arbitrary point in a program, you can use IPython's
1162 embedding facilities, see :func:`IPython.embed` for details.
1162 embedding facilities, see :func:`IPython.embed` for details.
1163
1163
1164 .. include:: ../links.txt
1164 .. include:: ../links.txt
@@ -1,202 +1,201 b''
1 .. _tutorial:
1 .. _tutorial:
2
2
3 ======================
3 ======================
4 Introducing IPython
4 Introducing IPython
5 ======================
5 ======================
6
6
7 You don't need to know anything beyond Python to start using IPython – just type
7 You don't need to know anything beyond Python to start using IPython – just type
8 commands as you would at the standard Python prompt. But IPython can do much
8 commands as you would at the standard Python prompt. But IPython can do much
9 more than the standard prompt. Some key features are described here. For more
9 more than the standard prompt. Some key features are described here. For more
10 information, check the :ref:`tips page <tips>`, or look at examples in the
10 information, check the :ref:`tips page <tips>`, or look at examples in the
11 `IPython cookbook <https://github.com/ipython/ipython/wiki/Cookbook%3A-Index>`_.
11 `IPython cookbook <https://github.com/ipython/ipython/wiki/Cookbook%3A-Index>`_.
12
12
13 If you've never used Python before, you might want to look at `the official
13 If you've never used Python before, you might want to look at `the official
14 tutorial <http://docs.python.org/tutorial/>`_ or an alternative, `Dive into
14 tutorial <http://docs.python.org/tutorial/>`_ or an alternative, `Dive into
15 Python <http://diveintopython.net/toc/index.html>`_.
15 Python <http://diveintopython.net/toc/index.html>`_.
16
16
17 The four most helpful commands
17 The four most helpful commands
18 ===============================
18 ===============================
19
19
20 The four most helpful commands, as well as their brief description, is shown
20 The four most helpful commands, as well as their brief description, is shown
21 to you in a banner, every time you start IPython:
21 to you in a banner, every time you start IPython:
22
22
23 ========== =========================================================
23 ========== =========================================================
24 command description
24 command description
25 ========== =========================================================
25 ========== =========================================================
26 ? Introduction and overview of IPython's features.
26 ? Introduction and overview of IPython's features.
27 %quickref Quick reference.
27 %quickref Quick reference.
28 help Python's own help system.
28 help Python's own help system.
29 object? Details about 'object', use 'object??' for extra details.
29 object? Details about 'object', use 'object??' for extra details.
30 ========== =========================================================
30 ========== =========================================================
31
31
32 Tab completion
32 Tab completion
33 ==============
33 ==============
34
34
35 Tab completion, especially for attributes, is a convenient way to explore the
35 Tab completion, especially for attributes, is a convenient way to explore the
36 structure of any object you're dealing with. Simply type ``object_name.<TAB>``
36 structure of any object you're dealing with. Simply type ``object_name.<TAB>``
37 to view the object's attributes (see :ref:`the readline section <readline>` for
37 to view the object's attributes (see :ref:`the readline section <readline>` for
38 more). Besides Python objects and keywords, tab completion also works on file
38 more). Besides Python objects and keywords, tab completion also works on file
39 and directory names.
39 and directory names.
40
40
41 Exploring your objects
41 Exploring your objects
42 ======================
42 ======================
43
43
44 Typing ``object_name?`` will print all sorts of details about any object,
44 Typing ``object_name?`` will print all sorts of details about any object,
45 including docstrings, function definition lines (for call arguments) and
45 including docstrings, function definition lines (for call arguments) and
46 constructor details for classes. To get specific information on an object, you
46 constructor details for classes. To get specific information on an object, you
47 can use the magic commands ``%pdoc``, ``%pdef``, ``%psource`` and ``%pfile``
47 can use the magic commands ``%pdoc``, ``%pdef``, ``%psource`` and ``%pfile``
48
48
49 .. _magics_explained:
49 .. _magics_explained:
50
50
51 Magic functions
51 Magic functions
52 ===============
52 ===============
53
53
54 IPython has a set of predefined 'magic functions' that you can call with a
54 IPython has a set of predefined 'magic functions' that you can call with a
55 command line style syntax. There are two kinds of magics, line-oriented and
55 command line style syntax. There are two kinds of magics, line-oriented and
56 cell-oriented. **Line magics** are prefixed with the ``%`` character and work much
56 cell-oriented. **Line magics** are prefixed with the ``%`` character and work much
57 like OS command-line calls: they get as an argument the rest of the line, where
57 like OS command-line calls: they get as an argument the rest of the line, where
58 arguments are passed without parentheses or quotes. **Cell magics** are
58 arguments are passed without parentheses or quotes. **Cell magics** are
59 prefixed with a double ``%%``, and they are functions that get as an argument
59 prefixed with a double ``%%``, and they are functions that get as an argument
60 not only the rest of the line, but also the lines below it in a separate
60 not only the rest of the line, but also the lines below it in a separate
61 argument.
61 argument.
62
62
63 The following examples show how to call the builtin ``timeit`` magic, both in
63 The following examples show how to call the builtin ``timeit`` magic, both in
64 line and cell mode::
64 line and cell mode::
65
65
66 In [1]: %timeit range(1000)
66 In [1]: %timeit range(1000)
67 100000 loops, best of 3: 7.76 us per loop
67 100000 loops, best of 3: 7.76 us per loop
68
68
69 In [2]: %%timeit x = range(10000)
69 In [2]: %%timeit x = range(10000)
70 ...: max(x)
70 ...: max(x)
71 ...:
71 ...:
72 1000 loops, best of 3: 223 us per loop
72 1000 loops, best of 3: 223 us per loop
73
73
74 The builtin magics include:
74 The builtin magics include:
75
75
76 - Functions that work with code: ``%run``, ``%edit``, ``%save``, ``%macro``,
76 - Functions that work with code: ``%run``, ``%edit``, ``%save``, ``%macro``,
77 ``%recall``, etc.
77 ``%recall``, etc.
78 - Functions which affect the shell: ``%colors``, ``%xmode``, ``%autoindent``,
78 - Functions which affect the shell: ``%colors``, ``%xmode``, ``%autoindent``,
79 ``%automagic``, etc.
79 ``%automagic``, etc.
80 - Other functions such as ``%reset``, ``%timeit``, ``%%file``, ``%load``, or
80 - Other functions such as ``%reset``, ``%timeit``, ``%%file``, ``%load``, or
81 ``%paste``.
81 ``%paste``.
82
82
83 You can always call them using the ``%`` prefix, and if you're calling a line
83 You can always call them using the ``%`` prefix, and if you're calling a line
84 magic on a line by itself, you can omit even that::
84 magic on a line by itself, you can omit even that::
85
85
86 run thescript.py
86 run thescript.py
87
87
88 You can toggle this behavior by running the ``%automagic`` magic. Cell magics
88 You can toggle this behavior by running the ``%automagic`` magic. Cell magics
89 must always have the ``%%`` prefix.
89 must always have the ``%%`` prefix.
90
90
91 A more detailed explanation of the magic system can be obtained by calling
91 A more detailed explanation of the magic system can be obtained by calling
92 ``%magic``, and for more details on any magic function, call ``%somemagic?`` to
92 ``%magic``, and for more details on any magic function, call ``%somemagic?`` to
93 read its docstring. To see all the available magic functions, call
93 read its docstring. To see all the available magic functions, call
94 ``%lsmagic``.
94 ``%lsmagic``.
95
95
96 .. seealso::
96 .. seealso::
97
97
98 `Cell magics`_ example notebook
98 `Cell magics`_ example notebook
99
99
100 Running and Editing
100 Running and Editing
101 -------------------
101 -------------------
102
102
103 The ``%run`` magic command allows you to run any python script and load all of
103 The ``%run`` magic command allows you to run any python script and load all of
104 its data directly into the interactive namespace. Since the file is re-read
104 its data directly into the interactive namespace. Since the file is re-read
105 from disk each time, changes you make to it are reflected immediately (unlike
105 from disk each time, changes you make to it are reflected immediately (unlike
106 imported modules, which have to be specifically reloaded). IPython also
106 imported modules, which have to be specifically reloaded). IPython also
107 includes :ref:`dreload <dreload>`, a recursive reload function.
107 includes :ref:`dreload <dreload>`, a recursive reload function.
108
108
109 ``%run`` has special flags for timing the execution of your scripts (-t), or
109 ``%run`` has special flags for timing the execution of your scripts (-t), or
110 for running them under the control of either Python's pdb debugger (-d) or
110 for running them under the control of either Python's pdb debugger (-d) or
111 profiler (-p).
111 profiler (-p).
112
112
113 The ``%edit`` command gives a reasonable approximation of multiline editing,
113 The ``%edit`` command gives a reasonable approximation of multiline editing,
114 by invoking your favorite editor on the spot. IPython will execute the
114 by invoking your favorite editor on the spot. IPython will execute the
115 code you type in there as if it were typed interactively.
115 code you type in there as if it were typed interactively.
116
116
117 Debugging
117 Debugging
118 ---------
118 ---------
119
119
120 After an exception occurs, you can call ``%debug`` to jump into the Python
120 After an exception occurs, you can call ``%debug`` to jump into the Python
121 debugger (pdb) and examine the problem. Alternatively, if you call ``%pdb``,
121 debugger (pdb) and examine the problem. Alternatively, if you call ``%pdb``,
122 IPython will automatically start the debugger on any uncaught exception. You can
122 IPython will automatically start the debugger on any uncaught exception. You can
123 print variables, see code, execute statements and even walk up and down the
123 print variables, see code, execute statements and even walk up and down the
124 call stack to track down the true source of the problem. This can be an efficient
124 call stack to track down the true source of the problem. This can be an efficient
125 way to develop and debug code, in many cases eliminating the need for print
125 way to develop and debug code, in many cases eliminating the need for print
126 statements or external debugging tools.
126 statements or external debugging tools.
127
127
128 You can also step through a program from the beginning by calling
128 You can also step through a program from the beginning by calling
129 ``%run -d theprogram.py``.
129 ``%run -d theprogram.py``.
130
130
131 History
131 History
132 =======
132 =======
133
133
134 IPython stores both the commands you enter, and the results it produces. You
134 IPython stores both the commands you enter, and the results it produces. You
135 can easily go through previous commands with the up- and down-arrow keys, or
135 can easily go through previous commands with the up- and down-arrow keys, or
136 access your history in more sophisticated ways.
136 access your history in more sophisticated ways.
137
137
138 Input and output history are kept in variables called ``In`` and ``Out``, keyed
138 Input and output history are kept in variables called ``In`` and ``Out``, keyed
139 by the prompt numbers, e.g. ``In[4]``. The last three objects in output history
139 by the prompt numbers, e.g. ``In[4]``. The last three objects in output history
140 are also kept in variables named ``_``, ``__`` and ``___``.
140 are also kept in variables named ``_``, ``__`` and ``___``.
141
141
142 You can use the ``%history`` magic function to examine past input and output.
142 You can use the ``%history`` magic function to examine past input and output.
143 Input history from previous sessions is saved in a database, and IPython can be
143 Input history from previous sessions is saved in a database, and IPython can be
144 configured to save output history.
144 configured to save output history.
145
145
146 Several other magic functions can use your input history, including ``%edit``,
146 Several other magic functions can use your input history, including ``%edit``,
147 ``%rerun``, ``%recall``, ``%macro``, ``%save`` and ``%pastebin``. You can use a
147 ``%rerun``, ``%recall``, ``%macro``, ``%save`` and ``%pastebin``. You can use a
148 standard format to refer to lines::
148 standard format to refer to lines::
149
149
150 %pastebin 3 18-20 ~1/1-5
150 %pastebin 3 18-20 ~1/1-5
151
151
152 This will take line 3 and lines 18 to 20 from the current session, and lines
152 This will take line 3 and lines 18 to 20 from the current session, and lines
153 1-5 from the previous session.
153 1-5 from the previous session.
154
154
155 System shell commands
155 System shell commands
156 =====================
156 =====================
157
157
158 To run any command at the system shell, simply prefix it with !, e.g.::
158 To run any command at the system shell, simply prefix it with !, e.g.::
159
159
160 !ping www.bbc.co.uk
160 !ping www.bbc.co.uk
161
161
162 You can capture the output into a Python list, e.g.: ``files = !ls``. To pass
162 You can capture the output into a Python list, e.g.: ``files = !ls``. To pass
163 the values of Python variables or expressions to system commands, prefix them
163 the values of Python variables or expressions to system commands, prefix them
164 with $: ``!grep -rF $pattern ipython/*``. See :ref:`our shell section
164 with $: ``!grep -rF $pattern ipython/*``. See :ref:`our shell section
165 <system_shell_access>` for more details.
165 <system_shell_access>` for more details.
166
166
167 Define your own system aliases
167 Define your own system aliases
168 ------------------------------
168 ------------------------------
169
169
170 It's convenient to have aliases to the system commands you use most often.
170 It's convenient to have aliases to the system commands you use most often.
171 This allows you to work seamlessly from inside IPython with the same commands
171 This allows you to work seamlessly from inside IPython with the same commands
172 you are used to in your system shell. IPython comes with some pre-defined
172 you are used to in your system shell. IPython comes with some pre-defined
173 aliases and a complete system for changing directories, both via a stack (see
173 aliases and a complete system for changing directories, both via a stack (see
174 %pushd, %popd and %dhist) and via direct %cd. The latter keeps a history of
174 %pushd, %popd and %dhist) and via direct %cd. The latter keeps a history of
175 visited directories and allows you to go to any previously visited one.
175 visited directories and allows you to go to any previously visited one.
176
176
177
177
178 Configuration
178 Configuration
179 =============
179 =============
180
180
181 Much of IPython can be tweaked through :ref:`configuration <config_overview>`.
181 Much of IPython can be tweaked through :ref:`configuration <config_overview>`.
182 To get started, use the command ``ipython profile create`` to produce the
182 To get started, use the command ``ipython profile create`` to produce the
183 default config files. These will be placed in
183 default config files. These will be placed in
184 :file:`~/.ipython/profile_default` or
184 :file:`~/.ipython/profile_default`, and contain comments explaining
185 :file:`~/.config/ipython/profile_default`, and contain comments explaining
186 what the various options do.
185 what the various options do.
187
186
188 Profiles allow you to use IPython for different tasks, keeping separate config
187 Profiles allow you to use IPython for different tasks, keeping separate config
189 files and history for each one. More details in :ref:`the profiles section
188 files and history for each one. More details in :ref:`the profiles section
190 <profiles>`.
189 <profiles>`.
191
190
192 Startup Files
191 Startup Files
193 -------------
192 -------------
194
193
195 If you want some code to be run at the beginning of every IPython session, the
194 If you want some code to be run at the beginning of every IPython session, the
196 easiest way is to add Python (.py) or IPython (.ipy) scripts to your
195 easiest way is to add Python (.py) or IPython (.ipy) scripts to your
197 :file:`profile_default/startup/` directory. Files here will be executed as soon
196 :file:`profile_default/startup/` directory. Files here will be executed as soon
198 as the IPython shell is constructed, before any other code or scripts you have
197 as the IPython shell is constructed, before any other code or scripts you have
199 specified. The files will be run in order of their names, so you can control the
198 specified. The files will be run in order of their names, so you can control the
200 ordering with prefixes, like ``10-myimports.py``.
199 ordering with prefixes, like ``10-myimports.py``.
201
200
202 .. include:: ../links.txt
201 .. include:: ../links.txt
@@ -1,884 +1,884 b''
1 .. _parallel_process:
1 .. _parallel_process:
2
2
3 ===========================================
3 ===========================================
4 Starting the IPython controller and engines
4 Starting the IPython controller and engines
5 ===========================================
5 ===========================================
6
6
7 To use IPython for parallel computing, you need to start one instance of
7 To use IPython for parallel computing, you need to start one instance of
8 the controller and one or more instances of the engine. The controller
8 the controller and one or more instances of the engine. The controller
9 and each engine can run on different machines or on the same machine.
9 and each engine can run on different machines or on the same machine.
10 Because of this, there are many different possibilities.
10 Because of this, there are many different possibilities.
11
11
12 Broadly speaking, there are two ways of going about starting a controller and engines:
12 Broadly speaking, there are two ways of going about starting a controller and engines:
13
13
14 * In an automated manner using the :command:`ipcluster` command.
14 * In an automated manner using the :command:`ipcluster` command.
15 * In a more manual way using the :command:`ipcontroller` and
15 * In a more manual way using the :command:`ipcontroller` and
16 :command:`ipengine` commands.
16 :command:`ipengine` commands.
17
17
18 This document describes both of these methods. We recommend that new users
18 This document describes both of these methods. We recommend that new users
19 start with the :command:`ipcluster` command as it simplifies many common usage
19 start with the :command:`ipcluster` command as it simplifies many common usage
20 cases.
20 cases.
21
21
22 General considerations
22 General considerations
23 ======================
23 ======================
24
24
25 Before delving into the details about how you can start a controller and
25 Before delving into the details about how you can start a controller and
26 engines using the various methods, we outline some of the general issues that
26 engines using the various methods, we outline some of the general issues that
27 come up when starting the controller and engines. These things come up no
27 come up when starting the controller and engines. These things come up no
28 matter which method you use to start your IPython cluster.
28 matter which method you use to start your IPython cluster.
29
29
30 If you are running engines on multiple machines, you will likely need to instruct the
30 If you are running engines on multiple machines, you will likely need to instruct the
31 controller to listen for connections on an external interface. This can be done by specifying
31 controller to listen for connections on an external interface. This can be done by specifying
32 the ``ip`` argument on the command-line, or the ``HubFactory.ip`` configurable in
32 the ``ip`` argument on the command-line, or the ``HubFactory.ip`` configurable in
33 :file:`ipcontroller_config.py`.
33 :file:`ipcontroller_config.py`.
34
34
35 If your machines are on a trusted network, you can safely instruct the controller to listen
35 If your machines are on a trusted network, you can safely instruct the controller to listen
36 on all interfaces with::
36 on all interfaces with::
37
37
38 $> ipcontroller --ip=*
38 $> ipcontroller --ip=*
39
39
40
40
41 Or you can set the same behavior as the default by adding the following line to your :file:`ipcontroller_config.py`:
41 Or you can set the same behavior as the default by adding the following line to your :file:`ipcontroller_config.py`:
42
42
43 .. sourcecode:: python
43 .. sourcecode:: python
44
44
45 c.HubFactory.ip = '*'
45 c.HubFactory.ip = '*'
46 # c.HubFactory.location = '10.0.1.1'
46 # c.HubFactory.location = '10.0.1.1'
47
47
48
48
49 .. note::
49 .. note::
50
50
51 ``--ip=*`` instructs ZeroMQ to listen on all interfaces,
51 ``--ip=*`` instructs ZeroMQ to listen on all interfaces,
52 but it does not contain the IP needed for engines / clients
52 but it does not contain the IP needed for engines / clients
53 to know where the controller actually is.
53 to know where the controller actually is.
54 This can be specified with ``--location=10.0.0.1``,
54 This can be specified with ``--location=10.0.0.1``,
55 the specific IP address of the controller, as seen from engines and/or clients.
55 the specific IP address of the controller, as seen from engines and/or clients.
56 IPython tries to guess this value by default, but it will not always guess correctly.
56 IPython tries to guess this value by default, but it will not always guess correctly.
57 Check the ``location`` field in your connection files if you are having connection trouble.
57 Check the ``location`` field in your connection files if you are having connection trouble.
58
58
59 .. note::
59 .. note::
60
60
61 Due to the lack of security in ZeroMQ, the controller will only listen for connections on
61 Due to the lack of security in ZeroMQ, the controller will only listen for connections on
62 localhost by default. If you see Timeout errors on engines or clients, then the first
62 localhost by default. If you see Timeout errors on engines or clients, then the first
63 thing you should check is the ip address the controller is listening on, and make sure
63 thing you should check is the ip address the controller is listening on, and make sure
64 that it is visible from the timing out machine.
64 that it is visible from the timing out machine.
65
65
66 .. seealso::
66 .. seealso::
67
67
68 Our `notes <parallel_security>`_ on security in the new parallel computing code.
68 Our `notes <parallel_security>`_ on security in the new parallel computing code.
69
69
70 Let's say that you want to start the controller on ``host0`` and engines on
70 Let's say that you want to start the controller on ``host0`` and engines on
71 hosts ``host1``-``hostn``. The following steps are then required:
71 hosts ``host1``-``hostn``. The following steps are then required:
72
72
73 1. Start the controller on ``host0`` by running :command:`ipcontroller` on
73 1. Start the controller on ``host0`` by running :command:`ipcontroller` on
74 ``host0``. The controller must be instructed to listen on an interface visible
74 ``host0``. The controller must be instructed to listen on an interface visible
75 to the engine machines, via the ``ip`` command-line argument or ``HubFactory.ip``
75 to the engine machines, via the ``ip`` command-line argument or ``HubFactory.ip``
76 in :file:`ipcontroller_config.py`.
76 in :file:`ipcontroller_config.py`.
77 2. Move the JSON file (:file:`ipcontroller-engine.json`) created by the
77 2. Move the JSON file (:file:`ipcontroller-engine.json`) created by the
78 controller from ``host0`` to hosts ``host1``-``hostn``.
78 controller from ``host0`` to hosts ``host1``-``hostn``.
79 3. Start the engines on hosts ``host1``-``hostn`` by running
79 3. Start the engines on hosts ``host1``-``hostn`` by running
80 :command:`ipengine`. This command has to be told where the JSON file
80 :command:`ipengine`. This command has to be told where the JSON file
81 (:file:`ipcontroller-engine.json`) is located.
81 (:file:`ipcontroller-engine.json`) is located.
82
82
83 At this point, the controller and engines will be connected. By default, the JSON files
83 At this point, the controller and engines will be connected. By default, the JSON files
84 created by the controller are put into the :file:`IPYTHONDIR/profile_default/security`
84 created by the controller are put into the :file:`IPYTHONDIR/profile_default/security`
85 directory. If the engines share a filesystem with the controller, step 2 can be skipped as
85 directory. If the engines share a filesystem with the controller, step 2 can be skipped as
86 the engines will automatically look at that location.
86 the engines will automatically look at that location.
87
87
88 The final step required to actually use the running controller from a client is to move
88 The final step required to actually use the running controller from a client is to move
89 the JSON file :file:`ipcontroller-client.json` from ``host0`` to any host where clients
89 the JSON file :file:`ipcontroller-client.json` from ``host0`` to any host where clients
90 will be run. If these file are put into the :file:`IPYTHONDIR/profile_default/security`
90 will be run. If these file are put into the :file:`IPYTHONDIR/profile_default/security`
91 directory of the client's host, they will be found automatically. Otherwise, the full path
91 directory of the client's host, they will be found automatically. Otherwise, the full path
92 to them has to be passed to the client's constructor.
92 to them has to be passed to the client's constructor.
93
93
94 Using :command:`ipcluster`
94 Using :command:`ipcluster`
95 ===========================
95 ===========================
96
96
97 The :command:`ipcluster` command provides a simple way of starting a
97 The :command:`ipcluster` command provides a simple way of starting a
98 controller and engines in the following situations:
98 controller and engines in the following situations:
99
99
100 1. When the controller and engines are all run on localhost. This is useful
100 1. When the controller and engines are all run on localhost. This is useful
101 for testing or running on a multicore computer.
101 for testing or running on a multicore computer.
102 2. When engines are started using the :command:`mpiexec` command that comes
102 2. When engines are started using the :command:`mpiexec` command that comes
103 with most MPI [MPI]_ implementations
103 with most MPI [MPI]_ implementations
104 3. When engines are started using the PBS [PBS]_ batch system
104 3. When engines are started using the PBS [PBS]_ batch system
105 (or other `qsub` systems, such as SGE).
105 (or other `qsub` systems, such as SGE).
106 4. When the controller is started on localhost and the engines are started on
106 4. When the controller is started on localhost and the engines are started on
107 remote nodes using :command:`ssh`.
107 remote nodes using :command:`ssh`.
108 5. When engines are started using the Windows HPC Server batch system.
108 5. When engines are started using the Windows HPC Server batch system.
109
109
110 .. note::
110 .. note::
111
111
112 Currently :command:`ipcluster` requires that the
112 Currently :command:`ipcluster` requires that the
113 :file:`IPYTHONDIR/profile_<name>/security` directory live on a shared filesystem that is
113 :file:`IPYTHONDIR/profile_<name>/security` directory live on a shared filesystem that is
114 seen by both the controller and engines. If you don't have a shared file
114 seen by both the controller and engines. If you don't have a shared file
115 system you will need to use :command:`ipcontroller` and
115 system you will need to use :command:`ipcontroller` and
116 :command:`ipengine` directly.
116 :command:`ipengine` directly.
117
117
118 Under the hood, :command:`ipcluster` just uses :command:`ipcontroller`
118 Under the hood, :command:`ipcluster` just uses :command:`ipcontroller`
119 and :command:`ipengine` to perform the steps described above.
119 and :command:`ipengine` to perform the steps described above.
120
120
121 The simplest way to use ipcluster requires no configuration, and will
121 The simplest way to use ipcluster requires no configuration, and will
122 launch a controller and a number of engines on the local machine. For instance,
122 launch a controller and a number of engines on the local machine. For instance,
123 to start one controller and 4 engines on localhost, just do::
123 to start one controller and 4 engines on localhost, just do::
124
124
125 $ ipcluster start -n 4
125 $ ipcluster start -n 4
126
126
127 To see other command line options, do::
127 To see other command line options, do::
128
128
129 $ ipcluster -h
129 $ ipcluster -h
130
130
131
131
132 Configuring an IPython cluster
132 Configuring an IPython cluster
133 ==============================
133 ==============================
134
134
135 Cluster configurations are stored as `profiles`. You can create a new profile with::
135 Cluster configurations are stored as `profiles`. You can create a new profile with::
136
136
137 $ ipython profile create --parallel --profile=myprofile
137 $ ipython profile create --parallel --profile=myprofile
138
138
139 This will create the directory :file:`IPYTHONDIR/profile_myprofile`, and populate it
139 This will create the directory :file:`IPYTHONDIR/profile_myprofile`, and populate it
140 with the default configuration files for the three IPython cluster commands. Once
140 with the default configuration files for the three IPython cluster commands. Once
141 you edit those files, you can continue to call ipcluster/ipcontroller/ipengine
141 you edit those files, you can continue to call ipcluster/ipcontroller/ipengine
142 with no arguments beyond ``profile=myprofile``, and any configuration will be maintained.
142 with no arguments beyond ``profile=myprofile``, and any configuration will be maintained.
143
143
144 There is no limit to the number of profiles you can have, so you can maintain a profile for each
144 There is no limit to the number of profiles you can have, so you can maintain a profile for each
145 of your common use cases. The default profile will be used whenever the
145 of your common use cases. The default profile will be used whenever the
146 profile argument is not specified, so edit :file:`IPYTHONDIR/profile_default/*_config.py` to
146 profile argument is not specified, so edit :file:`IPYTHONDIR/profile_default/*_config.py` to
147 represent your most common use case.
147 represent your most common use case.
148
148
149 The configuration files are loaded with commented-out settings and explanations,
149 The configuration files are loaded with commented-out settings and explanations,
150 which should cover most of the available possibilities.
150 which should cover most of the available possibilities.
151
151
152 Using various batch systems with :command:`ipcluster`
152 Using various batch systems with :command:`ipcluster`
153 -----------------------------------------------------
153 -----------------------------------------------------
154
154
155 :command:`ipcluster` has a notion of Launchers that can start controllers
155 :command:`ipcluster` has a notion of Launchers that can start controllers
156 and engines with various remote execution schemes. Currently supported
156 and engines with various remote execution schemes. Currently supported
157 models include :command:`ssh`, :command:`mpiexec`, PBS-style (Torque, SGE, LSF),
157 models include :command:`ssh`, :command:`mpiexec`, PBS-style (Torque, SGE, LSF),
158 and Windows HPC Server.
158 and Windows HPC Server.
159
159
160 In general, these are configured by the :attr:`IPClusterEngines.engine_set_launcher_class`,
160 In general, these are configured by the :attr:`IPClusterEngines.engine_set_launcher_class`,
161 and :attr:`IPClusterStart.controller_launcher_class` configurables, which can be the
161 and :attr:`IPClusterStart.controller_launcher_class` configurables, which can be the
162 fully specified object name (e.g. ``'IPython.parallel.apps.launcher.LocalControllerLauncher'``),
162 fully specified object name (e.g. ``'IPython.parallel.apps.launcher.LocalControllerLauncher'``),
163 but if you are using IPython's builtin launchers, you can specify just the class name,
163 but if you are using IPython's builtin launchers, you can specify just the class name,
164 or even just the prefix e.g:
164 or even just the prefix e.g:
165
165
166 .. sourcecode:: python
166 .. sourcecode:: python
167
167
168 c.IPClusterEngines.engine_launcher_class = 'SSH'
168 c.IPClusterEngines.engine_launcher_class = 'SSH'
169 # equivalent to
169 # equivalent to
170 c.IPClusterEngines.engine_launcher_class = 'SSHEngineSetLauncher'
170 c.IPClusterEngines.engine_launcher_class = 'SSHEngineSetLauncher'
171 # both of which expand to
171 # both of which expand to
172 c.IPClusterEngines.engine_launcher_class = 'IPython.parallel.apps.launcher.SSHEngineSetLauncher'
172 c.IPClusterEngines.engine_launcher_class = 'IPython.parallel.apps.launcher.SSHEngineSetLauncher'
173
173
174 The shortest form being of particular use on the command line, where all you need to do to
174 The shortest form being of particular use on the command line, where all you need to do to
175 get an IPython cluster running with engines started with MPI is:
175 get an IPython cluster running with engines started with MPI is:
176
176
177 .. sourcecode:: bash
177 .. sourcecode:: bash
178
178
179 $> ipcluster start --engines=MPI
179 $> ipcluster start --engines=MPI
180
180
181 Assuming that the default MPI config is sufficient.
181 Assuming that the default MPI config is sufficient.
182
182
183 .. note::
183 .. note::
184
184
185 shortcuts for builtin launcher names were added in 0.12, as was the ``_class`` suffix
185 shortcuts for builtin launcher names were added in 0.12, as was the ``_class`` suffix
186 on the configurable names. If you use the old 0.11 names (e.g. ``engine_set_launcher``),
186 on the configurable names. If you use the old 0.11 names (e.g. ``engine_set_launcher``),
187 they will still work, but you will get a deprecation warning that the name has changed.
187 they will still work, but you will get a deprecation warning that the name has changed.
188
188
189
189
190 .. note::
190 .. note::
191
191
192 The Launchers and configuration are designed in such a way that advanced
192 The Launchers and configuration are designed in such a way that advanced
193 users can subclass and configure them to fit their own system that we
193 users can subclass and configure them to fit their own system that we
194 have not yet supported (such as Condor)
194 have not yet supported (such as Condor)
195
195
196 Using :command:`ipcluster` in mpiexec/mpirun mode
196 Using :command:`ipcluster` in mpiexec/mpirun mode
197 -------------------------------------------------
197 -------------------------------------------------
198
198
199
199
200 The mpiexec/mpirun mode is useful if you:
200 The mpiexec/mpirun mode is useful if you:
201
201
202 1. Have MPI installed.
202 1. Have MPI installed.
203 2. Your systems are configured to use the :command:`mpiexec` or
203 2. Your systems are configured to use the :command:`mpiexec` or
204 :command:`mpirun` commands to start MPI processes.
204 :command:`mpirun` commands to start MPI processes.
205
205
206 If these are satisfied, you can create a new profile::
206 If these are satisfied, you can create a new profile::
207
207
208 $ ipython profile create --parallel --profile=mpi
208 $ ipython profile create --parallel --profile=mpi
209
209
210 and edit the file :file:`IPYTHONDIR/profile_mpi/ipcluster_config.py`.
210 and edit the file :file:`IPYTHONDIR/profile_mpi/ipcluster_config.py`.
211
211
212 There, instruct ipcluster to use the MPI launchers by adding the lines:
212 There, instruct ipcluster to use the MPI launchers by adding the lines:
213
213
214 .. sourcecode:: python
214 .. sourcecode:: python
215
215
216 c.IPClusterEngines.engine_launcher_class = 'MPIEngineSetLauncher'
216 c.IPClusterEngines.engine_launcher_class = 'MPIEngineSetLauncher'
217
217
218 If the default MPI configuration is correct, then you can now start your cluster, with::
218 If the default MPI configuration is correct, then you can now start your cluster, with::
219
219
220 $ ipcluster start -n 4 --profile=mpi
220 $ ipcluster start -n 4 --profile=mpi
221
221
222 This does the following:
222 This does the following:
223
223
224 1. Starts the IPython controller on current host.
224 1. Starts the IPython controller on current host.
225 2. Uses :command:`mpiexec` to start 4 engines.
225 2. Uses :command:`mpiexec` to start 4 engines.
226
226
227 If you have a reason to also start the Controller with mpi, you can specify:
227 If you have a reason to also start the Controller with mpi, you can specify:
228
228
229 .. sourcecode:: python
229 .. sourcecode:: python
230
230
231 c.IPClusterStart.controller_launcher_class = 'MPIControllerLauncher'
231 c.IPClusterStart.controller_launcher_class = 'MPIControllerLauncher'
232
232
233 .. note::
233 .. note::
234
234
235 The Controller *will not* be in the same MPI universe as the engines, so there is not
235 The Controller *will not* be in the same MPI universe as the engines, so there is not
236 much reason to do this unless sysadmins demand it.
236 much reason to do this unless sysadmins demand it.
237
237
238 On newer MPI implementations (such as OpenMPI), this will work even if you
238 On newer MPI implementations (such as OpenMPI), this will work even if you
239 don't make any calls to MPI or call :func:`MPI_Init`. However, older MPI
239 don't make any calls to MPI or call :func:`MPI_Init`. However, older MPI
240 implementations actually require each process to call :func:`MPI_Init` upon
240 implementations actually require each process to call :func:`MPI_Init` upon
241 starting. The easiest way of having this done is to install the mpi4py
241 starting. The easiest way of having this done is to install the mpi4py
242 [mpi4py]_ package and then specify the ``c.MPI.use`` option in :file:`ipengine_config.py`:
242 [mpi4py]_ package and then specify the ``c.MPI.use`` option in :file:`ipengine_config.py`:
243
243
244 .. sourcecode:: python
244 .. sourcecode:: python
245
245
246 c.MPI.use = 'mpi4py'
246 c.MPI.use = 'mpi4py'
247
247
248 Unfortunately, even this won't work for some MPI implementations. If you are
248 Unfortunately, even this won't work for some MPI implementations. If you are
249 having problems with this, you will likely have to use a custom Python
249 having problems with this, you will likely have to use a custom Python
250 executable that itself calls :func:`MPI_Init` at the appropriate time.
250 executable that itself calls :func:`MPI_Init` at the appropriate time.
251 Fortunately, mpi4py comes with such a custom Python executable that is easy to
251 Fortunately, mpi4py comes with such a custom Python executable that is easy to
252 install and use. However, this custom Python executable approach will not work
252 install and use. However, this custom Python executable approach will not work
253 with :command:`ipcluster` currently.
253 with :command:`ipcluster` currently.
254
254
255 More details on using MPI with IPython can be found :ref:`here <parallelmpi>`.
255 More details on using MPI with IPython can be found :ref:`here <parallelmpi>`.
256
256
257
257
258 Using :command:`ipcluster` in PBS mode
258 Using :command:`ipcluster` in PBS mode
259 --------------------------------------
259 --------------------------------------
260
260
261 The PBS mode uses the Portable Batch System (PBS) to start the engines.
261 The PBS mode uses the Portable Batch System (PBS) to start the engines.
262
262
263 As usual, we will start by creating a fresh profile::
263 As usual, we will start by creating a fresh profile::
264
264
265 $ ipython profile create --parallel --profile=pbs
265 $ ipython profile create --parallel --profile=pbs
266
266
267 And in :file:`ipcluster_config.py`, we will select the PBS launchers for the controller
267 And in :file:`ipcluster_config.py`, we will select the PBS launchers for the controller
268 and engines:
268 and engines:
269
269
270 .. sourcecode:: python
270 .. sourcecode:: python
271
271
272 c.IPClusterStart.controller_launcher_class = 'PBSControllerLauncher'
272 c.IPClusterStart.controller_launcher_class = 'PBSControllerLauncher'
273 c.IPClusterEngines.engine_launcher_class = 'PBSEngineSetLauncher'
273 c.IPClusterEngines.engine_launcher_class = 'PBSEngineSetLauncher'
274
274
275 .. note::
275 .. note::
276
276
277 Note that the configurable is IPClusterEngines for the engine launcher, and
277 Note that the configurable is IPClusterEngines for the engine launcher, and
278 IPClusterStart for the controller launcher. This is because the start command is a
278 IPClusterStart for the controller launcher. This is because the start command is a
279 subclass of the engine command, adding a controller launcher. Since it is a subclass,
279 subclass of the engine command, adding a controller launcher. Since it is a subclass,
280 any configuration made in IPClusterEngines is inherited by IPClusterStart unless it is
280 any configuration made in IPClusterEngines is inherited by IPClusterStart unless it is
281 overridden.
281 overridden.
282
282
283 IPython does provide simple default batch templates for PBS and SGE, but you may need
283 IPython does provide simple default batch templates for PBS and SGE, but you may need
284 to specify your own. Here is a sample PBS script template:
284 to specify your own. Here is a sample PBS script template:
285
285
286 .. sourcecode:: bash
286 .. sourcecode:: bash
287
287
288 #PBS -N ipython
288 #PBS -N ipython
289 #PBS -j oe
289 #PBS -j oe
290 #PBS -l walltime=00:10:00
290 #PBS -l walltime=00:10:00
291 #PBS -l nodes={n/4}:ppn=4
291 #PBS -l nodes={n/4}:ppn=4
292 #PBS -q {queue}
292 #PBS -q {queue}
293
293
294 cd $PBS_O_WORKDIR
294 cd $PBS_O_WORKDIR
295 export PATH=$HOME/usr/local/bin
295 export PATH=$HOME/usr/local/bin
296 export PYTHONPATH=$HOME/usr/local/lib/python2.7/site-packages
296 export PYTHONPATH=$HOME/usr/local/lib/python2.7/site-packages
297 /usr/local/bin/mpiexec -n {n} ipengine --profile-dir={profile_dir}
297 /usr/local/bin/mpiexec -n {n} ipengine --profile-dir={profile_dir}
298
298
299 There are a few important points about this template:
299 There are a few important points about this template:
300
300
301 1. This template will be rendered at runtime using IPython's :class:`EvalFormatter`.
301 1. This template will be rendered at runtime using IPython's :class:`EvalFormatter`.
302 This is simply a subclass of :class:`string.Formatter` that allows simple expressions
302 This is simply a subclass of :class:`string.Formatter` that allows simple expressions
303 on keys.
303 on keys.
304
304
305 2. Instead of putting in the actual number of engines, use the notation
305 2. Instead of putting in the actual number of engines, use the notation
306 ``{n}`` to indicate the number of engines to be started. You can also use
306 ``{n}`` to indicate the number of engines to be started. You can also use
307 expressions like ``{n/4}`` in the template to indicate the number of nodes.
307 expressions like ``{n/4}`` in the template to indicate the number of nodes.
308 There will always be ``{n}`` and ``{profile_dir}`` variables passed to the formatter.
308 There will always be ``{n}`` and ``{profile_dir}`` variables passed to the formatter.
309 These allow the batch system to know how many engines, and where the configuration
309 These allow the batch system to know how many engines, and where the configuration
310 files reside. The same is true for the batch queue, with the template variable
310 files reside. The same is true for the batch queue, with the template variable
311 ``{queue}``.
311 ``{queue}``.
312
312
313 3. Any options to :command:`ipengine` can be given in the batch script
313 3. Any options to :command:`ipengine` can be given in the batch script
314 template, or in :file:`ipengine_config.py`.
314 template, or in :file:`ipengine_config.py`.
315
315
316 4. Depending on the configuration of you system, you may have to set
316 4. Depending on the configuration of you system, you may have to set
317 environment variables in the script template.
317 environment variables in the script template.
318
318
319 The controller template should be similar, but simpler:
319 The controller template should be similar, but simpler:
320
320
321 .. sourcecode:: bash
321 .. sourcecode:: bash
322
322
323 #PBS -N ipython
323 #PBS -N ipython
324 #PBS -j oe
324 #PBS -j oe
325 #PBS -l walltime=00:10:00
325 #PBS -l walltime=00:10:00
326 #PBS -l nodes=1:ppn=4
326 #PBS -l nodes=1:ppn=4
327 #PBS -q {queue}
327 #PBS -q {queue}
328
328
329 cd $PBS_O_WORKDIR
329 cd $PBS_O_WORKDIR
330 export PATH=$HOME/usr/local/bin
330 export PATH=$HOME/usr/local/bin
331 export PYTHONPATH=$HOME/usr/local/lib/python2.7/site-packages
331 export PYTHONPATH=$HOME/usr/local/lib/python2.7/site-packages
332 ipcontroller --profile-dir={profile_dir}
332 ipcontroller --profile-dir={profile_dir}
333
333
334
334
335 Once you have created these scripts, save them with names like
335 Once you have created these scripts, save them with names like
336 :file:`pbs.engine.template`. Now you can load them into the :file:`ipcluster_config` with:
336 :file:`pbs.engine.template`. Now you can load them into the :file:`ipcluster_config` with:
337
337
338 .. sourcecode:: python
338 .. sourcecode:: python
339
339
340 c.PBSEngineSetLauncher.batch_template_file = "pbs.engine.template"
340 c.PBSEngineSetLauncher.batch_template_file = "pbs.engine.template"
341
341
342 c.PBSControllerLauncher.batch_template_file = "pbs.controller.template"
342 c.PBSControllerLauncher.batch_template_file = "pbs.controller.template"
343
343
344
344
345 Alternately, you can just define the templates as strings inside :file:`ipcluster_config`.
345 Alternately, you can just define the templates as strings inside :file:`ipcluster_config`.
346
346
347 Whether you are using your own templates or our defaults, the extra configurables available are
347 Whether you are using your own templates or our defaults, the extra configurables available are
348 the number of engines to launch (``{n}``, and the batch system queue to which the jobs are to be
348 the number of engines to launch (``{n}``, and the batch system queue to which the jobs are to be
349 submitted (``{queue}``)). These are configurables, and can be specified in
349 submitted (``{queue}``)). These are configurables, and can be specified in
350 :file:`ipcluster_config`:
350 :file:`ipcluster_config`:
351
351
352 .. sourcecode:: python
352 .. sourcecode:: python
353
353
354 c.PBSLauncher.queue = 'veryshort.q'
354 c.PBSLauncher.queue = 'veryshort.q'
355 c.IPClusterEngines.n = 64
355 c.IPClusterEngines.n = 64
356
356
357 Note that assuming you are running PBS on a multi-node cluster, the Controller's default behavior
357 Note that assuming you are running PBS on a multi-node cluster, the Controller's default behavior
358 of listening only on localhost is likely too restrictive. In this case, also assuming the
358 of listening only on localhost is likely too restrictive. In this case, also assuming the
359 nodes are safely behind a firewall, you can simply instruct the Controller to listen for
359 nodes are safely behind a firewall, you can simply instruct the Controller to listen for
360 connections on all its interfaces, by adding in :file:`ipcontroller_config`:
360 connections on all its interfaces, by adding in :file:`ipcontroller_config`:
361
361
362 .. sourcecode:: python
362 .. sourcecode:: python
363
363
364 c.HubFactory.ip = '*'
364 c.HubFactory.ip = '*'
365
365
366 You can now run the cluster with::
366 You can now run the cluster with::
367
367
368 $ ipcluster start --profile=pbs -n 128
368 $ ipcluster start --profile=pbs -n 128
369
369
370 Additional configuration options can be found in the PBS section of :file:`ipcluster_config`.
370 Additional configuration options can be found in the PBS section of :file:`ipcluster_config`.
371
371
372 .. note::
372 .. note::
373
373
374 Due to the flexibility of configuration, the PBS launchers work with simple changes
374 Due to the flexibility of configuration, the PBS launchers work with simple changes
375 to the template for other :command:`qsub`-using systems, such as Sun Grid Engine,
375 to the template for other :command:`qsub`-using systems, such as Sun Grid Engine,
376 and with further configuration in similar batch systems like Condor.
376 and with further configuration in similar batch systems like Condor.
377
377
378
378
379 Using :command:`ipcluster` in SSH mode
379 Using :command:`ipcluster` in SSH mode
380 --------------------------------------
380 --------------------------------------
381
381
382
382
383 The SSH mode uses :command:`ssh` to execute :command:`ipengine` on remote
383 The SSH mode uses :command:`ssh` to execute :command:`ipengine` on remote
384 nodes and :command:`ipcontroller` can be run remotely as well, or on localhost.
384 nodes and :command:`ipcontroller` can be run remotely as well, or on localhost.
385
385
386 .. note::
386 .. note::
387
387
388 When using this mode it highly recommended that you have set up SSH keys
388 When using this mode it highly recommended that you have set up SSH keys
389 and are using ssh-agent [SSH]_ for password-less logins.
389 and are using ssh-agent [SSH]_ for password-less logins.
390
390
391 As usual, we start by creating a clean profile::
391 As usual, we start by creating a clean profile::
392
392
393 $ ipython profile create --parallel --profile=ssh
393 $ ipython profile create --parallel --profile=ssh
394
394
395 To use this mode, select the SSH launchers in :file:`ipcluster_config.py`:
395 To use this mode, select the SSH launchers in :file:`ipcluster_config.py`:
396
396
397 .. sourcecode:: python
397 .. sourcecode:: python
398
398
399 c.IPClusterEngines.engine_launcher_class = 'SSHEngineSetLauncher'
399 c.IPClusterEngines.engine_launcher_class = 'SSHEngineSetLauncher'
400 # and if the Controller is also to be remote:
400 # and if the Controller is also to be remote:
401 c.IPClusterStart.controller_launcher_class = 'SSHControllerLauncher'
401 c.IPClusterStart.controller_launcher_class = 'SSHControllerLauncher'
402
402
403
403
404
404
405 The controller's remote location and configuration can be specified:
405 The controller's remote location and configuration can be specified:
406
406
407 .. sourcecode:: python
407 .. sourcecode:: python
408
408
409 # Set the user and hostname for the controller
409 # Set the user and hostname for the controller
410 # c.SSHControllerLauncher.hostname = 'controller.example.com'
410 # c.SSHControllerLauncher.hostname = 'controller.example.com'
411 # c.SSHControllerLauncher.user = os.environ.get('USER','username')
411 # c.SSHControllerLauncher.user = os.environ.get('USER','username')
412
412
413 # Set the arguments to be passed to ipcontroller
413 # Set the arguments to be passed to ipcontroller
414 # note that remotely launched ipcontroller will not get the contents of
414 # note that remotely launched ipcontroller will not get the contents of
415 # the local ipcontroller_config.py unless it resides on the *remote host*
415 # the local ipcontroller_config.py unless it resides on the *remote host*
416 # in the location specified by the `profile-dir` argument.
416 # in the location specified by the `profile-dir` argument.
417 # c.SSHControllerLauncher.controller_args = ['--reuse', '--ip=*', '--profile-dir=/path/to/cd']
417 # c.SSHControllerLauncher.controller_args = ['--reuse', '--ip=*', '--profile-dir=/path/to/cd']
418
418
419 Engines are specified in a dictionary, by hostname and the number of engines to be run
419 Engines are specified in a dictionary, by hostname and the number of engines to be run
420 on that host.
420 on that host.
421
421
422 .. sourcecode:: python
422 .. sourcecode:: python
423
423
424 c.SSHEngineSetLauncher.engines = { 'host1.example.com' : 2,
424 c.SSHEngineSetLauncher.engines = { 'host1.example.com' : 2,
425 'host2.example.com' : 5,
425 'host2.example.com' : 5,
426 'host3.example.com' : (1, ['--profile-dir=/home/different/location']),
426 'host3.example.com' : (1, ['--profile-dir=/home/different/location']),
427 'host4.example.com' : 8 }
427 'host4.example.com' : 8 }
428
428
429 * The `engines` dict, where the keys are the host we want to run engines on and
429 * The `engines` dict, where the keys are the host we want to run engines on and
430 the value is the number of engines to run on that host.
430 the value is the number of engines to run on that host.
431 * on host3, the value is a tuple, where the number of engines is first, and the arguments
431 * on host3, the value is a tuple, where the number of engines is first, and the arguments
432 to be passed to :command:`ipengine` are the second element.
432 to be passed to :command:`ipengine` are the second element.
433
433
434 For engines without explicitly specified arguments, the default arguments are set in
434 For engines without explicitly specified arguments, the default arguments are set in
435 a single location:
435 a single location:
436
436
437 .. sourcecode:: python
437 .. sourcecode:: python
438
438
439 c.SSHEngineSetLauncher.engine_args = ['--profile-dir=/path/to/profile_ssh']
439 c.SSHEngineSetLauncher.engine_args = ['--profile-dir=/path/to/profile_ssh']
440
440
441 Current limitations of the SSH mode of :command:`ipcluster` are:
441 Current limitations of the SSH mode of :command:`ipcluster` are:
442
442
443 * Untested and unsupported on Windows. Would require a working :command:`ssh` on Windows.
443 * Untested and unsupported on Windows. Would require a working :command:`ssh` on Windows.
444 Also, we are using shell scripts to setup and execute commands on remote hosts.
444 Also, we are using shell scripts to setup and execute commands on remote hosts.
445
445
446
446
447 Moving files with SSH
447 Moving files with SSH
448 *********************
448 *********************
449
449
450 SSH launchers will try to move connection files, controlled by the ``to_send`` and
450 SSH launchers will try to move connection files, controlled by the ``to_send`` and
451 ``to_fetch`` configurables. If your machines are on a shared filesystem, this step is
451 ``to_fetch`` configurables. If your machines are on a shared filesystem, this step is
452 unnecessary, and can be skipped by setting these to empty lists:
452 unnecessary, and can be skipped by setting these to empty lists:
453
453
454 .. sourcecode:: python
454 .. sourcecode:: python
455
455
456 c.SSHLauncher.to_send = []
456 c.SSHLauncher.to_send = []
457 c.SSHLauncher.to_fetch = []
457 c.SSHLauncher.to_fetch = []
458
458
459 If our default guesses about paths don't work for you, or other files
459 If our default guesses about paths don't work for you, or other files
460 should be moved, you can manually specify these lists as tuples of (local_path,
460 should be moved, you can manually specify these lists as tuples of (local_path,
461 remote_path) for to_send, and (remote_path, local_path) for to_fetch. If you do
461 remote_path) for to_send, and (remote_path, local_path) for to_fetch. If you do
462 specify these lists explicitly, IPython *will not* automatically send connection files,
462 specify these lists explicitly, IPython *will not* automatically send connection files,
463 so you must include this yourself if they should still be sent/retrieved.
463 so you must include this yourself if they should still be sent/retrieved.
464
464
465
465
466 IPython on EC2 with StarCluster
466 IPython on EC2 with StarCluster
467 ===============================
467 ===============================
468
468
469 The excellent StarCluster_ toolkit for managing `Amazon EC2`_ clusters has a plugin
469 The excellent StarCluster_ toolkit for managing `Amazon EC2`_ clusters has a plugin
470 which makes deploying IPython on EC2 quite simple. The starcluster plugin uses
470 which makes deploying IPython on EC2 quite simple. The starcluster plugin uses
471 :command:`ipcluster` with the SGE launchers to distribute engines across the
471 :command:`ipcluster` with the SGE launchers to distribute engines across the
472 EC2 cluster. See their `ipcluster plugin documentation`_ for more information.
472 EC2 cluster. See their `ipcluster plugin documentation`_ for more information.
473
473
474 .. _StarCluster: http://web.mit.edu/starcluster
474 .. _StarCluster: http://web.mit.edu/starcluster
475 .. _Amazon EC2: http://aws.amazon.com/ec2/
475 .. _Amazon EC2: http://aws.amazon.com/ec2/
476 .. _ipcluster plugin documentation: http://web.mit.edu/starcluster/docs/latest/plugins/ipython.html
476 .. _ipcluster plugin documentation: http://web.mit.edu/starcluster/docs/latest/plugins/ipython.html
477
477
478
478
479 Using the :command:`ipcontroller` and :command:`ipengine` commands
479 Using the :command:`ipcontroller` and :command:`ipengine` commands
480 ==================================================================
480 ==================================================================
481
481
482 It is also possible to use the :command:`ipcontroller` and :command:`ipengine`
482 It is also possible to use the :command:`ipcontroller` and :command:`ipengine`
483 commands to start your controller and engines. This approach gives you full
483 commands to start your controller and engines. This approach gives you full
484 control over all aspects of the startup process.
484 control over all aspects of the startup process.
485
485
486 Starting the controller and engine on your local machine
486 Starting the controller and engine on your local machine
487 --------------------------------------------------------
487 --------------------------------------------------------
488
488
489 To use :command:`ipcontroller` and :command:`ipengine` to start things on your
489 To use :command:`ipcontroller` and :command:`ipengine` to start things on your
490 local machine, do the following.
490 local machine, do the following.
491
491
492 First start the controller::
492 First start the controller::
493
493
494 $ ipcontroller
494 $ ipcontroller
495
495
496 Next, start however many instances of the engine you want using (repeatedly)
496 Next, start however many instances of the engine you want using (repeatedly)
497 the command::
497 the command::
498
498
499 $ ipengine
499 $ ipengine
500
500
501 The engines should start and automatically connect to the controller using the
501 The engines should start and automatically connect to the controller using the
502 JSON files in :file:`IPYTHONDIR/profile_default/security`. You are now ready to use the
502 JSON files in :file:`IPYTHONDIR/profile_default/security`. You are now ready to use the
503 controller and engines from IPython.
503 controller and engines from IPython.
504
504
505 .. warning::
505 .. warning::
506
506
507 The order of the above operations may be important. You *must*
507 The order of the above operations may be important. You *must*
508 start the controller before the engines, unless you are reusing connection
508 start the controller before the engines, unless you are reusing connection
509 information (via ``--reuse``), in which case ordering is not important.
509 information (via ``--reuse``), in which case ordering is not important.
510
510
511 .. note::
511 .. note::
512
512
513 On some platforms (OS X), to put the controller and engine into the
513 On some platforms (OS X), to put the controller and engine into the
514 background you may need to give these commands in the form ``(ipcontroller
514 background you may need to give these commands in the form ``(ipcontroller
515 &)`` and ``(ipengine &)`` (with the parentheses) for them to work
515 &)`` and ``(ipengine &)`` (with the parentheses) for them to work
516 properly.
516 properly.
517
517
518 Starting the controller and engines on different hosts
518 Starting the controller and engines on different hosts
519 ------------------------------------------------------
519 ------------------------------------------------------
520
520
521 When the controller and engines are running on different hosts, things are
521 When the controller and engines are running on different hosts, things are
522 slightly more complicated, but the underlying ideas are the same:
522 slightly more complicated, but the underlying ideas are the same:
523
523
524 1. Start the controller on a host using :command:`ipcontroller`. The controller must be
524 1. Start the controller on a host using :command:`ipcontroller`. The controller must be
525 instructed to listen on an interface visible to the engine machines, via the ``ip``
525 instructed to listen on an interface visible to the engine machines, via the ``ip``
526 command-line argument or ``HubFactory.ip`` in :file:`ipcontroller_config.py`::
526 command-line argument or ``HubFactory.ip`` in :file:`ipcontroller_config.py`::
527
527
528 $ ipcontroller --ip=192.168.1.16
528 $ ipcontroller --ip=192.168.1.16
529
529
530 .. sourcecode:: python
530 .. sourcecode:: python
531
531
532 # in ipcontroller_config.py
532 # in ipcontroller_config.py
533 HubFactory.ip = '192.168.1.16'
533 HubFactory.ip = '192.168.1.16'
534
534
535 2. Copy :file:`ipcontroller-engine.json` from :file:`IPYTHONDIR/profile_<name>/security` on
535 2. Copy :file:`ipcontroller-engine.json` from :file:`IPYTHONDIR/profile_<name>/security` on
536 the controller's host to the host where the engines will run.
536 the controller's host to the host where the engines will run.
537 3. Use :command:`ipengine` on the engine's hosts to start the engines.
537 3. Use :command:`ipengine` on the engine's hosts to start the engines.
538
538
539 The only thing you have to be careful of is to tell :command:`ipengine` where
539 The only thing you have to be careful of is to tell :command:`ipengine` where
540 the :file:`ipcontroller-engine.json` file is located. There are two ways you
540 the :file:`ipcontroller-engine.json` file is located. There are two ways you
541 can do this:
541 can do this:
542
542
543 * Put :file:`ipcontroller-engine.json` in the :file:`IPYTHONDIR/profile_<name>/security`
543 * Put :file:`ipcontroller-engine.json` in the :file:`IPYTHONDIR/profile_<name>/security`
544 directory on the engine's host, where it will be found automatically.
544 directory on the engine's host, where it will be found automatically.
545 * Call :command:`ipengine` with the ``--file=full_path_to_the_file``
545 * Call :command:`ipengine` with the ``--file=full_path_to_the_file``
546 flag.
546 flag.
547
547
548 The ``file`` flag works like this::
548 The ``file`` flag works like this::
549
549
550 $ ipengine --file=/path/to/my/ipcontroller-engine.json
550 $ ipengine --file=/path/to/my/ipcontroller-engine.json
551
551
552 .. note::
552 .. note::
553
553
554 If the controller's and engine's hosts all have a shared file system
554 If the controller's and engine's hosts all have a shared file system
555 (:file:`IPYTHONDIR/profile_<name>/security` is the same on all of them), then things
555 (:file:`IPYTHONDIR/profile_<name>/security` is the same on all of them), then things
556 will just work!
556 will just work!
557
557
558 SSH Tunnels
558 SSH Tunnels
559 ***********
559 ***********
560
560
561 If your engines are not on the same LAN as the controller, or you are on a highly
561 If your engines are not on the same LAN as the controller, or you are on a highly
562 restricted network where your nodes cannot see each others ports, then you can
562 restricted network where your nodes cannot see each others ports, then you can
563 use SSH tunnels to connect engines to the controller.
563 use SSH tunnels to connect engines to the controller.
564
564
565 .. note::
565 .. note::
566
566
567 This does not work in all cases. Manual tunnels may be an option, but are
567 This does not work in all cases. Manual tunnels may be an option, but are
568 highly inconvenient. Support for manual tunnels will be improved.
568 highly inconvenient. Support for manual tunnels will be improved.
569
569
570 You can instruct all engines to use ssh, by specifying the ssh server in
570 You can instruct all engines to use ssh, by specifying the ssh server in
571 :file:`ipcontroller-engine.json`:
571 :file:`ipcontroller-engine.json`:
572
572
573 .. I know this is really JSON, but the example is a subset of Python:
573 .. I know this is really JSON, but the example is a subset of Python:
574 .. sourcecode:: python
574 .. sourcecode:: python
575
575
576 {
576 {
577 "url":"tcp://192.168.1.123:56951",
577 "url":"tcp://192.168.1.123:56951",
578 "exec_key":"26f4c040-587d-4a4e-b58b-030b96399584",
578 "exec_key":"26f4c040-587d-4a4e-b58b-030b96399584",
579 "ssh":"user@example.com",
579 "ssh":"user@example.com",
580 "location":"192.168.1.123"
580 "location":"192.168.1.123"
581 }
581 }
582
582
583 This will be specified if you give the ``--enginessh=use@example.com`` argument when
583 This will be specified if you give the ``--enginessh=use@example.com`` argument when
584 starting :command:`ipcontroller`.
584 starting :command:`ipcontroller`.
585
585
586 Or you can specify an ssh server on the command-line when starting an engine::
586 Or you can specify an ssh server on the command-line when starting an engine::
587
587
588 $> ipengine --profile=foo --ssh=my.login.node
588 $> ipengine --profile=foo --ssh=my.login.node
589
589
590 For example, if your system is totally restricted, then all connections will actually be
590 For example, if your system is totally restricted, then all connections will actually be
591 loopback, and ssh tunnels will be used to connect engines to the controller::
591 loopback, and ssh tunnels will be used to connect engines to the controller::
592
592
593 [node1] $> ipcontroller --enginessh=node1
593 [node1] $> ipcontroller --enginessh=node1
594 [node2] $> ipengine
594 [node2] $> ipengine
595 [node3] $> ipcluster engines --n=4
595 [node3] $> ipcluster engines --n=4
596
596
597 Or if you want to start many engines on each node, the command `ipcluster engines --n=4`
597 Or if you want to start many engines on each node, the command `ipcluster engines --n=4`
598 without any configuration is equivalent to running ipengine 4 times.
598 without any configuration is equivalent to running ipengine 4 times.
599
599
600 An example using ipcontroller/engine with ssh
600 An example using ipcontroller/engine with ssh
601 ---------------------------------------------
601 ---------------------------------------------
602
602
603 No configuration files are necessary to use ipcontroller/engine in an SSH environment
603 No configuration files are necessary to use ipcontroller/engine in an SSH environment
604 without a shared filesystem. You simply need to make sure that the controller is listening
604 without a shared filesystem. You simply need to make sure that the controller is listening
605 on an interface visible to the engines, and move the connection file from the controller to
605 on an interface visible to the engines, and move the connection file from the controller to
606 the engines.
606 the engines.
607
607
608 1. start the controller, listening on an ip-address visible to the engine machines::
608 1. start the controller, listening on an ip-address visible to the engine machines::
609
609
610 [controller.host] $ ipcontroller --ip=192.168.1.16
610 [controller.host] $ ipcontroller --ip=192.168.1.16
611
611
612 [IPControllerApp] Using existing profile dir: u'/Users/me/.ipython/profile_default'
612 [IPControllerApp] Using existing profile dir: u'/Users/me/.ipython/profile_default'
613 [IPControllerApp] Hub listening on tcp://192.168.1.16:63320 for registration.
613 [IPControllerApp] Hub listening on tcp://192.168.1.16:63320 for registration.
614 [IPControllerApp] Hub using DB backend: 'IPython.parallel.controller.dictdb.DictDB'
614 [IPControllerApp] Hub using DB backend: 'IPython.parallel.controller.dictdb.DictDB'
615 [IPControllerApp] hub::created hub
615 [IPControllerApp] hub::created hub
616 [IPControllerApp] writing connection info to /Users/me/.ipython/profile_default/security/ipcontroller-client.json
616 [IPControllerApp] writing connection info to /Users/me/.ipython/profile_default/security/ipcontroller-client.json
617 [IPControllerApp] writing connection info to /Users/me/.ipython/profile_default/security/ipcontroller-engine.json
617 [IPControllerApp] writing connection info to /Users/me/.ipython/profile_default/security/ipcontroller-engine.json
618 [IPControllerApp] task::using Python leastload Task scheduler
618 [IPControllerApp] task::using Python leastload Task scheduler
619 [IPControllerApp] Heartmonitor started
619 [IPControllerApp] Heartmonitor started
620 [IPControllerApp] Creating pid file: /Users/me/.ipython/profile_default/pid/ipcontroller.pid
620 [IPControllerApp] Creating pid file: /Users/me/.ipython/profile_default/pid/ipcontroller.pid
621 Scheduler started [leastload]
621 Scheduler started [leastload]
622
622
623 2. on each engine, fetch the connection file with scp::
623 2. on each engine, fetch the connection file with scp::
624
624
625 [engine.host.n] $ scp controller.host:.ipython/profile_default/security/ipcontroller-engine.json ./
625 [engine.host.n] $ scp controller.host:.ipython/profile_default/security/ipcontroller-engine.json ./
626
626
627 .. note::
627 .. note::
628
628
629 The log output of ipcontroller above shows you where the json files were written.
629 The log output of ipcontroller above shows you where the json files were written.
630 They will be in :file:`~/.ipython` (or :file:`~/.config/ipython`) under
630 They will be in :file:`~/.ipython` under
631 :file:`profile_default/security/ipcontroller-engine.json`
631 :file:`profile_default/security/ipcontroller-engine.json`
632
632
633 3. start the engines, using the connection file::
633 3. start the engines, using the connection file::
634
634
635 [engine.host.n] $ ipengine --file=./ipcontroller-engine.json
635 [engine.host.n] $ ipengine --file=./ipcontroller-engine.json
636
636
637 A couple of notes:
637 A couple of notes:
638
638
639 * You can avoid having to fetch the connection file every time by adding ``--reuse`` flag
639 * You can avoid having to fetch the connection file every time by adding ``--reuse`` flag
640 to ipcontroller, which instructs the controller to read the previous connection file for
640 to ipcontroller, which instructs the controller to read the previous connection file for
641 connection info, rather than generate a new one with randomized ports.
641 connection info, rather than generate a new one with randomized ports.
642
642
643 * In step 2, if you fetch the connection file directly into the security dir of a profile,
643 * In step 2, if you fetch the connection file directly into the security dir of a profile,
644 then you need not specify its path directly, only the profile (assumes the path exists,
644 then you need not specify its path directly, only the profile (assumes the path exists,
645 otherwise you must create it first)::
645 otherwise you must create it first)::
646
646
647 [engine.host.n] $ scp controller.host:.ipython/profile_default/security/ipcontroller-engine.json ~/.config/ipython/profile_ssh/security/
647 [engine.host.n] $ scp controller.host:.ipython/profile_default/security/ipcontroller-engine.json ~/.ipython/profile_ssh/security/
648 [engine.host.n] $ ipengine --profile=ssh
648 [engine.host.n] $ ipengine --profile=ssh
649
649
650 Of course, if you fetch the file into the default profile, no arguments must be passed to
650 Of course, if you fetch the file into the default profile, no arguments must be passed to
651 ipengine at all.
651 ipengine at all.
652
652
653 * Note that ipengine *did not* specify the ip argument. In general, it is unlikely for any
653 * Note that ipengine *did not* specify the ip argument. In general, it is unlikely for any
654 connection information to be specified at the command-line to ipengine, as all of this
654 connection information to be specified at the command-line to ipengine, as all of this
655 information should be contained in the connection file written by ipcontroller.
655 information should be contained in the connection file written by ipcontroller.
656
656
657 Make JSON files persistent
657 Make JSON files persistent
658 --------------------------
658 --------------------------
659
659
660 At fist glance it may seem that that managing the JSON files is a bit
660 At fist glance it may seem that that managing the JSON files is a bit
661 annoying. Going back to the house and key analogy, copying the JSON around
661 annoying. Going back to the house and key analogy, copying the JSON around
662 each time you start the controller is like having to make a new key every time
662 each time you start the controller is like having to make a new key every time
663 you want to unlock the door and enter your house. As with your house, you want
663 you want to unlock the door and enter your house. As with your house, you want
664 to be able to create the key (or JSON file) once, and then simply use it at
664 to be able to create the key (or JSON file) once, and then simply use it at
665 any point in the future.
665 any point in the future.
666
666
667 To do this, the only thing you have to do is specify the `--reuse` flag, so that
667 To do this, the only thing you have to do is specify the `--reuse` flag, so that
668 the connection information in the JSON files remains accurate::
668 the connection information in the JSON files remains accurate::
669
669
670 $ ipcontroller --reuse
670 $ ipcontroller --reuse
671
671
672 Then, just copy the JSON files over the first time and you are set. You can
672 Then, just copy the JSON files over the first time and you are set. You can
673 start and stop the controller and engines any many times as you want in the
673 start and stop the controller and engines any many times as you want in the
674 future, just make sure to tell the controller to reuse the file.
674 future, just make sure to tell the controller to reuse the file.
675
675
676 .. note::
676 .. note::
677
677
678 You may ask the question: what ports does the controller listen on if you
678 You may ask the question: what ports does the controller listen on if you
679 don't tell is to use specific ones? The default is to use high random port
679 don't tell is to use specific ones? The default is to use high random port
680 numbers. We do this for two reasons: i) to increase security through
680 numbers. We do this for two reasons: i) to increase security through
681 obscurity and ii) to multiple controllers on a given host to start and
681 obscurity and ii) to multiple controllers on a given host to start and
682 automatically use different ports.
682 automatically use different ports.
683
683
684 Log files
684 Log files
685 ---------
685 ---------
686
686
687 All of the components of IPython have log files associated with them.
687 All of the components of IPython have log files associated with them.
688 These log files can be extremely useful in debugging problems with
688 These log files can be extremely useful in debugging problems with
689 IPython and can be found in the directory :file:`IPYTHONDIR/profile_<name>/log`.
689 IPython and can be found in the directory :file:`IPYTHONDIR/profile_<name>/log`.
690 Sending the log files to us will often help us to debug any problems.
690 Sending the log files to us will often help us to debug any problems.
691
691
692
692
693 Configuring `ipcontroller`
693 Configuring `ipcontroller`
694 ---------------------------
694 ---------------------------
695
695
696 The IPython Controller takes its configuration from the file :file:`ipcontroller_config.py`
696 The IPython Controller takes its configuration from the file :file:`ipcontroller_config.py`
697 in the active profile directory.
697 in the active profile directory.
698
698
699 Ports and addresses
699 Ports and addresses
700 *******************
700 *******************
701
701
702 In many cases, you will want to configure the Controller's network identity. By default,
702 In many cases, you will want to configure the Controller's network identity. By default,
703 the Controller listens only on loopback, which is the most secure but often impractical.
703 the Controller listens only on loopback, which is the most secure but often impractical.
704 To instruct the controller to listen on a specific interface, you can set the
704 To instruct the controller to listen on a specific interface, you can set the
705 :attr:`HubFactory.ip` trait. To listen on all interfaces, simply specify:
705 :attr:`HubFactory.ip` trait. To listen on all interfaces, simply specify:
706
706
707 .. sourcecode:: python
707 .. sourcecode:: python
708
708
709 c.HubFactory.ip = '*'
709 c.HubFactory.ip = '*'
710
710
711 When connecting to a Controller that is listening on loopback or behind a firewall, it may
711 When connecting to a Controller that is listening on loopback or behind a firewall, it may
712 be necessary to specify an SSH server to use for tunnels, and the external IP of the
712 be necessary to specify an SSH server to use for tunnels, and the external IP of the
713 Controller. If you specified that the HubFactory listen on loopback, or all interfaces,
713 Controller. If you specified that the HubFactory listen on loopback, or all interfaces,
714 then IPython will try to guess the external IP. If you are on a system with VM network
714 then IPython will try to guess the external IP. If you are on a system with VM network
715 devices, or many interfaces, this guess may be incorrect. In these cases, you will want
715 devices, or many interfaces, this guess may be incorrect. In these cases, you will want
716 to specify the 'location' of the Controller. This is the IP of the machine the Controller
716 to specify the 'location' of the Controller. This is the IP of the machine the Controller
717 is on, as seen by the clients, engines, or the SSH server used to tunnel connections.
717 is on, as seen by the clients, engines, or the SSH server used to tunnel connections.
718
718
719 For example, to set up a cluster with a Controller on a work node, using ssh tunnels
719 For example, to set up a cluster with a Controller on a work node, using ssh tunnels
720 through the login node, an example :file:`ipcontroller_config.py` might contain:
720 through the login node, an example :file:`ipcontroller_config.py` might contain:
721
721
722 .. sourcecode:: python
722 .. sourcecode:: python
723
723
724 # allow connections on all interfaces from engines
724 # allow connections on all interfaces from engines
725 # engines on the same node will use loopback, while engines
725 # engines on the same node will use loopback, while engines
726 # from other nodes will use an external IP
726 # from other nodes will use an external IP
727 c.HubFactory.ip = '*'
727 c.HubFactory.ip = '*'
728
728
729 # you typically only need to specify the location when there are extra
729 # you typically only need to specify the location when there are extra
730 # interfaces that may not be visible to peer nodes (e.g. VM interfaces)
730 # interfaces that may not be visible to peer nodes (e.g. VM interfaces)
731 c.HubFactory.location = '10.0.1.5'
731 c.HubFactory.location = '10.0.1.5'
732 # or to get an automatic value, try this:
732 # or to get an automatic value, try this:
733 import socket
733 import socket
734 hostname = socket.gethostname()
734 hostname = socket.gethostname()
735 # alternate choices for hostname include `socket.getfqdn()`
735 # alternate choices for hostname include `socket.getfqdn()`
736 # or `socket.gethostname() + '.local'`
736 # or `socket.gethostname() + '.local'`
737
737
738 ex_ip = socket.gethostbyname_ex(hostname)[-1][-1]
738 ex_ip = socket.gethostbyname_ex(hostname)[-1][-1]
739 c.HubFactory.location = ex_ip
739 c.HubFactory.location = ex_ip
740
740
741 # now instruct clients to use the login node for SSH tunnels:
741 # now instruct clients to use the login node for SSH tunnels:
742 c.HubFactory.ssh_server = 'login.mycluster.net'
742 c.HubFactory.ssh_server = 'login.mycluster.net'
743
743
744 After doing this, your :file:`ipcontroller-client.json` file will look something like this:
744 After doing this, your :file:`ipcontroller-client.json` file will look something like this:
745
745
746 .. this can be Python, despite the fact that it's actually JSON, because it's
746 .. this can be Python, despite the fact that it's actually JSON, because it's
747 .. still valid Python
747 .. still valid Python
748
748
749 .. sourcecode:: python
749 .. sourcecode:: python
750
750
751 {
751 {
752 "url":"tcp:\/\/*:43447",
752 "url":"tcp:\/\/*:43447",
753 "exec_key":"9c7779e4-d08a-4c3b-ba8e-db1f80b562c1",
753 "exec_key":"9c7779e4-d08a-4c3b-ba8e-db1f80b562c1",
754 "ssh":"login.mycluster.net",
754 "ssh":"login.mycluster.net",
755 "location":"10.0.1.5"
755 "location":"10.0.1.5"
756 }
756 }
757
757
758 Then this file will be all you need for a client to connect to the controller, tunneling
758 Then this file will be all you need for a client to connect to the controller, tunneling
759 SSH connections through login.mycluster.net.
759 SSH connections through login.mycluster.net.
760
760
761 Database Backend
761 Database Backend
762 ****************
762 ****************
763
763
764 The Hub stores all messages and results passed between Clients and Engines.
764 The Hub stores all messages and results passed between Clients and Engines.
765 For large and/or long-running clusters, it would be unreasonable to keep all
765 For large and/or long-running clusters, it would be unreasonable to keep all
766 of this information in memory. For this reason, we have two database backends:
766 of this information in memory. For this reason, we have two database backends:
767 [MongoDB]_ via PyMongo_, and SQLite with the stdlib :py:mod:`sqlite`.
767 [MongoDB]_ via PyMongo_, and SQLite with the stdlib :py:mod:`sqlite`.
768
768
769 MongoDB is our design target, and the dict-like model it uses has driven our design. As far
769 MongoDB is our design target, and the dict-like model it uses has driven our design. As far
770 as we are concerned, BSON can be considered essentially the same as JSON, adding support
770 as we are concerned, BSON can be considered essentially the same as JSON, adding support
771 for binary data and datetime objects, and any new database backend must support the same
771 for binary data and datetime objects, and any new database backend must support the same
772 data types.
772 data types.
773
773
774 .. seealso::
774 .. seealso::
775
775
776 MongoDB `BSON doc <http://www.mongodb.org/display/DOCS/BSON>`_
776 MongoDB `BSON doc <http://www.mongodb.org/display/DOCS/BSON>`_
777
777
778 To use one of these backends, you must set the :attr:`HubFactory.db_class` trait:
778 To use one of these backends, you must set the :attr:`HubFactory.db_class` trait:
779
779
780 .. sourcecode:: python
780 .. sourcecode:: python
781
781
782 # for a simple dict-based in-memory implementation, use dictdb
782 # for a simple dict-based in-memory implementation, use dictdb
783 # This is the default and the fastest, since it doesn't involve the filesystem
783 # This is the default and the fastest, since it doesn't involve the filesystem
784 c.HubFactory.db_class = 'IPython.parallel.controller.dictdb.DictDB'
784 c.HubFactory.db_class = 'IPython.parallel.controller.dictdb.DictDB'
785
785
786 # To use MongoDB:
786 # To use MongoDB:
787 c.HubFactory.db_class = 'IPython.parallel.controller.mongodb.MongoDB'
787 c.HubFactory.db_class = 'IPython.parallel.controller.mongodb.MongoDB'
788
788
789 # and SQLite:
789 # and SQLite:
790 c.HubFactory.db_class = 'IPython.parallel.controller.sqlitedb.SQLiteDB'
790 c.HubFactory.db_class = 'IPython.parallel.controller.sqlitedb.SQLiteDB'
791
791
792 # You can use NoDB to disable the database altogether, in case you don't need
792 # You can use NoDB to disable the database altogether, in case you don't need
793 # to reuse tasks or results, and want to keep memory consumption under control.
793 # to reuse tasks or results, and want to keep memory consumption under control.
794 c.HubFactory.db_class = 'IPython.parallel.controller.dictdb.NoDB'
794 c.HubFactory.db_class = 'IPython.parallel.controller.dictdb.NoDB'
795
795
796 When using the proper databases, you can actually allow for tasks to persist from
796 When using the proper databases, you can actually allow for tasks to persist from
797 one session to the next by specifying the MongoDB database or SQLite table in
797 one session to the next by specifying the MongoDB database or SQLite table in
798 which tasks are to be stored. The default is to use a table named for the Hub's Session,
798 which tasks are to be stored. The default is to use a table named for the Hub's Session,
799 which is a UUID, and thus different every time.
799 which is a UUID, and thus different every time.
800
800
801 .. sourcecode:: python
801 .. sourcecode:: python
802
802
803 # To keep persistant task history in MongoDB:
803 # To keep persistant task history in MongoDB:
804 c.MongoDB.database = 'tasks'
804 c.MongoDB.database = 'tasks'
805
805
806 # and in SQLite:
806 # and in SQLite:
807 c.SQLiteDB.table = 'tasks'
807 c.SQLiteDB.table = 'tasks'
808
808
809
809
810 Since MongoDB servers can be running remotely or configured to listen on a particular port,
810 Since MongoDB servers can be running remotely or configured to listen on a particular port,
811 you can specify any arguments you may need to the PyMongo `Connection
811 you can specify any arguments you may need to the PyMongo `Connection
812 <http://api.mongodb.org/python/1.9/api/pymongo/connection.html#pymongo.connection.Connection>`_:
812 <http://api.mongodb.org/python/1.9/api/pymongo/connection.html#pymongo.connection.Connection>`_:
813
813
814 .. sourcecode:: python
814 .. sourcecode:: python
815
815
816 # positional args to pymongo.Connection
816 # positional args to pymongo.Connection
817 c.MongoDB.connection_args = []
817 c.MongoDB.connection_args = []
818
818
819 # keyword args to pymongo.Connection
819 # keyword args to pymongo.Connection
820 c.MongoDB.connection_kwargs = {}
820 c.MongoDB.connection_kwargs = {}
821
821
822 But sometimes you are moving lots of data around quickly, and you don't need
822 But sometimes you are moving lots of data around quickly, and you don't need
823 that information to be stored for later access, even by other Clients to this
823 that information to be stored for later access, even by other Clients to this
824 same session. For this case, we have a dummy database, which doesn't actually
824 same session. For this case, we have a dummy database, which doesn't actually
825 store anything. This lets the Hub stay small in memory, at the obvious expense
825 store anything. This lets the Hub stay small in memory, at the obvious expense
826 of being able to access the information that would have been stored in the
826 of being able to access the information that would have been stored in the
827 database (used for task resubmission, requesting results of tasks you didn't
827 database (used for task resubmission, requesting results of tasks you didn't
828 submit, etc.). To use this backend, simply pass ``--nodb`` to
828 submit, etc.). To use this backend, simply pass ``--nodb`` to
829 :command:`ipcontroller` on the command-line, or specify the :class:`NoDB` class
829 :command:`ipcontroller` on the command-line, or specify the :class:`NoDB` class
830 in your :file:`ipcontroller_config.py` as described above.
830 in your :file:`ipcontroller_config.py` as described above.
831
831
832
832
833 .. seealso::
833 .. seealso::
834
834
835 For more information on the database backends, see the :ref:`db backend reference <parallel_db>`.
835 For more information on the database backends, see the :ref:`db backend reference <parallel_db>`.
836
836
837
837
838 .. _PyMongo: http://api.mongodb.org/python/1.9/
838 .. _PyMongo: http://api.mongodb.org/python/1.9/
839
839
840 Configuring `ipengine`
840 Configuring `ipengine`
841 -----------------------
841 -----------------------
842
842
843 The IPython Engine takes its configuration from the file :file:`ipengine_config.py`
843 The IPython Engine takes its configuration from the file :file:`ipengine_config.py`
844
844
845 The Engine itself also has some amount of configuration. Most of this
845 The Engine itself also has some amount of configuration. Most of this
846 has to do with initializing MPI or connecting to the controller.
846 has to do with initializing MPI or connecting to the controller.
847
847
848 To instruct the Engine to initialize with an MPI environment set up by
848 To instruct the Engine to initialize with an MPI environment set up by
849 mpi4py, add:
849 mpi4py, add:
850
850
851 .. sourcecode:: python
851 .. sourcecode:: python
852
852
853 c.MPI.use = 'mpi4py'
853 c.MPI.use = 'mpi4py'
854
854
855 In this case, the Engine will use our default mpi4py init script to set up
855 In this case, the Engine will use our default mpi4py init script to set up
856 the MPI environment prior to exection. We have default init scripts for
856 the MPI environment prior to exection. We have default init scripts for
857 mpi4py and pytrilinos. If you want to specify your own code to be run
857 mpi4py and pytrilinos. If you want to specify your own code to be run
858 at the beginning, specify `c.MPI.init_script`.
858 at the beginning, specify `c.MPI.init_script`.
859
859
860 You can also specify a file or python command to be run at startup of the
860 You can also specify a file or python command to be run at startup of the
861 Engine:
861 Engine:
862
862
863 .. sourcecode:: python
863 .. sourcecode:: python
864
864
865 c.IPEngineApp.startup_script = u'/path/to/my/startup.py'
865 c.IPEngineApp.startup_script = u'/path/to/my/startup.py'
866
866
867 c.IPEngineApp.startup_command = 'import numpy, scipy, mpi4py'
867 c.IPEngineApp.startup_command = 'import numpy, scipy, mpi4py'
868
868
869 These commands/files will be run again, after each
869 These commands/files will be run again, after each
870
870
871 It's also useful on systems with shared filesystems to run the engines
871 It's also useful on systems with shared filesystems to run the engines
872 in some scratch directory. This can be set with:
872 in some scratch directory. This can be set with:
873
873
874 .. sourcecode:: python
874 .. sourcecode:: python
875
875
876 c.IPEngineApp.work_dir = u'/path/to/scratch/'
876 c.IPEngineApp.work_dir = u'/path/to/scratch/'
877
877
878
878
879
879
880 .. [MongoDB] MongoDB database http://www.mongodb.org
880 .. [MongoDB] MongoDB database http://www.mongodb.org
881
881
882 .. [PBS] Portable Batch System http://www.openpbs.org
882 .. [PBS] Portable Batch System http://www.openpbs.org
883
883
884 .. [SSH] SSH-Agent http://en.wikipedia.org/wiki/ssh-agent
884 .. [SSH] SSH-Agent http://en.wikipedia.org/wiki/ssh-agent
General Comments 0
You need to be logged in to leave comments. Login now