##// END OF EJS Templates
Various polishing of interactive reference doc.
Thomas Kluyver -
Show More
@@ -1,1163 +1,1093 b''
1 =================
1 =================
2 IPython reference
2 IPython reference
3 =================
3 =================
4
4
5 .. _command_line_options:
5 .. _command_line_options:
6
6
7 Command-line usage
7 Command-line usage
8 ==================
8 ==================
9
9
10 You start IPython with the command::
10 You start IPython with the command::
11
11
12 $ ipython [options] files
12 $ ipython [options] files
13
13
14 If invoked with no options, it executes all the files listed in sequence
14 If invoked with no options, it executes all the files listed in sequence
15 and drops you into the interpreter while still acknowledging any options
15 and drops you into the interpreter while still acknowledging any options
16 you may have set in your ipython_config.py. This behavior is different from
16 you may have set in your ipython_config.py. This behavior is different from
17 standard Python, which when called as python -i will only execute one
17 standard Python, which when called as python -i will only execute one
18 file and ignore your configuration setup.
18 file and ignore your configuration setup.
19
19
20 Please note that some of the configuration options are not available at
20 Please note that some of the configuration options are not available at
21 the command line, simply because they are not practical here. Look into
21 the command line, simply because they are not practical here. Look into
22 your configuration files for details on those. There are separate configuration
22 your configuration files for details on those. There are separate configuration
23 files for each profile, and the files look like :file:`ipython_config.py` or
23 files for each profile, and the files look like :file:`ipython_config.py` or
24 :file:`ipython_config_{frontendname}.py`. Profile directories look like
24 :file:`ipython_config_{frontendname}.py`. Profile directories look like
25 :file:`profile_{profilename}` and are typically installed in the :envvar:`IPYTHONDIR` directory,
25 :file:`profile_{profilename}` and are typically installed in the :envvar:`IPYTHONDIR` directory,
26 which defaults to :file:`$HOME/.ipython`. For Windows users, :envvar:`HOME`
26 which defaults to :file:`$HOME/.ipython`. For Windows users, :envvar:`HOME`
27 resolves to :file:`C:\\Users\\{YourUserName}` in most instances.
27 resolves to :file:`C:\\Users\\{YourUserName}` in most instances.
28
28
29
30 Eventloop integration
31 ---------------------
32
33 Previously IPython had command line options for controlling GUI event loop
34 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
35 version 0.11, these have been removed. Please see the new ``%gui``
36 magic command or :ref:`this section <gui_support>` for details on the new
37 interface, or specify the gui at the commandline::
38
39 $ ipython --gui=qt
40
41
42 Command-line Options
29 Command-line Options
43 --------------------
30 --------------------
44
31
45 To see the options IPython accepts, use ``ipython --help`` (and you probably
32 To see the options IPython accepts, use ``ipython --help`` (and you probably
46 should run the output through a pager such as ``ipython --help | less`` for
33 should run the output through a pager such as ``ipython --help | less`` for
47 more convenient reading). This shows all the options that have a single-word
34 more convenient reading). This shows all the options that have a single-word
48 alias to control them, but IPython lets you configure all of its objects from
35 alias to control them, but IPython lets you configure all of its objects from
49 the command-line by passing the full class name and a corresponding value; type
36 the command-line by passing the full class name and a corresponding value; type
50 ``ipython --help-all`` to see this full list. For example::
37 ``ipython --help-all`` to see this full list. For example::
51
38
52 ipython --matplotlib qt
39 ipython --matplotlib qt
53
40
54 is equivalent to::
41 is equivalent to::
55
42
56 ipython --TerminalIPythonApp.matplotlib='qt'
43 ipython --TerminalIPythonApp.matplotlib='qt'
57
44
58 Note that in the second form, you *must* use the equal sign, as the expression
45 Note that in the second form, you *must* use the equal sign, as the expression
59 is evaluated as an actual Python assignment. While in the above example the
46 is evaluated as an actual Python assignment. While in the above example the
60 short form is more convenient, only the most common options have a short form,
47 short form is more convenient, only the most common options have a short form,
61 while any configurable variable in IPython can be set at the command-line by
48 while any configurable variable in IPython can be set at the command-line by
62 using the long form. This long form is the same syntax used in the
49 using the long form. This long form is the same syntax used in the
63 configuration files, if you want to set these options permanently.
50 configuration files, if you want to set these options permanently.
64
51
65
52
66 Interactive use
53 Interactive use
67 ===============
54 ===============
68
55
69 IPython is meant to work as a drop-in replacement for the standard interactive
56 IPython is meant to work as a drop-in replacement for the standard interactive
70 interpreter. As such, any code which is valid python should execute normally
57 interpreter. As such, any code which is valid python should execute normally
71 under IPython (cases where this is not true should be reported as bugs). It
58 under IPython (cases where this is not true should be reported as bugs). It
72 does, however, offer many features which are not available at a standard python
59 does, however, offer many features which are not available at a standard python
73 prompt. What follows is a list of these.
60 prompt. What follows is a list of these.
74
61
75
62
76 Caution for Windows users
63 Caution for Windows users
77 -------------------------
64 -------------------------
78
65
79 Windows, unfortunately, uses the '\\' character as a path separator. This is a
66 Windows, unfortunately, uses the '\\' character as a path separator. This is a
80 terrible choice, because '\\' also represents the escape character in most
67 terrible choice, because '\\' also represents the escape character in most
81 modern programming languages, including Python. For this reason, using '/'
68 modern programming languages, including Python. For this reason, using '/'
82 character is recommended if you have problems with ``\``. However, in Windows
69 character is recommended if you have problems with ``\``. However, in Windows
83 commands '/' flags options, so you can not use it for the root directory. This
70 commands '/' flags options, so you can not use it for the root directory. This
84 means that paths beginning at the root must be typed in a contrived manner
71 means that paths beginning at the root must be typed in a contrived manner
85 like: ``%copy \opt/foo/bar.txt \tmp``
72 like: ``%copy \opt/foo/bar.txt \tmp``
86
73
87 .. _magic:
74 .. _magic:
88
75
89 Magic command system
76 Magic command system
90 --------------------
77 --------------------
91
78
92 IPython will treat any line whose first character is a % as a special
79 IPython will treat any line whose first character is a % as a special
93 call to a 'magic' function. These allow you to control the behavior of
80 call to a 'magic' function. These allow you to control the behavior of
94 IPython itself, plus a lot of system-type features. They are all
81 IPython itself, plus a lot of system-type features. They are all
95 prefixed with a % character, but parameters are given without
82 prefixed with a % character, but parameters are given without
96 parentheses or quotes.
83 parentheses or quotes.
97
84
98 Lines that begin with ``%%`` signal a *cell magic*: they take as arguments not
85 Lines that begin with ``%%`` signal a *cell magic*: they take as arguments not
99 only the rest of the current line, but all lines below them as well, in the
86 only the rest of the current line, but all lines below them as well, in the
100 current execution block. Cell magics can in fact make arbitrary modifications
87 current execution block. Cell magics can in fact make arbitrary modifications
101 to the input they receive, which need not even be valid Python code at all.
88 to the input they receive, which need not even be valid Python code at all.
102 They receive the whole block as a single string.
89 They receive the whole block as a single string.
103
90
104 As a line magic example, the ``%cd`` magic works just like the OS command of
91 As a line magic example, the ``%cd`` magic works just like the OS command of
105 the same name::
92 the same name::
106
93
107 In [8]: %cd
94 In [8]: %cd
108 /home/fperez
95 /home/fperez
109
96
110 The following uses the builtin ``timeit`` in cell mode::
97 The following uses the builtin ``timeit`` in cell mode::
111
98
112 In [10]: %%timeit x = range(10000)
99 In [10]: %%timeit x = range(10000)
113 ...: min(x)
100 ...: min(x)
114 ...: max(x)
101 ...: max(x)
115 ...:
102 ...:
116 1000 loops, best of 3: 438 us per loop
103 1000 loops, best of 3: 438 us per loop
117
104
118 In this case, ``x = range(10000)`` is called as the line argument, and the
105 In this case, ``x = range(10000)`` is called as the line argument, and the
119 block with ``min(x)`` and ``max(x)`` is called as the cell body. The
106 block with ``min(x)`` and ``max(x)`` is called as the cell body. The
120 ``timeit`` magic receives both.
107 ``timeit`` magic receives both.
121
108
122 If you have 'automagic' enabled (as it by default), you don't need to type in
109 If you have 'automagic' enabled (as it by default), you don't need to type in
123 the single ``%`` explicitly for line magics; IPython will scan its internal
110 the single ``%`` explicitly for line magics; IPython will scan its internal
124 list of magic functions and call one if it exists. With automagic on you can
111 list of magic functions and call one if it exists. With automagic on you can
125 then just type ``cd mydir`` to go to directory 'mydir'::
112 then just type ``cd mydir`` to go to directory 'mydir'::
126
113
127 In [9]: cd mydir
114 In [9]: cd mydir
128 /home/fperez/mydir
115 /home/fperez/mydir
129
116
130 Note that cell magics *always* require an explicit ``%%`` prefix, automagic
117 Note that cell magics *always* require an explicit ``%%`` prefix, automagic
131 calling only works for line magics.
118 calling only works for line magics.
132
119
133 The automagic system has the lowest possible precedence in name searches, so
120 The automagic system has the lowest possible precedence in name searches, so
134 defining an identifier with the same name as an existing magic function will
121 you can freely use variables with the same names as magic commands. If a magic
135 shadow it for automagic use. You can still access the shadowed magic function
122 command is 'shadowed' by a variable, you will need the explicit ``%`` prefix to
136 by explicitly using the ``%`` character at the beginning of the line.
123 use it:
137
138 An example (with automagic on) should clarify all this:
139
124
140 .. sourcecode:: ipython
125 .. sourcecode:: ipython
141
126
142 In [1]: cd ipython # %cd is called by automagic
127 In [1]: cd ipython # %cd is called by automagic
143 /home/fperez/ipython
128 /home/fperez/ipython
144
129
145 In [2]: cd=1 # now cd is just a variable
130 In [2]: cd=1 # now cd is just a variable
146
131
147 In [3]: cd .. # and doesn't work as a function anymore
132 In [3]: cd .. # and doesn't work as a function anymore
148 File "<ipython-input-3-9fedb3aff56c>", line 1
133 File "<ipython-input-3-9fedb3aff56c>", line 1
149 cd ..
134 cd ..
150 ^
135 ^
151 SyntaxError: invalid syntax
136 SyntaxError: invalid syntax
152
137
153
138
154 In [4]: %cd .. # but %cd always works
139 In [4]: %cd .. # but %cd always works
155 /home/fperez
140 /home/fperez
156
141
157 In [5]: del cd # if you remove the cd variable, automagic works again
142 In [5]: del cd # if you remove the cd variable, automagic works again
158
143
159 In [6]: cd ipython
144 In [6]: cd ipython
160
145
161 /home/fperez/ipython
146 /home/fperez/ipython
162
147
163 .. _defining_magics:
148 .. _defining_magics:
164
149
165 Defining your own magics
150 Defining your own magics
166 ++++++++++++++++++++++++
151 ++++++++++++++++++++++++
167
152
168 There are two main ways to define your own magic functions: from standalone
153 There are two main ways to define your own magic functions: from standalone
169 functions and by inheriting from a base class provided by IPython:
154 functions and by inheriting from a base class provided by IPython:
170 :class:`IPython.core.magic.Magics`. Below we show code you can place in a file
155 :class:`IPython.core.magic.Magics`. Below we show code you can place in a file
171 that you load from your configuration, such as any file in the ``startup``
156 that you load from your configuration, such as any file in the ``startup``
172 subdirectory of your default IPython profile.
157 subdirectory of your default IPython profile.
173
158
174 First, let us see the simplest case. The following shows how to create a line
159 First, let us see the simplest case. The following shows how to create a line
175 magic, a cell one and one that works in both modes, using just plain functions:
160 magic, a cell one and one that works in both modes, using just plain functions:
176
161
177 .. sourcecode:: python
162 .. sourcecode:: python
178
163
179 from IPython.core.magic import (register_line_magic, register_cell_magic,
164 from IPython.core.magic import (register_line_magic, register_cell_magic,
180 register_line_cell_magic)
165 register_line_cell_magic)
181
166
182 @register_line_magic
167 @register_line_magic
183 def lmagic(line):
168 def lmagic(line):
184 "my line magic"
169 "my line magic"
185 return line
170 return line
186
171
187 @register_cell_magic
172 @register_cell_magic
188 def cmagic(line, cell):
173 def cmagic(line, cell):
189 "my cell magic"
174 "my cell magic"
190 return line, cell
175 return line, cell
191
176
192 @register_line_cell_magic
177 @register_line_cell_magic
193 def lcmagic(line, cell=None):
178 def lcmagic(line, cell=None):
194 "Magic that works both as %lcmagic and as %%lcmagic"
179 "Magic that works both as %lcmagic and as %%lcmagic"
195 if cell is None:
180 if cell is None:
196 print("Called as line magic")
181 print("Called as line magic")
197 return line
182 return line
198 else:
183 else:
199 print("Called as cell magic")
184 print("Called as cell magic")
200 return line, cell
185 return line, cell
201
186
202 # We delete these to avoid name conflicts for automagic to work
187 # We delete these to avoid name conflicts for automagic to work
203 del lmagic, lcmagic
188 del lmagic, lcmagic
204
189
205
190
206 You can also create magics of all three kinds by inheriting from the
191 You can also create magics of all three kinds by inheriting from the
207 :class:`IPython.core.magic.Magics` class. This lets you create magics that can
192 :class:`IPython.core.magic.Magics` class. This lets you create magics that can
208 potentially hold state in between calls, and that have full access to the main
193 potentially hold state in between calls, and that have full access to the main
209 IPython object:
194 IPython object:
210
195
211 .. sourcecode:: python
196 .. sourcecode:: python
212
197
213 # This code can be put in any Python module, it does not require IPython
198 # This code can be put in any Python module, it does not require IPython
214 # itself to be running already. It only creates the magics subclass but
199 # itself to be running already. It only creates the magics subclass but
215 # doesn't instantiate it yet.
200 # doesn't instantiate it yet.
216 from __future__ import print_function
201 from __future__ import print_function
217 from IPython.core.magic import (Magics, magics_class, line_magic,
202 from IPython.core.magic import (Magics, magics_class, line_magic,
218 cell_magic, line_cell_magic)
203 cell_magic, line_cell_magic)
219
204
220 # The class MUST call this class decorator at creation time
205 # The class MUST call this class decorator at creation time
221 @magics_class
206 @magics_class
222 class MyMagics(Magics):
207 class MyMagics(Magics):
223
208
224 @line_magic
209 @line_magic
225 def lmagic(self, line):
210 def lmagic(self, line):
226 "my line magic"
211 "my line magic"
227 print("Full access to the main IPython object:", self.shell)
212 print("Full access to the main IPython object:", self.shell)
228 print("Variables in the user namespace:", list(self.shell.user_ns.keys()))
213 print("Variables in the user namespace:", list(self.shell.user_ns.keys()))
229 return line
214 return line
230
215
231 @cell_magic
216 @cell_magic
232 def cmagic(self, line, cell):
217 def cmagic(self, line, cell):
233 "my cell magic"
218 "my cell magic"
234 return line, cell
219 return line, cell
235
220
236 @line_cell_magic
221 @line_cell_magic
237 def lcmagic(self, line, cell=None):
222 def lcmagic(self, line, cell=None):
238 "Magic that works both as %lcmagic and as %%lcmagic"
223 "Magic that works both as %lcmagic and as %%lcmagic"
239 if cell is None:
224 if cell is None:
240 print("Called as line magic")
225 print("Called as line magic")
241 return line
226 return line
242 else:
227 else:
243 print("Called as cell magic")
228 print("Called as cell magic")
244 return line, cell
229 return line, cell
245
230
246
231
247 # In order to actually use these magics, you must register them with a
232 # In order to actually use these magics, you must register them with a
248 # running IPython. This code must be placed in a file that is loaded once
233 # running IPython. This code must be placed in a file that is loaded once
249 # IPython is up and running:
234 # IPython is up and running:
250 ip = get_ipython()
235 ip = get_ipython()
251 # You can register the class itself without instantiating it. IPython will
236 # You can register the class itself without instantiating it. IPython will
252 # call the default constructor on it.
237 # call the default constructor on it.
253 ip.register_magics(MyMagics)
238 ip.register_magics(MyMagics)
254
239
255 If you want to create a class with a different constructor that holds
240 If you want to create a class with a different constructor that holds
256 additional state, then you should always call the parent constructor and
241 additional state, then you should always call the parent constructor and
257 instantiate the class yourself before registration:
242 instantiate the class yourself before registration:
258
243
259 .. sourcecode:: python
244 .. sourcecode:: python
260
245
261 @magics_class
246 @magics_class
262 class StatefulMagics(Magics):
247 class StatefulMagics(Magics):
263 "Magics that hold additional state"
248 "Magics that hold additional state"
264
249
265 def __init__(self, shell, data):
250 def __init__(self, shell, data):
266 # You must call the parent constructor
251 # You must call the parent constructor
267 super(StatefulMagics, self).__init__(shell)
252 super(StatefulMagics, self).__init__(shell)
268 self.data = data
253 self.data = data
269
254
270 # etc...
255 # etc...
271
256
272 # This class must then be registered with a manually created instance,
257 # This class must then be registered with a manually created instance,
273 # since its constructor has different arguments from the default:
258 # since its constructor has different arguments from the default:
274 ip = get_ipython()
259 ip = get_ipython()
275 magics = StatefulMagics(ip, some_data)
260 magics = StatefulMagics(ip, some_data)
276 ip.register_magics(magics)
261 ip.register_magics(magics)
277
262
278
263
279 In earlier versions, IPython had an API for the creation of line magics (cell
264 In earlier versions, IPython had an API for the creation of line magics (cell
280 magics did not exist at the time) that required you to create functions with a
265 magics did not exist at the time) that required you to create functions with a
281 method-looking signature and to manually pass both the function and the name.
266 method-looking signature and to manually pass both the function and the name.
282 While this API is no longer recommended, it remains indefinitely supported for
267 While this API is no longer recommended, it remains indefinitely supported for
283 backwards compatibility purposes. With the old API, you'd create a magic as
268 backwards compatibility purposes. With the old API, you'd create a magic as
284 follows:
269 follows:
285
270
286 .. sourcecode:: python
271 .. sourcecode:: python
287
272
288 def func(self, line):
273 def func(self, line):
289 print("Line magic called with line:", line)
274 print("Line magic called with line:", line)
290 print("IPython object:", self.shell)
275 print("IPython object:", self.shell)
291
276
292 ip = get_ipython()
277 ip = get_ipython()
293 # Declare this function as the magic %mycommand
278 # Declare this function as the magic %mycommand
294 ip.define_magic('mycommand', func)
279 ip.define_magic('mycommand', func)
295
280
296 Type ``%magic`` for more information, including a list of all available magic
281 Type ``%magic`` for more information, including a list of all available magic
297 functions at any time and their docstrings. You can also type
282 functions at any time and their docstrings. You can also type
298 ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for
283 ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for
299 information on the '?' system) to get information about any particular magic
284 information on the '?' system) to get information about any particular magic
300 function you are interested in.
285 function you are interested in.
301
286
302 The API documentation for the :mod:`IPython.core.magic` module contains the full
287 The API documentation for the :mod:`IPython.core.magic` module contains the full
303 docstrings of all currently available magic commands.
288 docstrings of all currently available magic commands.
304
289
305
290
306 Access to the standard Python help
291 Access to the standard Python help
307 ----------------------------------
292 ----------------------------------
308
293
309 Simply type ``help()`` to access Python's standard help system. You can
294 Simply type ``help()`` to access Python's standard help system. You can
310 also type ``help(object)`` for information about a given object, or
295 also type ``help(object)`` for information about a given object, or
311 ``help('keyword')`` for information on a keyword. You may need to configure your
296 ``help('keyword')`` for information on a keyword. You may need to configure your
312 PYTHONDOCS environment variable for this feature to work correctly.
297 PYTHONDOCS environment variable for this feature to work correctly.
313
298
314 .. _dynamic_object_info:
299 .. _dynamic_object_info:
315
300
316 Dynamic object information
301 Dynamic object information
317 --------------------------
302 --------------------------
318
303
319 Typing ``?word`` or ``word?`` prints detailed information about an object. If
304 Typing ``?word`` or ``word?`` prints detailed information about an object. If
320 certain strings in the object are too long (e.g. function signatures) they get
305 certain strings in the object are too long (e.g. function signatures) they get
321 snipped in the center for brevity. This system gives access variable types and
306 snipped in the center for brevity. This system gives access variable types and
322 values, docstrings, function prototypes and other useful information.
307 values, docstrings, function prototypes and other useful information.
323
308
324 If the information will not fit in the terminal, it is displayed in a pager
309 If the information will not fit in the terminal, it is displayed in a pager
325 (``less`` if available, otherwise a basic internal pager).
310 (``less`` if available, otherwise a basic internal pager).
326
311
327 Typing ``??word`` or ``word??`` gives access to the full information, including
312 Typing ``??word`` or ``word??`` gives access to the full information, including
328 the source code where possible. Long strings are not snipped.
313 the source code where possible. Long strings are not snipped.
329
314
330 The following magic functions are particularly useful for gathering
315 The following magic functions are particularly useful for gathering
331 information about your working environment. You can get more details by
316 information about your working environment. You can get more details by
332 typing ``%magic`` or querying them individually (``%function_name?``);
317 typing ``%magic`` or querying them individually (``%function_name?``);
333 this is just a summary:
318 this is just a summary:
334
319
335 * **%pdoc <object>**: Print (or run through a pager if too long) the
320 * **%pdoc <object>**: Print (or run through a pager if too long) the
336 docstring for an object. If the given object is a class, it will
321 docstring for an object. If the given object is a class, it will
337 print both the class and the constructor docstrings.
322 print both the class and the constructor docstrings.
338 * **%pdef <object>**: Print the call signature for any callable
323 * **%pdef <object>**: Print the call signature for any callable
339 object. If the object is a class, print the constructor information.
324 object. If the object is a class, print the constructor information.
340 * **%psource <object>**: Print (or run through a pager if too long)
325 * **%psource <object>**: Print (or run through a pager if too long)
341 the source code for an object.
326 the source code for an object.
342 * **%pfile <object>**: Show the entire source file where an object was
327 * **%pfile <object>**: Show the entire source file where an object was
343 defined via a pager, opening it at the line where the object
328 defined via a pager, opening it at the line where the object
344 definition begins.
329 definition begins.
345 * **%who/%whos**: These functions give information about identifiers
330 * **%who/%whos**: These functions give information about identifiers
346 you have defined interactively (not things you loaded or defined
331 you have defined interactively (not things you loaded or defined
347 in your configuration files). %who just prints a list of
332 in your configuration files). %who just prints a list of
348 identifiers and %whos prints a table with some basic details about
333 identifiers and %whos prints a table with some basic details about
349 each identifier.
334 each identifier.
350
335
351 Note that the dynamic object information functions (?/??, ``%pdoc``,
336 Note that the dynamic object information functions (?/??, ``%pdoc``,
352 ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as
337 ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as
353 directly on variables. For example, after doing ``import os``, you can use
338 directly on variables. For example, after doing ``import os``, you can use
354 ``os.path.abspath??``.
339 ``os.path.abspath??``.
355
340
356 .. _readline:
341 .. _readline:
357
342
358 Readline-based features
343 Readline-based features
359 -----------------------
344 -----------------------
360
345
361 These features require the GNU readline library, so they won't work if your
346 These features require the GNU readline library, so they won't work if your
362 Python installation lacks readline support. We will first describe the default
347 Python installation lacks readline support. We will first describe the default
363 behavior IPython uses, and then how to change it to suit your preferences.
348 behavior IPython uses, and then how to change it to suit your preferences.
364
349
365
350
366 Command line completion
351 Command line completion
367 +++++++++++++++++++++++
352 +++++++++++++++++++++++
368
353
369 At any time, hitting TAB will complete any available python commands or
354 At any time, hitting TAB will complete any available python commands or
370 variable names, and show you a list of the possible completions if
355 variable names, and show you a list of the possible completions if
371 there's no unambiguous one. It will also complete filenames in the
356 there's no unambiguous one. It will also complete filenames in the
372 current directory if no python names match what you've typed so far.
357 current directory if no python names match what you've typed so far.
373
358
374
359
375 Search command history
360 Search command history
376 ++++++++++++++++++++++
361 ++++++++++++++++++++++
377
362
378 IPython provides two ways for searching through previous input and thus
363 IPython provides two ways for searching through previous input and thus
379 reduce the need for repetitive typing:
364 reduce the need for repetitive typing:
380
365
381 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
366 1. Start typing, and then use the up and down arrow keys (or :kbd:`Ctrl-p`
382 (next,down) to search through only the history items that match
367 and :kbd:`Ctrl-n`) to search through only the history items that match
383 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
368 what you've typed so far.
384 prompt, they just behave like normal arrow keys.
369 2. Hit :kbd:`Ctrl-r`: opens a search prompt. Begin typing and the system
385 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
386 searches your history for lines that contain what you've typed so
370 searches your history for lines that contain what you've typed so
387 far, completing as much as it can.
371 far, completing as much as it can.
388
372
389
390 Persistent command history across sessions
391 ++++++++++++++++++++++++++++++++++++++++++
392
393 IPython will save your input history when it leaves and reload it next
373 IPython will save your input history when it leaves and reload it next
394 time you restart it. By default, the history file is named
374 time you restart it. By default, the history file is named
395 $IPYTHONDIR/profile_<name>/history.sqlite. This allows you to keep
375 :file:`.ipython/profile_{name}/history.sqlite`.
396 separate histories related to various tasks: commands related to
397 numerical work will not be clobbered by a system shell history, for
398 example.
399
400
376
401 Autoindent
377 Autoindent
402 ++++++++++
378 ++++++++++
403
379
404 IPython can recognize lines ending in ':' and indent the next line,
380 IPython can recognize lines ending in ':' and indent the next line,
405 while also un-indenting automatically after 'raise' or 'return'.
381 while also un-indenting automatically after 'raise' or 'return'.
406
382
407 This feature uses the readline library, so it will honor your
383 This feature uses the readline library, so it will honor your
408 :file:`~/.inputrc` configuration (or whatever file your INPUTRC variable points
384 :file:`~/.inputrc` configuration (or whatever file your :envvar:`INPUTRC` environment variable points
409 to). Adding the following lines to your :file:`.inputrc` file can make
385 to). Adding the following lines to your :file:`.inputrc` file can make
410 indenting/unindenting more convenient (M-i indents, M-u unindents)::
386 indenting/unindenting more convenient (M-i indents, M-u unindents)::
411
387
412 # if you don't already have a ~/.inputrc file, you need this include:
388 # if you don't already have a ~/.inputrc file, you need this include:
413 $include /etc/inputrc
389 $include /etc/inputrc
414
390
415 $if Python
391 $if Python
416 "\M-i": " "
392 "\M-i": " "
417 "\M-u": "\d\d\d\d"
393 "\M-u": "\d\d\d\d"
418 $endif
394 $endif
419
395
420 Note that there are 4 spaces between the quote marks after "M-i" above.
396 Note that there are 4 spaces between the quote marks after "M-i" above.
421
397
422 .. warning::
398 .. warning::
423
399
424 Setting the above indents will cause problems with unicode text entry in
400 Setting the above indents will cause problems with unicode text entry in
425 the terminal.
401 the terminal.
426
402
427 .. warning::
403 .. warning::
428
404
429 Autoindent is ON by default, but it can cause problems with the pasting of
405 Autoindent is ON by default, but it can cause problems with the pasting of
430 multi-line indented code (the pasted code gets re-indented on each line). A
406 multi-line indented code (the pasted code gets re-indented on each line). A
431 magic function %autoindent allows you to toggle it on/off at runtime. You
407 magic function %autoindent allows you to toggle it on/off at runtime. You
432 can also disable it permanently on in your :file:`ipython_config.py` file
408 can also disable it permanently on in your :file:`ipython_config.py` file
433 (set TerminalInteractiveShell.autoindent=False).
409 (set TerminalInteractiveShell.autoindent=False).
434
410
435 If you want to paste multiple lines in the terminal, it is recommended that
411 If you want to paste multiple lines in the terminal, it is recommended that
436 you use ``%paste``.
412 you use ``%paste``.
437
413
438
414
439 Customizing readline behavior
415 Customizing readline behavior
440 +++++++++++++++++++++++++++++
416 +++++++++++++++++++++++++++++
441
417
442 All these features are based on the GNU readline library, which has an
418 All these features are based on the GNU readline library, which has an
443 extremely customizable interface. Normally, readline is configured via a
419 extremely customizable interface. Normally, readline is configured via a
444 file which defines the behavior of the library; the details of the
420 :file:`.inputrc` file. IPython respects this, and you can also customise readline
445 syntax for this can be found in the readline documentation available
421 by setting the following :doc:`configuration </config/intro>` options:
446 with your system or on the Internet. IPython doesn't read this file (if
422
447 it exists) directly, but it does support passing to readline valid
423 * ``InteractiveShell.readline_parse_and_bind``: this holds a list of strings to be executed
448 options via a simple interface. In brief, you can customize readline by
449 setting the following options in your configuration file (note
450 that these options can not be specified at the command line):
451
452 * **readline_parse_and_bind**: this holds a list of strings to be executed
453 via a readline.parse_and_bind() command. The syntax for valid commands
424 via a readline.parse_and_bind() command. The syntax for valid commands
454 of this kind can be found by reading the documentation for the GNU
425 of this kind can be found by reading the documentation for the GNU
455 readline library, as these commands are of the kind which readline
426 readline library, as these commands are of the kind which readline
456 accepts in its configuration file.
427 accepts in its configuration file.
457 * **readline_remove_delims**: a string of characters to be removed
428 * ``InteractiveShell.readline_remove_delims``: a string of characters to be removed
458 from the default word-delimiters list used by readline, so that
429 from the default word-delimiters list used by readline, so that
459 completions may be performed on strings which contain them. Do not
430 completions may be performed on strings which contain them. Do not
460 change the default value unless you know what you're doing.
431 change the default value unless you know what you're doing.
461
432
462 You will find the default values in your configuration file.
433 You will find the default values in your configuration file.
463
434
464
435
465 Session logging and restoring
436 Session logging and restoring
466 -----------------------------
437 -----------------------------
467
438
468 You can log all input from a session either by starting IPython with the
439 You can log all input from a session either by starting IPython with the
469 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
440 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
470 or by activating the logging at any moment with the magic function %logstart.
441 or by activating the logging at any moment with the magic function %logstart.
471
442
472 Log files can later be reloaded by running them as scripts and IPython
443 Log files can later be reloaded by running them as scripts and IPython
473 will attempt to 'replay' the log by executing all the lines in it, thus
444 will attempt to 'replay' the log by executing all the lines in it, thus
474 restoring the state of a previous session. This feature is not quite
445 restoring the state of a previous session. This feature is not quite
475 perfect, but can still be useful in many cases.
446 perfect, but can still be useful in many cases.
476
447
477 The log files can also be used as a way to have a permanent record of
448 The log files can also be used as a way to have a permanent record of
478 any code you wrote while experimenting. Log files are regular text files
449 any code you wrote while experimenting. Log files are regular text files
479 which you can later open in your favorite text editor to extract code or
450 which you can later open in your favorite text editor to extract code or
480 to 'clean them up' before using them to replay a session.
451 to 'clean them up' before using them to replay a session.
481
452
482 The `%logstart` function for activating logging in mid-session is used as
453 The `%logstart` function for activating logging in mid-session is used as
483 follows::
454 follows::
484
455
485 %logstart [log_name [log_mode]]
456 %logstart [log_name [log_mode]]
486
457
487 If no name is given, it defaults to a file named 'ipython_log.py' in your
458 If no name is given, it defaults to a file named 'ipython_log.py' in your
488 current working directory, in 'rotate' mode (see below).
459 current working directory, in 'rotate' mode (see below).
489
460
490 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
461 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
491 history up to that point and then continues logging.
462 history up to that point and then continues logging.
492
463
493 %logstart takes a second optional parameter: logging mode. This can be
464 %logstart takes a second optional parameter: logging mode. This can be
494 one of (note that the modes are given unquoted):
465 one of (note that the modes are given unquoted):
495
466
496 * [over:] overwrite existing log_name.
467 * [over:] overwrite existing log_name.
497 * [backup:] rename (if exists) to log_name~ and start log_name.
468 * [backup:] rename (if exists) to log_name~ and start log_name.
498 * [append:] well, that says it.
469 * [append:] well, that says it.
499 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
470 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
500
471
501 The %logoff and %logon functions allow you to temporarily stop and
472 The %logoff and %logon functions allow you to temporarily stop and
502 resume logging to a file which had previously been started with
473 resume logging to a file which had previously been started with
503 %logstart. They will fail (with an explanation) if you try to use them
474 %logstart. They will fail (with an explanation) if you try to use them
504 before logging has been started.
475 before logging has been started.
505
476
506 .. _system_shell_access:
477 .. _system_shell_access:
507
478
508 System shell access
479 System shell access
509 -------------------
480 -------------------
510
481
511 Any input line beginning with a ! character is passed verbatim (minus
482 Any input line beginning with a ! character is passed verbatim (minus
512 the !, of course) to the underlying operating system. For example,
483 the !, of course) to the underlying operating system. For example,
513 typing ``!ls`` will run 'ls' in the current directory.
484 typing ``!ls`` will run 'ls' in the current directory.
514
485
515 Manual capture of command output
486 Manual capture of command output
516 --------------------------------
487 --------------------------------
517
488
518 You can assign the result of a system command to a Python variable with the
489 You can assign the result of a system command to a Python variable with the
519 syntax ``myfiles = !ls``. This gets machine readable output from stdout
490 syntax ``myfiles = !ls``. This gets machine readable output from stdout
520 (e.g. without colours), and splits on newlines. To explicitly get this sort of
491 (e.g. without colours), and splits on newlines. To explicitly get this sort of
521 output without assigning to a variable, use two exclamation marks (``!!ls``) or
492 output without assigning to a variable, use two exclamation marks (``!!ls``) or
522 the ``%sx`` magic command.
493 the ``%sx`` magic command.
523
494
524 The captured list has some convenience features. ``myfiles.n`` or ``myfiles.s``
495 The captured list has some convenience features. ``myfiles.n`` or ``myfiles.s``
525 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
496 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
526 produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items.
497 produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items.
527 See :ref:`string_lists` for details.
498 See :ref:`string_lists` for details.
528
499
529 IPython also allows you to expand the value of python variables when
500 IPython also allows you to expand the value of python variables when
530 making system calls. Wrap variables or expressions in {braces}::
501 making system calls. Wrap variables or expressions in {braces}::
531
502
532 In [1]: pyvar = 'Hello world'
503 In [1]: pyvar = 'Hello world'
533 In [2]: !echo "A python variable: {pyvar}"
504 In [2]: !echo "A python variable: {pyvar}"
534 A python variable: Hello world
505 A python variable: Hello world
535 In [3]: import math
506 In [3]: import math
536 In [4]: x = 8
507 In [4]: x = 8
537 In [5]: !echo {math.factorial(x)}
508 In [5]: !echo {math.factorial(x)}
538 40320
509 40320
539
510
540 For simple cases, you can alternatively prepend $ to a variable name::
511 For simple cases, you can alternatively prepend $ to a variable name::
541
512
542 In [6]: !echo $sys.argv
513 In [6]: !echo $sys.argv
543 [/home/fperez/usr/bin/ipython]
514 [/home/fperez/usr/bin/ipython]
544 In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $
515 In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $
545 A system variable: /home/fperez
516 A system variable: /home/fperez
546
517
547 System command aliases
518 System command aliases
548 ----------------------
519 ----------------------
549
520
550 The %alias magic function allows you to define magic functions which are in fact
521 The %alias magic function allows you to define magic functions which are in fact
551 system shell commands. These aliases can have parameters.
522 system shell commands. These aliases can have parameters.
552
523
553 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
524 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
554
525
555 Then, typing ``alias_name params`` will execute the system command 'cmd
526 Then, typing ``alias_name params`` will execute the system command 'cmd
556 params' (from your underlying operating system).
527 params' (from your underlying operating system).
557
528
558 You can also define aliases with parameters using %s specifiers (one per
529 You can also define aliases with parameters using %s specifiers (one per
559 parameter). The following example defines the parts function as an
530 parameter). The following example defines the parts function as an
560 alias to the command 'echo first %s second %s' where each %s will be
531 alias to the command 'echo first %s second %s' where each %s will be
561 replaced by a positional parameter to the call to %parts::
532 replaced by a positional parameter to the call to %parts::
562
533
563 In [1]: %alias parts echo first %s second %s
534 In [1]: %alias parts echo first %s second %s
564 In [2]: parts A B
535 In [2]: parts A B
565 first A second B
536 first A second B
566 In [3]: parts A
537 In [3]: parts A
567 ERROR: Alias <parts> requires 2 arguments, 1 given.
538 ERROR: Alias <parts> requires 2 arguments, 1 given.
568
539
569 If called with no parameters, %alias prints the table of currently
540 If called with no parameters, %alias prints the table of currently
570 defined aliases.
541 defined aliases.
571
542
572 The %rehashx magic allows you to load your entire $PATH as
543 The %rehashx magic allows you to load your entire $PATH as
573 ipython aliases. See its docstring for further details.
544 ipython aliases. See its docstring for further details.
574
545
575
546
576 .. _dreload:
547 .. _dreload:
577
548
578 Recursive reload
549 Recursive reload
579 ----------------
550 ----------------
580
551
581 The :mod:`IPython.lib.deepreload` module allows you to recursively reload a
552 The :mod:`IPython.lib.deepreload` module allows you to recursively reload a
582 module: changes made to any of its dependencies will be reloaded without
553 module: changes made to any of its dependencies will be reloaded without
583 having to exit. To start using it, do::
554 having to exit. To start using it, do::
584
555
585 from IPython.lib.deepreload import reload as dreload
556 from IPython.lib.deepreload import reload as dreload
586
557
587
558
588 Verbose and colored exception traceback printouts
559 Verbose and colored exception traceback printouts
589 -------------------------------------------------
560 -------------------------------------------------
590
561
591 IPython provides the option to see very detailed exception tracebacks,
562 IPython provides the option to see very detailed exception tracebacks,
592 which can be especially useful when debugging large programs. You can
563 which can be especially useful when debugging large programs. You can
593 run any Python file with the %run function to benefit from these
564 run any Python file with the %run function to benefit from these
594 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
565 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
595 be colored (if your terminal supports it) which makes them much easier
566 be colored (if your terminal supports it) which makes them much easier
596 to parse visually.
567 to parse visually.
597
568
598 See the magic xmode and colors functions for details (just type %magic).
569 See the magic xmode and colors functions for details.
599
570
600 These features are basically a terminal version of Ka-Ping Yee's cgitb
571 These features are basically a terminal version of Ka-Ping Yee's cgitb
601 module, now part of the standard Python library.
572 module, now part of the standard Python library.
602
573
603
574
604 .. _input_caching:
575 .. _input_caching:
605
576
606 Input caching system
577 Input caching system
607 --------------------
578 --------------------
608
579
609 IPython offers numbered prompts (In/Out) with input and output caching
580 IPython offers numbered prompts (In/Out) with input and output caching
610 (also referred to as 'input history'). All input is saved and can be
581 (also referred to as 'input history'). All input is saved and can be
611 retrieved as variables (besides the usual arrow key recall), in
582 retrieved as variables (besides the usual arrow key recall), in
612 addition to the %rep magic command that brings a history entry
583 addition to the %rep magic command that brings a history entry
613 up for editing on the next command line.
584 up for editing on the next command line.
614
585
615 The following GLOBAL variables always exist (so don't overwrite them!):
586 The following variables always exist:
616
587
617 * _i, _ii, _iii: store previous, next previous and next-next previous inputs.
588 * _i, _ii, _iii: store previous, next previous and next-next previous inputs.
618 * In, _ih : a list of all inputs; _ih[n] is the input from line n. If you
589 * In, _ih : a list of all inputs; _ih[n] is the input from line n. If you
619 overwrite In with a variable of your own, you can remake the assignment to the
590 overwrite In with a variable of your own, you can remake the assignment to the
620 internal list with a simple ``In=_ih``.
591 internal list with a simple ``In=_ih``.
621
592
622 Additionally, global variables named _i<n> are dynamically created (<n>
593 Additionally, global variables named _i<n> are dynamically created (<n>
623 being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``.
594 being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``.
624
595
625 For example, what you typed at prompt 14 is available as _i14, _ih[14]
596 For example, what you typed at prompt 14 is available as ``_i14``, ``_ih[14]``
626 and In[14].
597 and ``In[14]``.
627
598
628 This allows you to easily cut and paste multi line interactive prompts
599 This allows you to easily cut and paste multi line interactive prompts
629 by printing them out: they print like a clean string, without prompt
600 by printing them out: they print like a clean string, without prompt
630 characters. You can also manipulate them like regular variables (they
601 characters. You can also manipulate them like regular variables (they
631 are strings), modify or exec them (typing ``exec _i9`` will re-execute the
602 are strings), modify or exec them.
632 contents of input prompt 9.
633
603
634 You can also re-execute multiple lines of input easily by using the
604 You can also re-execute multiple lines of input easily by using the
635 magic %rerun or %macro functions. The macro system also allows you to re-execute
605 magic %rerun or %macro functions. The macro system also allows you to re-execute
636 previous lines which include magic function calls (which require special
606 previous lines which include magic function calls (which require special
637 processing). Type %macro? for more details on the macro system.
607 processing). Type %macro? for more details on the macro system.
638
608
639 A history function %hist allows you to see any part of your input
609 A history function %hist allows you to see any part of your input
640 history by printing a range of the _i variables.
610 history by printing a range of the _i variables.
641
611
642 You can also search ('grep') through your history by typing
612 You can also search ('grep') through your history by typing
643 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
613 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
644 etc. You can bring history entries listed by '%hist -g' up for editing
614 etc. You can bring history entries listed by '%hist -g' up for editing
645 with the %recall command, or run them immediately with %rerun.
615 with the %recall command, or run them immediately with %rerun.
646
616
647 .. _output_caching:
617 .. _output_caching:
648
618
649 Output caching system
619 Output caching system
650 ---------------------
620 ---------------------
651
621
652 For output that is returned from actions, a system similar to the input
622 For output that is returned from actions, a system similar to the input
653 cache exists but using _ instead of _i. Only actions that produce a
623 cache exists but using _ instead of _i. Only actions that produce a
654 result (NOT assignments, for example) are cached. If you are familiar
624 result (NOT assignments, for example) are cached. If you are familiar
655 with Mathematica, IPython's _ variables behave exactly like
625 with Mathematica, IPython's _ variables behave exactly like
656 Mathematica's % variables.
626 Mathematica's % variables.
657
627
658 The following GLOBAL variables always exist (so don't overwrite them!):
628 The following variables always exist:
659
629
660 * [_] (a single underscore) : stores previous output, like Python's
630 * [_] (a single underscore): stores previous output, like Python's
661 default interpreter.
631 default interpreter.
662 * [__] (two underscores): next previous.
632 * [__] (two underscores): next previous.
663 * [___] (three underscores): next-next previous.
633 * [___] (three underscores): next-next previous.
664
634
665 Additionally, global variables named _<n> are dynamically created (<n>
635 Additionally, global variables named _<n> are dynamically created (<n>
666 being the prompt counter), such that the result of output <n> is always
636 being the prompt counter), such that the result of output <n> is always
667 available as _<n> (don't use the angle brackets, just the number, e.g.
637 available as _<n> (don't use the angle brackets, just the number, e.g.
668 _21).
638 ``_21``).
669
639
670 These variables are also stored in a global dictionary (not a
640 These variables are also stored in a global dictionary (not a
671 list, since it only has entries for lines which returned a result)
641 list, since it only has entries for lines which returned a result)
672 available under the names _oh and Out (similar to _ih and In). So the
642 available under the names _oh and Out (similar to _ih and In). So the
673 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
643 output from line 12 can be obtained as ``_12``, ``Out[12]`` or ``_oh[12]``. If you
674 accidentally overwrite the Out variable you can recover it by typing
644 accidentally overwrite the Out variable you can recover it by typing
675 'Out=_oh' at the prompt.
645 ``Out=_oh`` at the prompt.
676
646
677 This system obviously can potentially put heavy memory demands on your
647 This system obviously can potentially put heavy memory demands on your
678 system, since it prevents Python's garbage collector from removing any
648 system, since it prevents Python's garbage collector from removing any
679 previously computed results. You can control how many results are kept
649 previously computed results. You can control how many results are kept
680 in memory with the option (at the command line or in your configuration
650 in memory with the configuration option ``InteractiveShell.cache_size``.
681 file) cache_size. If you set it to 0, the whole system is completely
651 If you set it to 0, output caching is disabled. You can also use the ``%reset``
682 disabled and the prompts revert to the classic '>>>' of normal Python.
652 and ``%xdel`` magics to clear large items from memory.
683
684
653
685 Directory history
654 Directory history
686 -----------------
655 -----------------
687
656
688 Your history of visited directories is kept in the global list _dh, and
657 Your history of visited directories is kept in the global list _dh, and
689 the magic %cd command can be used to go to any entry in that list. The
658 the magic %cd command can be used to go to any entry in that list. The
690 %dhist command allows you to view this history. Do ``cd -<TAB>`` to
659 %dhist command allows you to view this history. Do ``cd -<TAB>`` to
691 conveniently view the directory history.
660 conveniently view the directory history.
692
661
693
662
694 Automatic parentheses and quotes
663 Automatic parentheses and quotes
695 --------------------------------
664 --------------------------------
696
665
697 These features were adapted from Nathan Gray's LazyPython. They are
666 These features were adapted from Nathan Gray's LazyPython. They are
698 meant to allow less typing for common situations.
667 meant to allow less typing for common situations.
699
668
700
701 Automatic parentheses
702 +++++++++++++++++++++
703
704 Callable objects (i.e. functions, methods, etc) can be invoked like this
669 Callable objects (i.e. functions, methods, etc) can be invoked like this
705 (notice the commas between the arguments)::
670 (notice the commas between the arguments)::
706
671
707 In [1]: callable_ob arg1, arg2, arg3
672 In [1]: callable_ob arg1, arg2, arg3
708 ------> callable_ob(arg1, arg2, arg3)
673 ------> callable_ob(arg1, arg2, arg3)
709
674
675 .. note::
676 This feature is disabled by default. To enable it, use the ``%autocall``
677 magic command. The commands below with special prefixes will always work,
678 however.
679
710 You can force automatic parentheses by using '/' as the first character
680 You can force automatic parentheses by using '/' as the first character
711 of a line. For example::
681 of a line. For example::
712
682
713 In [2]: /globals # becomes 'globals()'
683 In [2]: /globals # becomes 'globals()'
714
684
715 Note that the '/' MUST be the first character on the line! This won't work::
685 Note that the '/' MUST be the first character on the line! This won't work::
716
686
717 In [3]: print /globals # syntax error
687 In [3]: print /globals # syntax error
718
688
719 In most cases the automatic algorithm should work, so you should rarely
689 In most cases the automatic algorithm should work, so you should rarely
720 need to explicitly invoke /. One notable exception is if you are trying
690 need to explicitly invoke /. One notable exception is if you are trying
721 to call a function with a list of tuples as arguments (the parenthesis
691 to call a function with a list of tuples as arguments (the parenthesis
722 will confuse IPython)::
692 will confuse IPython)::
723
693
724 In [4]: zip (1,2,3),(4,5,6) # won't work
694 In [4]: zip (1,2,3),(4,5,6) # won't work
725
695
726 but this will work::
696 but this will work::
727
697
728 In [5]: /zip (1,2,3),(4,5,6)
698 In [5]: /zip (1,2,3),(4,5,6)
729 ------> zip ((1,2,3),(4,5,6))
699 ------> zip ((1,2,3),(4,5,6))
730 Out[5]: [(1, 4), (2, 5), (3, 6)]
700 Out[5]: [(1, 4), (2, 5), (3, 6)]
731
701
732 IPython tells you that it has altered your command line by displaying
702 IPython tells you that it has altered your command line by displaying
733 the new command line preceded by ->. e.g.::
703 the new command line preceded by ``--->``.
734
735 In [6]: callable list
736 ------> callable(list)
737
704
738
705 You can force automatic quoting of a function's arguments by using ``,``
739 Automatic quoting
706 or ``;`` as the first character of a line. For example::
740 +++++++++++++++++
741
742 You can force automatic quoting of a function's arguments by using ','
743 or ';' as the first character of a line. For example::
744
707
745 In [1]: ,my_function /home/me # becomes my_function("/home/me")
708 In [1]: ,my_function /home/me # becomes my_function("/home/me")
746
709
747 If you use ';' the whole argument is quoted as a single string, while ',' splits
710 If you use ';' the whole argument is quoted as a single string, while ',' splits
748 on whitespace::
711 on whitespace::
749
712
750 In [2]: ,my_function a b c # becomes my_function("a","b","c")
713 In [2]: ,my_function a b c # becomes my_function("a","b","c")
751
714
752 In [3]: ;my_function a b c # becomes my_function("a b c")
715 In [3]: ;my_function a b c # becomes my_function("a b c")
753
716
754 Note that the ',' or ';' MUST be the first character on the line! This
717 Note that the ',' or ';' MUST be the first character on the line! This
755 won't work::
718 won't work::
756
719
757 In [4]: x = ,my_function /home/me # syntax error
720 In [4]: x = ,my_function /home/me # syntax error
758
721
759 IPython as your default Python environment
722 IPython as your default Python environment
760 ==========================================
723 ==========================================
761
724
762 Python honors the environment variable :envvar:`PYTHONSTARTUP` and will
725 Python honors the environment variable :envvar:`PYTHONSTARTUP` and will
763 execute at startup the file referenced by this variable. If you put the
726 execute at startup the file referenced by this variable. If you put the
764 following code at the end of that file, then IPython will be your working
727 following code at the end of that file, then IPython will be your working
765 environment anytime you start Python::
728 environment anytime you start Python::
766
729
767 import os, IPython
730 import os, IPython
768 os.environ['PYTHONSTARTUP'] = '' # Prevent running this again
731 os.environ['PYTHONSTARTUP'] = '' # Prevent running this again
769 IPython.start_ipython()
732 IPython.start_ipython()
770 raise SystemExit
733 raise SystemExit
771
734
772 The ``raise SystemExit`` is needed to exit Python when
735 The ``raise SystemExit`` is needed to exit Python when
773 it finishes, otherwise you'll be back at the normal Python '>>>'
736 it finishes, otherwise you'll be back at the normal Python ``>>>``
774 prompt.
737 prompt.
775
738
776 This is probably useful to developers who manage multiple Python
739 This is probably useful to developers who manage multiple Python
777 versions and don't want to have correspondingly multiple IPython
740 versions and don't want to have correspondingly multiple IPython
778 versions. Note that in this mode, there is no way to pass IPython any
741 versions. Note that in this mode, there is no way to pass IPython any
779 command-line options, as those are trapped first by Python itself.
742 command-line options, as those are trapped first by Python itself.
780
743
781 .. _Embedding:
744 .. _Embedding:
782
745
783 Embedding IPython
746 Embedding IPython
784 =================
747 =================
785
748
786 You can start a regular IPython session with
749 You can start a regular IPython session with
787
750
788 .. sourcecode:: python
751 .. sourcecode:: python
789
752
790 import IPython
753 import IPython
791 IPython.start_ipython()
754 IPython.start_ipython(argv=[])
792
755
793 at any point in your program. This will load IPython configuration,
756 at any point in your program. This will load IPython configuration,
794 startup files, and everything, just as if it were a normal IPython session.
757 startup files, and everything, just as if it were a normal IPython session.
795 In addition to this,
758
796 it is possible to embed an IPython instance inside your own Python programs.
759 It is also possible to embed an IPython shell in a namespace in your Python code.
797 This allows you to evaluate dynamically the state of your code,
760 This allows you to evaluate dynamically the state of your code,
798 operate with your variables, analyze them, etc. Note however that
761 operate with your variables, analyze them, etc. Note however that
799 any changes you make to values while in the shell do not propagate back
762 any changes you make to values while in the shell do not propagate back
800 to the running code, so it is safe to modify your values because you
763 to the running code, so it is safe to modify your values because you
801 won't break your code in bizarre ways by doing so.
764 won't break your code in bizarre ways by doing so.
802
765
803 .. note::
766 .. note::
804
767
805 At present, embedding IPython cannot be done from inside IPython.
768 At present, embedding IPython cannot be done from inside IPython.
806 Run the code samples below outside IPython.
769 Run the code samples below outside IPython.
807
770
808 This feature allows you to easily have a fully functional python
771 This feature allows you to easily have a fully functional python
809 environment for doing object introspection anywhere in your code with a
772 environment for doing object introspection anywhere in your code with a
810 simple function call. In some cases a simple print statement is enough,
773 simple function call. In some cases a simple print statement is enough,
811 but if you need to do more detailed analysis of a code fragment this
774 but if you need to do more detailed analysis of a code fragment this
812 feature can be very valuable.
775 feature can be very valuable.
813
776
814 It can also be useful in scientific computing situations where it is
777 It can also be useful in scientific computing situations where it is
815 common to need to do some automatic, computationally intensive part and
778 common to need to do some automatic, computationally intensive part and
816 then stop to look at data, plots, etc.
779 then stop to look at data, plots, etc.
817 Opening an IPython instance will give you full access to your data and
780 Opening an IPython instance will give you full access to your data and
818 functions, and you can resume program execution once you are done with
781 functions, and you can resume program execution once you are done with
819 the interactive part (perhaps to stop again later, as many times as
782 the interactive part (perhaps to stop again later, as many times as
820 needed).
783 needed).
821
784
822 The following code snippet is the bare minimum you need to include in
785 The following code snippet is the bare minimum you need to include in
823 your Python programs for this to work (detailed examples follow later)::
786 your Python programs for this to work (detailed examples follow later)::
824
787
825 from IPython import embed
788 from IPython import embed
826
789
827 embed() # this call anywhere in your program will start IPython
790 embed() # this call anywhere in your program will start IPython
828
791
829 .. note::
792 You can also embed an IPython *kernel*, for use with qtconsole, etc. via
830
793 ``IPython.embed_kernel()``. This should function work the same way, but you can
831 As of 0.13, you can embed an IPython *kernel*, for use with qtconsole,
794 connect an external frontend (``ipython qtconsole`` or ``ipython console``),
832 etc. via ``IPython.embed_kernel()`` instead of ``IPython.embed()``.
795 rather than interacting with it in the terminal.
833 It should function just the same as regular embed, but you connect
834 an external frontend rather than IPython starting up in the local
835 terminal.
836
796
837 You can run embedded instances even in code which is itself being run at
797 You can run embedded instances even in code which is itself being run at
838 the IPython interactive prompt with '%run <filename>'. Since it's easy
798 the IPython interactive prompt with '%run <filename>'. Since it's easy
839 to get lost as to where you are (in your top-level IPython or in your
799 to get lost as to where you are (in your top-level IPython or in your
840 embedded one), it's a good idea in such cases to set the in/out prompts
800 embedded one), it's a good idea in such cases to set the in/out prompts
841 to something different for the embedded instances. The code examples
801 to something different for the embedded instances. The code examples
842 below illustrate this.
802 below illustrate this.
843
803
844 You can also have multiple IPython instances in your program and open
804 You can also have multiple IPython instances in your program and open
845 them separately, for example with different options for data
805 them separately, for example with different options for data
846 presentation. If you close and open the same instance multiple times,
806 presentation. If you close and open the same instance multiple times,
847 its prompt counters simply continue from each execution to the next.
807 its prompt counters simply continue from each execution to the next.
848
808
849 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
809 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
850 module for more details on the use of this system.
810 module for more details on the use of this system.
851
811
852 The following sample file illustrating how to use the embedding
812 The following sample file illustrating how to use the embedding
853 functionality is provided in the examples directory as example-embed.py.
813 functionality is provided in the examples directory as example-embed.py.
854 It should be fairly self-explanatory:
814 It should be fairly self-explanatory:
855
815
856 .. literalinclude:: ../../../examples/core/example-embed.py
816 .. literalinclude:: ../../../examples/core/example-embed.py
857 :language: python
817 :language: python
858
818
859 Once you understand how the system functions, you can use the following
819 Once you understand how the system functions, you can use the following
860 code fragments in your programs which are ready for cut and paste:
820 code fragments in your programs which are ready for cut and paste:
861
821
862 .. literalinclude:: ../../../examples/core/example-embed-short.py
822 .. literalinclude:: ../../../examples/core/example-embed-short.py
863 :language: python
823 :language: python
864
824
865 Using the Python debugger (pdb)
825 Using the Python debugger (pdb)
866 ===============================
826 ===============================
867
827
868 Running entire programs via pdb
828 Running entire programs via pdb
869 -------------------------------
829 -------------------------------
870
830
871 pdb, the Python debugger, is a powerful interactive debugger which
831 pdb, the Python debugger, is a powerful interactive debugger which
872 allows you to step through code, set breakpoints, watch variables,
832 allows you to step through code, set breakpoints, watch variables,
873 etc. IPython makes it very easy to start any script under the control
833 etc. IPython makes it very easy to start any script under the control
874 of pdb, regardless of whether you have wrapped it into a 'main()'
834 of pdb, regardless of whether you have wrapped it into a 'main()'
875 function or not. For this, simply type '%run -d myscript' at an
835 function or not. For this, simply type ``%run -d myscript`` at an
876 IPython prompt. See the %run command's documentation (via '%run?' or
836 IPython prompt. See the %run command's documentation for more details, including
877 in Sec. magic_ for more details, including how to control where pdb
837 how to control where pdb will stop execution first.
878 will stop execution first.
879
880 For more information on the use of the pdb debugger, read the included
881 pdb.doc file (part of the standard Python distribution). On a stock
882 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
883 easiest way to read it is by using the help() function of the pdb module
884 as follows (in an IPython prompt)::
885
838
886 In [1]: import pdb
839 For more information on the use of the pdb debugger, see :ref:`debugger-commands`
887 In [2]: pdb.help()
840 in the Python documentation.
888
841
889 This will load the pdb.doc document in a file viewer for you automatically.
890
842
843 Post-mortem debugging
844 ---------------------
891
845
892 Automatic invocation of pdb on exceptions
846 Going into a debugger when an exception occurs can be
893 -----------------------------------------
894
895 IPython, if started with the ``--pdb`` option (or if the option is set in
896 your config file) can call the Python pdb debugger every time your code
897 triggers an uncaught exception. This feature
898 can also be toggled at any time with the %pdb magic command. This can be
899 extremely useful in order to find the origin of subtle bugs, because pdb
847 extremely useful in order to find the origin of subtle bugs, because pdb
900 opens up at the point in your code which triggered the exception, and
848 opens up at the point in your code which triggered the exception, and
901 while your program is at this point 'dead', all the data is still
849 while your program is at this point 'dead', all the data is still
902 available and you can walk up and down the stack frame and understand
850 available and you can walk up and down the stack frame and understand
903 the origin of the problem.
851 the origin of the problem.
904
852
905 Furthermore, you can use these debugging facilities both with the
853 You can use the ``%debug`` magic after an exception has occurred to start
906 embedded IPython mode and without IPython at all. For an embedded shell
854 post-mortem debugging. IPython can also call debugger every time your code
907 (see sec. Embedding_), simply call the constructor with
855 triggers an uncaught exception. This feature can be toggled with the %pdb magic
908 ``--pdb`` in the argument string and pdb will automatically be called if an
856 command, or you can start IPython with the ``--pdb`` option.
909 uncaught exception is triggered by your code.
910
857
911 For stand-alone use of the feature in your programs which do not use
858 For a post-mortem debugger in your programs outside IPython,
912 IPython at all, put the following lines toward the top of your 'main'
859 put the following lines toward the top of your 'main' routine::
913 routine::
914
860
915 import sys
861 import sys
916 from IPython.core import ultratb
862 from IPython.core import ultratb
917 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
863 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
918 color_scheme='Linux', call_pdb=1)
864 color_scheme='Linux', call_pdb=1)
919
865
920 The mode keyword can be either 'Verbose' or 'Plain', giving either very
866 The mode keyword can be either 'Verbose' or 'Plain', giving either very
921 detailed or normal tracebacks respectively. The color_scheme keyword can
867 detailed or normal tracebacks respectively. The color_scheme keyword can
922 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
868 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
923 options which can be set in IPython with ``--colors`` and ``--xmode``.
869 options which can be set in IPython with ``--colors`` and ``--xmode``.
924
870
925 This will give any of your programs detailed, colored tracebacks with
871 This will give any of your programs detailed, colored tracebacks with
926 automatic invocation of pdb.
872 automatic invocation of pdb.
927
873
928
929 Extensions for syntax processing
930 ================================
931
932 This isn't for the faint of heart, because the potential for breaking
933 things is quite high. But it can be a very powerful and useful feature.
934 In a nutshell, you can redefine the way IPython processes the user input
935 line to accept new, special extensions to the syntax without needing to
936 change any of IPython's own code.
937
938 In the IPython/extensions directory you will find some examples
939 supplied, which we will briefly describe now. These can be used 'as is'
940 (and both provide very useful functionality), or you can use them as a
941 starting point for writing your own extensions.
942
943 .. _pasting_with_prompts:
874 .. _pasting_with_prompts:
944
875
945 Pasting of code starting with Python or IPython prompts
876 Pasting of code starting with Python or IPython prompts
946 -------------------------------------------------------
877 =======================================================
947
878
948 IPython is smart enough to filter out input prompts, be they plain Python ones
879 IPython is smart enough to filter out input prompts, be they plain Python ones
949 (``>>>`` and ``...``) or IPython ones (``In [N]:`` and ``...:``). You can
880 (``>>>`` and ``...``) or IPython ones (``In [N]:`` and ``...:``). You can
950 therefore copy and paste from existing interactive sessions without worry.
881 therefore copy and paste from existing interactive sessions without worry.
951
882
952 The following is a 'screenshot' of how things work, copying an example from the
883 The following is a 'screenshot' of how things work, copying an example from the
953 standard Python tutorial::
884 standard Python tutorial::
954
885
955 In [1]: >>> # Fibonacci series:
886 In [1]: >>> # Fibonacci series:
956
887
957 In [2]: ... # the sum of two elements defines the next
888 In [2]: ... # the sum of two elements defines the next
958
889
959 In [3]: ... a, b = 0, 1
890 In [3]: ... a, b = 0, 1
960
891
961 In [4]: >>> while b < 10:
892 In [4]: >>> while b < 10:
962 ...: ... print(b)
893 ...: ... print(b)
963 ...: ... a, b = b, a+b
894 ...: ... a, b = b, a+b
964 ...:
895 ...:
965 1
896 1
966 1
897 1
967 2
898 2
968 3
899 3
969 5
900 5
970 8
901 8
971
902
972 And pasting from IPython sessions works equally well::
903 And pasting from IPython sessions works equally well::
973
904
974 In [1]: In [5]: def f(x):
905 In [1]: In [5]: def f(x):
975 ...: ...: "A simple function"
906 ...: ...: "A simple function"
976 ...: ...: return x**2
907 ...: ...: return x**2
977 ...: ...:
908 ...: ...:
978
909
979 In [2]: f(3)
910 In [2]: f(3)
980 Out[2]: 9
911 Out[2]: 9
981
912
982 .. _gui_support:
913 .. _gui_support:
983
914
984 GUI event loop support
915 GUI event loop support
985 ======================
916 ======================
986
917
987 .. versionadded:: 0.11
918 .. versionadded:: 0.11
988 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
919 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
989
920
990 IPython has excellent support for working interactively with Graphical User
921 IPython has excellent support for working interactively with Graphical User
991 Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is
922 Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is
992 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
923 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
993 is extremely robust compared to our previous thread-based version. The
924 is extremely robust compared to our previous thread-based version. The
994 advantages of this are:
925 advantages of this are:
995
926
996 * GUIs can be enabled and disabled dynamically at runtime.
927 * GUIs can be enabled and disabled dynamically at runtime.
997 * The active GUI can be switched dynamically at runtime.
928 * The active GUI can be switched dynamically at runtime.
998 * In some cases, multiple GUIs can run simultaneously with no problems.
929 * In some cases, multiple GUIs can run simultaneously with no problems.
999 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
930 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
1000 all of these things.
931 all of these things.
1001
932
1002 For users, enabling GUI event loop integration is simple. You simple use the
933 For users, enabling GUI event loop integration is simple. You simple use the
1003 ``%gui`` magic as follows::
934 ``%gui`` magic as follows::
1004
935
1005 %gui [GUINAME]
936 %gui [GUINAME]
1006
937
1007 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
938 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
1008 arguments are ``wx``, ``qt``, ``gtk`` and ``tk``.
939 arguments are ``wx``, ``qt``, ``gtk`` and ``tk``.
1009
940
1010 Thus, to use wxPython interactively and create a running :class:`wx.App`
941 Thus, to use wxPython interactively and create a running :class:`wx.App`
1011 object, do::
942 object, do::
1012
943
1013 %gui wx
944 %gui wx
1014
945
946 You can also start IPython with an event loop set up using the :option:`--gui`
947 flag::
948
949 $ ipython --gui=qt
950
1015 For information on IPython's matplotlib_ integration (and the ``matplotlib``
951 For information on IPython's matplotlib_ integration (and the ``matplotlib``
1016 mode) see :ref:`this section <matplotlib_support>`.
952 mode) see :ref:`this section <matplotlib_support>`.
1017
953
1018 For developers that want to use IPython's GUI event loop integration in the
954 For developers that want to use IPython's GUI event loop integration in the
1019 form of a library, these capabilities are exposed in library form in the
955 form of a library, these capabilities are exposed in library form in the
1020 :mod:`IPython.lib.inputhook` and :mod:`IPython.lib.guisupport` modules.
956 :mod:`IPython.lib.inputhook` and :mod:`IPython.lib.guisupport` modules.
1021 Interested developers should see the module docstrings for more information,
957 Interested developers should see the module docstrings for more information,
1022 but there are a few points that should be mentioned here.
958 but there are a few points that should be mentioned here.
1023
959
1024 First, the ``PyOSInputHook`` approach only works in command line settings
960 First, the ``PyOSInputHook`` approach only works in command line settings
1025 where readline is activated. The integration with various eventloops
961 where readline is activated. The integration with various eventloops
1026 is handled somewhat differently (and more simply) when using the standalone
962 is handled somewhat differently (and more simply) when using the standalone
1027 kernel, as in the qtconsole and notebook.
963 kernel, as in the qtconsole and notebook.
1028
964
1029 Second, when using the ``PyOSInputHook`` approach, a GUI application should
965 Second, when using the ``PyOSInputHook`` approach, a GUI application should
1030 *not* start its event loop. Instead all of this is handled by the
966 *not* start its event loop. Instead all of this is handled by the
1031 ``PyOSInputHook``. This means that applications that are meant to be used both
967 ``PyOSInputHook``. This means that applications that are meant to be used both
1032 in IPython and as standalone apps need to have special code to detects how the
968 in IPython and as standalone apps need to have special code to detects how the
1033 application is being run. We highly recommend using IPython's support for this.
969 application is being run. We highly recommend using IPython's support for this.
1034 Since the details vary slightly between toolkits, we point you to the various
970 Since the details vary slightly between toolkits, we point you to the various
1035 examples in our source directory :file:`examples/lib` that demonstrate
971 examples in our source directory :file:`examples/lib` that demonstrate
1036 these capabilities.
972 these capabilities.
1037
973
1038 Third, unlike previous versions of IPython, we no longer "hijack" (replace
974 Third, unlike previous versions of IPython, we no longer "hijack" (replace
1039 them with no-ops) the event loops. This is done to allow applications that
975 them with no-ops) the event loops. This is done to allow applications that
1040 actually need to run the real event loops to do so. This is often needed to
976 actually need to run the real event loops to do so. This is often needed to
1041 process pending events at critical points.
977 process pending events at critical points.
1042
978
1043 Finally, we also have a number of examples in our source directory
979 Finally, we also have a number of examples in our source directory
1044 :file:`examples/lib` that demonstrate these capabilities.
980 :file:`examples/lib` that demonstrate these capabilities.
1045
981
1046 PyQt and PySide
982 PyQt and PySide
1047 ---------------
983 ---------------
1048
984
1049 .. attempt at explanation of the complete mess that is Qt support
985 .. attempt at explanation of the complete mess that is Qt support
1050
986
1051 When you use ``--gui=qt`` or ``--matplotlib=qt``, IPython can work with either
987 When you use ``--gui=qt`` or ``--matplotlib=qt``, IPython can work with either
1052 PyQt4 or PySide. There are three options for configuration here, because
988 PyQt4 or PySide. There are three options for configuration here, because
1053 PyQt4 has two APIs for QString and QVariant - v1, which is the default on
989 PyQt4 has two APIs for QString and QVariant - v1, which is the default on
1054 Python 2, and the more natural v2, which is the only API supported by PySide.
990 Python 2, and the more natural v2, which is the only API supported by PySide.
1055 v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole
991 v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole
1056 uses v2, but you can still use any interface in your code, since the
992 uses v2, but you can still use any interface in your code, since the
1057 Qt frontend is in a different process.
993 Qt frontend is in a different process.
1058
994
1059 The default will be to import PyQt4 without configuration of the APIs, thus
995 The default will be to import PyQt4 without configuration of the APIs, thus
1060 matching what most applications would expect. It will fall back of PySide if
996 matching what most applications would expect. It will fall back of PySide if
1061 PyQt4 is unavailable.
997 PyQt4 is unavailable.
1062
998
1063 If specified, IPython will respect the environment variable ``QT_API`` used
999 If specified, IPython will respect the environment variable ``QT_API`` used
1064 by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires
1000 by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires
1065 PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used,
1001 PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used,
1066 and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for
1002 and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for
1067 QString and QVariant, so ETS codes like MayaVi will also work with IPython.
1003 QString and QVariant, so ETS codes like MayaVi will also work with IPython.
1068
1004
1069 If you launch IPython in matplotlib mode with ``ipython --matplotlib=qt``,
1005 If you launch IPython in matplotlib mode with ``ipython --matplotlib=qt``,
1070 then IPython will ask matplotlib which Qt library to use (only if QT_API is
1006 then IPython will ask matplotlib which Qt library to use (only if QT_API is
1071 *not set*), via the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or
1007 *not set*), via the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or
1072 older, then IPython will always use PyQt4 without setting the v2 APIs, since
1008 older, then IPython will always use PyQt4 without setting the v2 APIs, since
1073 neither v2 PyQt nor PySide work.
1009 neither v2 PyQt nor PySide work.
1074
1010
1075 .. warning::
1011 .. warning::
1076
1012
1077 Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set
1013 Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set
1078 to work with IPython's qt integration, because otherwise PyQt4 will be
1014 to work with IPython's qt integration, because otherwise PyQt4 will be
1079 loaded in an incompatible mode.
1015 loaded in an incompatible mode.
1080
1016
1081 It also means that you must *not* have ``QT_API`` set if you want to
1017 It also means that you must *not* have ``QT_API`` set if you want to
1082 use ``--gui=qt`` with code that requires PyQt4 API v1.
1018 use ``--gui=qt`` with code that requires PyQt4 API v1.
1083
1019
1084
1020
1085 .. _matplotlib_support:
1021 .. _matplotlib_support:
1086
1022
1087 Plotting with matplotlib
1023 Plotting with matplotlib
1088 ========================
1024 ========================
1089
1025
1090 matplotlib_ provides high quality 2D and 3D plotting for Python. matplotlib_
1026 matplotlib_ provides high quality 2D and 3D plotting for Python. matplotlib_
1091 can produce plots on screen using a variety of GUI toolkits, including Tk,
1027 can produce plots on screen using a variety of GUI toolkits, including Tk,
1092 PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for
1028 PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for
1093 scientific computing, all with a syntax compatible with that of the popular
1029 scientific computing, all with a syntax compatible with that of the popular
1094 Matlab program.
1030 Matlab program.
1095
1031
1096 To start IPython with matplotlib support, use the ``--matplotlib`` switch. If
1032 To start IPython with matplotlib support, use the ``--matplotlib`` switch. If
1097 IPython is already running, you can run the ``%matplotlib`` magic. If no
1033 IPython is already running, you can run the ``%matplotlib`` magic. If no
1098 arguments are given, IPython will automatically detect your choice of
1034 arguments are given, IPython will automatically detect your choice of
1099 matplotlib backend. You can also request a specific backend with
1035 matplotlib backend. You can also request a specific backend with
1100 ``%matplotlib backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx',
1036 ``%matplotlib backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx',
1101 'gtk', 'osx'. In the web notebook and Qt console, 'inline' is also a valid
1037 'gtk', 'osx'. In the web notebook and Qt console, 'inline' is also a valid
1102 backend value, which produces static figures inlined inside the application
1038 backend value, which produces static figures inlined inside the application
1103 window instead of matplotlib's interactive figures that live in separate
1039 window instead of matplotlib's interactive figures that live in separate
1104 windows.
1040 windows.
1105
1041
1106 .. _interactive_demos:
1042 .. _interactive_demos:
1107
1043
1108 Interactive demos with IPython
1044 Interactive demos with IPython
1109 ==============================
1045 ==============================
1110
1046
1111 IPython ships with a basic system for running scripts interactively in
1047 IPython ships with a basic system for running scripts interactively in
1112 sections, useful when presenting code to audiences. A few tags embedded
1048 sections, useful when presenting code to audiences. A few tags embedded
1113 in comments (so that the script remains valid Python code) divide a file
1049 in comments (so that the script remains valid Python code) divide a file
1114 into separate blocks, and the demo can be run one block at a time, with
1050 into separate blocks, and the demo can be run one block at a time, with
1115 IPython printing (with syntax highlighting) the block before executing
1051 IPython printing (with syntax highlighting) the block before executing
1116 it, and returning to the interactive prompt after each block. The
1052 it, and returning to the interactive prompt after each block. The
1117 interactive namespace is updated after each block is run with the
1053 interactive namespace is updated after each block is run with the
1118 contents of the demo's namespace.
1054 contents of the demo's namespace.
1119
1055
1120 This allows you to show a piece of code, run it and then execute
1056 This allows you to show a piece of code, run it and then execute
1121 interactively commands based on the variables just created. Once you
1057 interactively commands based on the variables just created. Once you
1122 want to continue, you simply execute the next block of the demo. The
1058 want to continue, you simply execute the next block of the demo. The
1123 following listing shows the markup necessary for dividing a script into
1059 following listing shows the markup necessary for dividing a script into
1124 sections for execution as a demo:
1060 sections for execution as a demo:
1125
1061
1126 .. literalinclude:: ../../../examples/lib/example-demo.py
1062 .. literalinclude:: ../../../examples/lib/example-demo.py
1127 :language: python
1063 :language: python
1128
1064
1129 In order to run a file as a demo, you must first make a Demo object out
1065 In order to run a file as a demo, you must first make a Demo object out
1130 of it. If the file is named myscript.py, the following code will make a
1066 of it. If the file is named myscript.py, the following code will make a
1131 demo::
1067 demo::
1132
1068
1133 from IPython.lib.demo import Demo
1069 from IPython.lib.demo import Demo
1134
1070
1135 mydemo = Demo('myscript.py')
1071 mydemo = Demo('myscript.py')
1136
1072
1137 This creates the mydemo object, whose blocks you run one at a time by
1073 This creates the mydemo object, whose blocks you run one at a time by
1138 simply calling the object with no arguments. If you have autocall active
1074 simply calling the object with no arguments. Then call it to run each step
1139 in IPython (the default), all you need to do is type::
1075 of the demo::
1140
1076
1141 mydemo
1077 mydemo()
1142
1078
1143 and IPython will call it, executing each block. Demo objects can be
1079 Demo objects can be
1144 restarted, you can move forward or back skipping blocks, re-execute the
1080 restarted, you can move forward or back skipping blocks, re-execute the
1145 last block, etc. Simply use the Tab key on a demo object to see its
1081 last block, etc. See the :mod:`IPython.lib.demo` module and the
1146 methods, and call '?' on them to see their docstrings for more usage
1082 :class:`~IPython.lib.demo.Demo` class for details.
1147 details. In addition, the demo module itself contains a comprehensive
1148 docstring, which you can access via::
1149
1150 from IPython.lib import demo
1151
1152 demo?
1153
1083
1154 Limitations: It is important to note that these demos are limited to
1084 Limitations: These demos are limited to
1155 fairly simple uses. In particular, you cannot break up sections within
1085 fairly simple uses. In particular, you cannot break up sections within
1156 indented code (loops, if statements, function definitions, etc.)
1086 indented code (loops, if statements, function definitions, etc.)
1157 Supporting something like this would basically require tracking the
1087 Supporting something like this would basically require tracking the
1158 internal execution state of the Python interpreter, so only top-level
1088 internal execution state of the Python interpreter, so only top-level
1159 divisions are allowed. If you want to be able to open an IPython
1089 divisions are allowed. If you want to be able to open an IPython
1160 instance at an arbitrary point in a program, you can use IPython's
1090 instance at an arbitrary point in a program, you can use IPython's
1161 embedding facilities, see :func:`IPython.embed` for details.
1091 :ref:`embedding facilities <Embedding>`.
1162
1092
1163 .. include:: ../links.txt
1093 .. include:: ../links.txt
@@ -1,138 +1,137 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2
3 """An example of how to embed an IPython shell into a running program.
2 """An example of how to embed an IPython shell into a running program.
4
3
5 Please see the documentation in the IPython.Shell module for more details.
4 Please see the documentation in the IPython.Shell module for more details.
6
5
7 The accompanying file example-embed-short.py has quick code fragments for
6 The accompanying file example-embed-short.py has quick code fragments for
8 embedding which you can cut and paste in your code once you understand how
7 embedding which you can cut and paste in your code once you understand how
9 things work.
8 things work.
10
9
11 The code in this file is deliberately extra-verbose, meant for learning."""
10 The code in this file is deliberately extra-verbose, meant for learning."""
12 from __future__ import print_function
11 from __future__ import print_function
13
12
14 # The basics to get you going:
13 # The basics to get you going:
15
14
16 # IPython sets the __IPYTHON__ variable so you can know if you have nested
15 # IPython injects get_ipython into builtins, so you can know if you have nested
17 # copies running.
16 # copies running.
18
17
19 # Try running this code both at the command line and from inside IPython (with
18 # Try running this code both at the command line and from inside IPython (with
20 # %run example-embed.py)
19 # %run example-embed.py)
21 from IPython.config.loader import Config
20 from IPython.config.loader import Config
22 try:
21 try:
23 get_ipython
22 get_ipython
24 except NameError:
23 except NameError:
25 nested = 0
24 nested = 0
26 cfg = Config()
25 cfg = Config()
27 prompt_config = cfg.PromptManager
26 prompt_config = cfg.PromptManager
28 prompt_config.in_template = 'In <\\#>: '
27 prompt_config.in_template = 'In <\\#>: '
29 prompt_config.in2_template = ' .\\D.: '
28 prompt_config.in2_template = ' .\\D.: '
30 prompt_config.out_template = 'Out<\\#>: '
29 prompt_config.out_template = 'Out<\\#>: '
31 else:
30 else:
32 print("Running nested copies of IPython.")
31 print("Running nested copies of IPython.")
33 print("The prompts for the nested copy have been modified")
32 print("The prompts for the nested copy have been modified")
34 cfg = Config()
33 cfg = Config()
35 nested = 1
34 nested = 1
36
35
37 # First import the embeddable shell class
36 # First import the embeddable shell class
38 from IPython.terminal.embed import InteractiveShellEmbed
37 from IPython.terminal.embed import InteractiveShellEmbed
39
38
40 # Now create an instance of the embeddable shell. The first argument is a
39 # Now create an instance of the embeddable shell. The first argument is a
41 # string with options exactly as you would type them if you were starting
40 # string with options exactly as you would type them if you were starting
42 # IPython at the system command line. Any parameters you want to define for
41 # IPython at the system command line. Any parameters you want to define for
43 # configuration can thus be specified here.
42 # configuration can thus be specified here.
44 ipshell = InteractiveShellEmbed(config=cfg,
43 ipshell = InteractiveShellEmbed(config=cfg,
45 banner1 = 'Dropping into IPython',
44 banner1 = 'Dropping into IPython',
46 exit_msg = 'Leaving Interpreter, back to program.')
45 exit_msg = 'Leaving Interpreter, back to program.')
47
46
48 # Make a second instance, you can have as many as you want.
47 # Make a second instance, you can have as many as you want.
49 cfg2 = cfg.copy()
48 cfg2 = cfg.copy()
50 prompt_config = cfg2.PromptManager
49 prompt_config = cfg2.PromptManager
51 prompt_config.in_template = 'In2<\\#>: '
50 prompt_config.in_template = 'In2<\\#>: '
52 if not nested:
51 if not nested:
53 prompt_config.in_template = 'In2<\\#>: '
52 prompt_config.in_template = 'In2<\\#>: '
54 prompt_config.in2_template = ' .\\D.: '
53 prompt_config.in2_template = ' .\\D.: '
55 prompt_config.out_template = 'Out<\\#>: '
54 prompt_config.out_template = 'Out<\\#>: '
56 ipshell2 = InteractiveShellEmbed(config=cfg,
55 ipshell2 = InteractiveShellEmbed(config=cfg,
57 banner1 = 'Second IPython instance.')
56 banner1 = 'Second IPython instance.')
58
57
59 print('\nHello. This is printed from the main controller program.\n')
58 print('\nHello. This is printed from the main controller program.\n')
60
59
61 # You can then call ipshell() anywhere you need it (with an optional
60 # You can then call ipshell() anywhere you need it (with an optional
62 # message):
61 # message):
63 ipshell('***Called from top level. '
62 ipshell('***Called from top level. '
64 'Hit Ctrl-D to exit interpreter and continue program.\n'
63 'Hit Ctrl-D to exit interpreter and continue program.\n'
65 'Note that if you use %kill_embedded, you can fully deactivate\n'
64 'Note that if you use %kill_embedded, you can fully deactivate\n'
66 'This embedded instance so it will never turn on again')
65 'This embedded instance so it will never turn on again')
67
66
68 print('\nBack in caller program, moving along...\n')
67 print('\nBack in caller program, moving along...\n')
69
68
70 #---------------------------------------------------------------------------
69 #---------------------------------------------------------------------------
71 # More details:
70 # More details:
72
71
73 # InteractiveShellEmbed instances don't print the standard system banner and
72 # InteractiveShellEmbed instances don't print the standard system banner and
74 # messages. The IPython banner (which actually may contain initialization
73 # messages. The IPython banner (which actually may contain initialization
75 # messages) is available as get_ipython().banner in case you want it.
74 # messages) is available as get_ipython().banner in case you want it.
76
75
77 # InteractiveShellEmbed instances print the following information everytime they
76 # InteractiveShellEmbed instances print the following information everytime they
78 # start:
77 # start:
79
78
80 # - A global startup banner.
79 # - A global startup banner.
81
80
82 # - A call-specific header string, which you can use to indicate where in the
81 # - A call-specific header string, which you can use to indicate where in the
83 # execution flow the shell is starting.
82 # execution flow the shell is starting.
84
83
85 # They also print an exit message every time they exit.
84 # They also print an exit message every time they exit.
86
85
87 # Both the startup banner and the exit message default to None, and can be set
86 # Both the startup banner and the exit message default to None, and can be set
88 # either at the instance constructor or at any other time with the
87 # either at the instance constructor or at any other time with the
89 # by setting the banner and exit_msg attributes.
88 # by setting the banner and exit_msg attributes.
90
89
91 # The shell instance can be also put in 'dummy' mode globally or on a per-call
90 # The shell instance can be also put in 'dummy' mode globally or on a per-call
92 # basis. This gives you fine control for debugging without having to change
91 # basis. This gives you fine control for debugging without having to change
93 # code all over the place.
92 # code all over the place.
94
93
95 # The code below illustrates all this.
94 # The code below illustrates all this.
96
95
97
96
98 # This is how the global banner and exit_msg can be reset at any point
97 # This is how the global banner and exit_msg can be reset at any point
99 ipshell.banner = 'Entering interpreter - New Banner'
98 ipshell.banner = 'Entering interpreter - New Banner'
100 ipshell.exit_msg = 'Leaving interpreter - New exit_msg'
99 ipshell.exit_msg = 'Leaving interpreter - New exit_msg'
101
100
102 def foo(m):
101 def foo(m):
103 s = 'spam'
102 s = 'spam'
104 ipshell('***In foo(). Try %whos, or print s or m:')
103 ipshell('***In foo(). Try %whos, or print s or m:')
105 print('foo says m = ',m)
104 print('foo says m = ',m)
106
105
107 def bar(n):
106 def bar(n):
108 s = 'eggs'
107 s = 'eggs'
109 ipshell('***In bar(). Try %whos, or print s or n:')
108 ipshell('***In bar(). Try %whos, or print s or n:')
110 print('bar says n = ',n)
109 print('bar says n = ',n)
111
110
112 # Some calls to the above functions which will trigger IPython:
111 # Some calls to the above functions which will trigger IPython:
113 print('Main program calling foo("eggs")\n')
112 print('Main program calling foo("eggs")\n')
114 foo('eggs')
113 foo('eggs')
115
114
116 # The shell can be put in 'dummy' mode where calls to it silently return. This
115 # The shell can be put in 'dummy' mode where calls to it silently return. This
117 # allows you, for example, to globally turn off debugging for a program with a
116 # allows you, for example, to globally turn off debugging for a program with a
118 # single call.
117 # single call.
119 ipshell.dummy_mode = True
118 ipshell.dummy_mode = True
120 print('\nTrying to call IPython which is now "dummy":')
119 print('\nTrying to call IPython which is now "dummy":')
121 ipshell()
120 ipshell()
122 print('Nothing happened...')
121 print('Nothing happened...')
123 # The global 'dummy' mode can still be overridden for a single call
122 # The global 'dummy' mode can still be overridden for a single call
124 print('\nOverriding dummy mode manually:')
123 print('\nOverriding dummy mode manually:')
125 ipshell(dummy=False)
124 ipshell(dummy=False)
126
125
127 # Reactivate the IPython shell
126 # Reactivate the IPython shell
128 ipshell.dummy_mode = False
127 ipshell.dummy_mode = False
129
128
130 print('You can even have multiple embedded instances:')
129 print('You can even have multiple embedded instances:')
131 ipshell2()
130 ipshell2()
132
131
133 print('\nMain program calling bar("spam")\n')
132 print('\nMain program calling bar("spam")\n')
134 bar('spam')
133 bar('spam')
135
134
136 print('Main program finished. Bye!')
135 print('Main program finished. Bye!')
137
136
138 #********************** End of file <example-embed.py> ***********************
137 #********************** End of file <example-embed.py> ***********************
@@ -1,44 +1,43 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """A simple interactive demo to illustrate the use of IPython's Demo class.
2 """A simple interactive demo to illustrate the use of IPython's Demo class.
3
3
4 Any python script can be run as a demo, but that does little more than showing
4 Any python script can be run as a demo, but that does little more than showing
5 it on-screen, syntax-highlighted in one shot. If you add a little simple
5 it on-screen, syntax-highlighted in one shot. If you add a little simple
6 markup, you can stop at specified intervals and return to the ipython prompt,
6 markup, you can stop at specified intervals and return to the ipython prompt,
7 resuming execution later.
7 resuming execution later.
8
8
9 This is a unicode test, Γ₯Àâ
9 This is a unicode test, Γ₯Àâ
10 """
10 """
11 from __future__ import print_function
11 from __future__ import print_function
12
12
13 print('Hello, welcome to an interactive IPython demo.')
13 print('Hello, welcome to an interactive IPython demo.')
14 print('Executing this block should require confirmation before proceeding,')
14 print('Executing this block should require confirmation before proceeding,')
15 print('unless auto_all has been set to true in the demo object')
15 print('unless auto_all has been set to true in the demo object')
16
16
17 # The mark below defines a block boundary, which is a point where IPython will
17 # The mark below defines a block boundary, which is a point where IPython will
18 # stop execution and return to the interactive prompt.
18 # stop execution and return to the interactive prompt.
19 # Note that in actual interactive execution,
20 # <demo> --- stop ---
19 # <demo> --- stop ---
21
20
22 x = 1
21 x = 1
23 y = 2
22 y = 2
24
23
25 # <demo> --- stop ---
24 # <demo> --- stop ---
26
25
27 # the mark below makes this block as silent
26 # the mark below makes this block as silent
28 # <demo> silent
27 # <demo> silent
29
28
30 print('This is a silent block, which gets executed but not printed.')
29 print('This is a silent block, which gets executed but not printed.')
31
30
32 # <demo> --- stop ---
31 # <demo> --- stop ---
33 # <demo> auto
32 # <demo> auto
34 print('This is an automatic block.')
33 print('This is an automatic block.')
35 print('It is executed without asking for confirmation, but printed.')
34 print('It is executed without asking for confirmation, but printed.')
36 z = x+y
35 z = x+y
37
36
38 print('z=',x)
37 print('z=',x)
39
38
40 # <demo> --- stop ---
39 # <demo> --- stop ---
41 # This is just another normal block.
40 # This is just another normal block.
42 print('z is now:', z)
41 print('z is now:', z)
43
42
44 print('bye!')
43 print('bye!')
General Comments 0
You need to be logged in to leave comments. Login now