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