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