##// END OF EJS Templates
update qt import priority per recent discussion...
MinRK -
Show More
@@ -1,75 +1,82 b''
1 1 """ Import Qt in a manner suitable for an IPython kernel.
2 2
3 3 This is the import used for the `gui=qt` or `pylab=qt` initialization.
4 4
5 Priority:
5 Import Priority:
6 6
7 if matplotlib has been imported:
8 # get here with pylab=qt
9 if matplotlib doesn't support v2 (<= 1.0.1):
10 use PyQt4 @v1
11 else:
12 ask matplotlib which Qt it's using
13 if it said PyQt:
14 use PyQt4 @v1
15 elif it said PySide:
16 use PySide
7 if matplotlib has been imported and doesn't support v2 (<= 1.0.1):
8 use PyQt4 @v1
17 9
18 if matplotlib had nothing to say, or matplotlib not imported:
19 # get here with gui=qt, or if matplotlib didn't tell us anything
20 ask ETS' QT_API env variable
10 Next, ask ETS' QT_API env variable
11
12 if QT_API not set:
13 ask matplotlib via rcParams['backend.qt4']
14 if it said PyQt:
15 use PyQt4 @v1
16 elif it said PySide:
17 use PySide
21 18
22 if QT_API not set:
23 # this is the *default* path - no information was given
19 else: (matplotlib said nothing)
20 # this is the default path - nobody told us anything
24 21 try:
25 22 PyQt @v1
26 23 except:
27 24 fallback on PySide
28 else:
29 use PyQt @v2 or PySide, depending on QT_API
30 because ETS doesn't work with v1.
25 else:
26 use PyQt @v2 or PySide, depending on QT_API
27 because ETS doesn't work with PyQt @v1.
28
31 29 """
32 30
33 31 import os
34 32 import sys
35 33
36 34 matplotlib = sys.modules.get('matplotlib')
37 if matplotlib:
38 # ask matplotlib first (get here with pylab=qt)
39 if matplotlib.__version__ <= '1.0.1':
40 # 1.0.1 doesn't support pyside or v2, so force PyQt @v1
41 mod = 'PyQt4'
42 else:
43 # this rc option has been proposed, but is yet not in matplotlib master
44 # as of writing.
45 mod = matplotlib.rcParams.get('backend.qt4', None)
35 if matplotlib and matplotlib.__version__ <= '1.0.1':
36 # 1.0.1 doesn't support pyside or v2, so stick with PyQt @v1,
37 # and ignore everything else
38 from PyQt4 import QtCore, QtGui
46 39 else:
47 # get here with `gui=qt`
48 mod = None
49
50 if mod is None:
51 # matplotlib not imported or had nothing to say.
52 # ask QT_API ETS variable
40 # ask QT_API ETS variable *first*
53 41 QT_API = os.environ.get('QT_API', None)
54 42 if QT_API is None:
55 try:
56 # default to unconfigured PyQt4
57 from PyQt4 import QtCore, QtGui
58 except ImportError:
59 # fallback on PySide
43 # QT_API not set, ask matplotlib if it was imported (e.g. `pylab=qt`)
44 if matplotlib:
45 mpqt = matplotlib.rcParams.get('backend.qt4', None)
46 else:
47 mpqt = None
48 if mpqt is None:
49 # matplotlib not imported or had nothing to say.
60 50 try:
61 from PySide import QtCore, QtGui
51 # default to unconfigured PyQt4
52 from PyQt4 import QtCore, QtGui
62 53 except ImportError:
63 raise ImportError('Cannot import PySide or PyQt4')
54 # fallback on PySide
55 try:
56 from PySide import QtCore, QtGui
57 except ImportError:
58 raise ImportError('Cannot import PySide or PyQt4')
59 elif mpqt.lower() == 'pyqt4':
60 # import PyQt4 unconfigured
61 from PyQt4 import QtCore, QtGui
62 elif mpqt.lower() == 'pyside':
63 from PySide import QtCore, QtGui
64 else:
65 raise ImportError("unhandled value for backend.qt4 from matplotlib: %r"%mpqt)
64 66 else:
65 67 # QT_API specified, use PySide or PyQt+v2 API from external.qt
66 68 # this means ETS is likely to be used, which requires v2
67 from IPython.external.qt import QtCore, QtGui
69 try:
70 from IPython.external.qt import QtCore, QtGui
71 except ValueError as e:
72 if 'API' in str(e):
73 # API mismatch, give more meaningful message
74 raise ImportError("""
75 Assigning the ETS variable `QT_API=pyqt` implies PyQt's v2 API for
76 QString and QVariant, but PyQt has already been imported
77 with v1 APIs. You must unset QT_API to work with PyQt4
78 in its default mode.
79 """)
80 else:
81 raise
68 82
69 elif mod.lower() == 'pyqt4':
70 # import PyQt4 unconfigured
71 from PyQt4 import QtCore, QtGui
72 elif mod.lower() == 'pyside':
73 from PySide import QtCore, QtGui
74 else:
75 raise ImportError("unhandled value for backend.qt4 from matplotlib: %r"%mod) No newline at end of file
@@ -1,1385 +1,1385 b''
1 1 =================
2 2 IPython reference
3 3 =================
4 4
5 5 .. _command_line_options:
6 6
7 7 Command-line usage
8 8 ==================
9 9
10 10 You start IPython with the command::
11 11
12 12 $ ipython [options] files
13 13
14 14 If invoked with no options, it executes all the files listed in sequence
15 15 and drops you into the interpreter while still acknowledging any options
16 16 you may have set in your ipython_config.py. This behavior is different from
17 17 standard Python, which when called as python -i will only execute one
18 18 file and ignore your configuration setup.
19 19
20 20 Please note that some of the configuration options are not available at
21 21 the command line, simply because they are not practical here. Look into
22 22 your ipythonrc configuration file for details on those. This file is typically
23 23 installed in the IPYTHON_DIR directory. For Linux
24 24 users, this will be $HOME/.config/ipython, and for other users it will be
25 25 $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and
26 26 Settings\\YourUserName in most instances.
27 27
28 28
29 29 Eventloop integration
30 30 ---------------------
31 31
32 32 Previously IPython had command line options for controlling GUI event loop
33 33 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
34 34 version 0.11, these have been removed. Please see the new ``%gui``
35 35 magic command or :ref:`this section <gui_support>` for details on the new
36 36 interface, or specify the gui at the commandline::
37 37
38 38 $ ipython gui=qt
39 39
40 40
41 41 Regular Options
42 42 ---------------
43 43
44 44 After the above threading options have been given, regular options can
45 45 follow in any order. All options can be abbreviated to their shortest
46 46 non-ambiguous form and are case-sensitive. One or two dashes can be
47 47 used. Some options have an alternate short form, indicated after a ``|``.
48 48
49 49 Most options can also be set from your ipythonrc configuration file. See
50 50 the provided example for more details on what the options do. Options
51 51 given at the command line override the values set in the ipythonrc file.
52 52
53 53 All options with a [no] prepended can be specified in negated form
54 54 (--no-option instead of --option) to turn the feature off.
55 55
56 56 ``-h, --help`` print a help message and exit.
57 57
58 58 ``--pylab, pylab=<name>``
59 59 See :ref:`Matplotlib support <matplotlib_support>`
60 60 for more details.
61 61
62 62 ``autocall=<val>``
63 63 Make IPython automatically call any callable object even if you
64 64 didn't type explicit parentheses. For example, 'str 43' becomes
65 65 'str(43)' automatically. The value can be '0' to disable the feature,
66 66 '1' for smart autocall, where it is not applied if there are no more
67 67 arguments on the line, and '2' for full autocall, where all callable
68 68 objects are automatically called (even if no arguments are
69 69 present). The default is '1'.
70 70
71 71 ``--[no-]autoindent``
72 72 Turn automatic indentation on/off.
73 73
74 74 ``--[no-]automagic``
75 75 make magic commands automatic (without needing their first character
76 76 to be %). Type %magic at the IPython prompt for more information.
77 77
78 78 ``--[no-]autoedit_syntax``
79 79 When a syntax error occurs after editing a file, automatically
80 80 open the file to the trouble causing line for convenient
81 81 fixing.
82 82
83 83 ``--[no-]banner``
84 84 Print the initial information banner (default on).
85 85
86 86 ``c=<command>``
87 87 execute the given command string. This is similar to the -c
88 88 option in the normal Python interpreter.
89 89
90 90 ``cache_size=<n>``
91 91 size of the output cache (maximum number of entries to hold in
92 92 memory). The default is 1000, you can change it permanently in your
93 93 config file. Setting it to 0 completely disables the caching system,
94 94 and the minimum value accepted is 20 (if you provide a value less than
95 95 20, it is reset to 0 and a warning is issued) This limit is defined
96 96 because otherwise you'll spend more time re-flushing a too small cache
97 97 than working.
98 98
99 99 ``--classic``
100 100 Gives IPython a similar feel to the classic Python
101 101 prompt.
102 102
103 103 ``colors=<scheme>``
104 104 Color scheme for prompts and exception reporting. Currently
105 105 implemented: NoColor, Linux and LightBG.
106 106
107 107 ``--[no-]color_info``
108 108 IPython can display information about objects via a set of functions,
109 109 and optionally can use colors for this, syntax highlighting source
110 110 code and various other elements. However, because this information is
111 111 passed through a pager (like 'less') and many pagers get confused with
112 112 color codes, this option is off by default. You can test it and turn
113 113 it on permanently in your ipythonrc file if it works for you. As a
114 114 reference, the 'less' pager supplied with Mandrake 8.2 works ok, but
115 115 that in RedHat 7.2 doesn't.
116 116
117 117 Test it and turn it on permanently if it works with your
118 118 system. The magic function %color_info allows you to toggle this
119 119 interactively for testing.
120 120
121 121 ``--[no-]debug``
122 122 Show information about the loading process. Very useful to pin down
123 123 problems with your configuration files or to get details about
124 124 session restores.
125 125
126 126 ``--[no-]deep_reload``
127 127 IPython can use the deep_reload module which reloads changes in
128 128 modules recursively (it replaces the reload() function, so you don't
129 129 need to change anything to use it). deep_reload() forces a full
130 130 reload of modules whose code may have changed, which the default
131 131 reload() function does not.
132 132
133 133 When deep_reload is off, IPython will use the normal reload(),
134 134 but deep_reload will still be available as dreload(). This
135 135 feature is off by default [which means that you have both
136 136 normal reload() and dreload()].
137 137
138 138 ``editor=<name>``
139 139 Which editor to use with the %edit command. By default,
140 140 IPython will honor your EDITOR environment variable (if not
141 141 set, vi is the Unix default and notepad the Windows one).
142 142 Since this editor is invoked on the fly by IPython and is
143 143 meant for editing small code snippets, you may want to use a
144 144 small, lightweight editor here (in case your default EDITOR is
145 145 something like Emacs).
146 146
147 147 ``ipython_dir=<name>``
148 148 name of your IPython configuration directory IPYTHON_DIR. This
149 149 can also be specified through the environment variable
150 150 IPYTHON_DIR.
151 151
152 152 ``logfile=<name>``
153 153 specify the name of your logfile.
154 154
155 155 This implies ``%logstart`` at the beginning of your session
156 156
157 157 generate a log file of all input. The file is named
158 158 ipython_log.py in your current directory (which prevents logs
159 159 from multiple IPython sessions from trampling each other). You
160 160 can use this to later restore a session by loading your
161 161 logfile with ``ipython --i ipython_log.py``
162 162
163 163 ``logplay=<name>``
164 164
165 165 NOT AVAILABLE in 0.11
166 166
167 167 you can replay a previous log. For restoring a session as close as
168 168 possible to the state you left it in, use this option (don't just run
169 169 the logfile). With -logplay, IPython will try to reconstruct the
170 170 previous working environment in full, not just execute the commands in
171 171 the logfile.
172 172
173 173 When a session is restored, logging is automatically turned on
174 174 again with the name of the logfile it was invoked with (it is
175 175 read from the log header). So once you've turned logging on for
176 176 a session, you can quit IPython and reload it as many times as
177 177 you want and it will continue to log its history and restore
178 178 from the beginning every time.
179 179
180 180 Caveats: there are limitations in this option. The history
181 181 variables _i*,_* and _dh don't get restored properly. In the
182 182 future we will try to implement full session saving by writing
183 183 and retrieving a 'snapshot' of the memory state of IPython. But
184 184 our first attempts failed because of inherent limitations of
185 185 Python's Pickle module, so this may have to wait.
186 186
187 187 ``--[no-]messages``
188 188 Print messages which IPython collects about its startup
189 189 process (default on).
190 190
191 191 ``--[no-]pdb``
192 192 Automatically call the pdb debugger after every uncaught
193 193 exception. If you are used to debugging using pdb, this puts
194 194 you automatically inside of it after any call (either in
195 195 IPython or in code called by it) which triggers an exception
196 196 which goes uncaught.
197 197
198 198 ``--[no-]pprint``
199 199 ipython can optionally use the pprint (pretty printer) module
200 200 for displaying results. pprint tends to give a nicer display
201 201 of nested data structures. If you like it, you can turn it on
202 202 permanently in your config file (default off).
203 203
204 204 ``profile=<name>``
205 205
206 206 Select the IPython profile by name.
207 207
208 208 This is a quick way to keep and load multiple
209 209 config files for different tasks, especially if you use the
210 210 include option of config files. You can keep a basic
211 211 :file:`IPYTHON_DIR/profile_default/ipython_config.py` file
212 212 and then have other 'profiles' which
213 213 include this one and load extra things for particular
214 214 tasks. For example:
215 215
216 216 1. $IPYTHON_DIR/profile_default : load basic things you always want.
217 217 2. $IPYTHON_DIR/profile_math : load (1) and basic math-related modules.
218 218 3. $IPYTHON_DIR/profile_numeric : load (1) and Numeric and plotting modules.
219 219
220 220 Since it is possible to create an endless loop by having
221 221 circular file inclusions, IPython will stop if it reaches 15
222 222 recursive inclusions.
223 223
224 224 ``InteractiveShell.prompt_in1=<string>``
225 225
226 226 Specify the string used for input prompts. Note that if you are using
227 227 numbered prompts, the number is represented with a '\#' in the
228 228 string. Don't forget to quote strings with spaces embedded in
229 229 them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>`
230 230 discusses in detail all the available escapes to customize your
231 231 prompts.
232 232
233 233 ``InteractiveShell.prompt_in2=<string>``
234 234 Similar to the previous option, but used for the continuation
235 235 prompts. The special sequence '\D' is similar to '\#', but
236 236 with all digits replaced dots (so you can have your
237 237 continuation prompt aligned with your input prompt). Default:
238 238 ' .\D.:' (note three spaces at the start for alignment with
239 239 'In [\#]').
240 240
241 241 ``InteractiveShell.prompt_out=<string>``
242 242 String used for output prompts, also uses numbers like
243 243 prompt_in1. Default: 'Out[\#]:'
244 244
245 245 ``--quick``
246 246 start in bare bones mode (no config file loaded).
247 247
248 248 ``config_file=<name>``
249 249 name of your IPython resource configuration file. Normally
250 250 IPython loads ipython_config.py (from current directory) or
251 251 IPYTHON_DIR/profile_default.
252 252
253 253 If the loading of your config file fails, IPython starts with
254 254 a bare bones configuration (no modules loaded at all).
255 255
256 256 ``--[no-]readline``
257 257 use the readline library, which is needed to support name
258 258 completion and command history, among other things. It is
259 259 enabled by default, but may cause problems for users of
260 260 X/Emacs in Python comint or shell buffers.
261 261
262 262 Note that X/Emacs 'eterm' buffers (opened with M-x term) support
263 263 IPython's readline and syntax coloring fine, only 'emacs' (M-x
264 264 shell and C-c !) buffers do not.
265 265
266 266 ``TerminalInteractiveShell.screen_length=<n>``
267 267 number of lines of your screen. This is used to control
268 268 printing of very long strings. Strings longer than this number
269 269 of lines will be sent through a pager instead of directly
270 270 printed.
271 271
272 272 The default value for this is 0, which means IPython will
273 273 auto-detect your screen size every time it needs to print certain
274 274 potentially long strings (this doesn't change the behavior of the
275 275 'print' keyword, it's only triggered internally). If for some
276 276 reason this isn't working well (it needs curses support), specify
277 277 it yourself. Otherwise don't change the default.
278 278
279 279 ``TerminalInteractiveShell.separate_in=<string>``
280 280
281 281 separator before input prompts.
282 282 Default: '\n'
283 283
284 284 ``TerminalInteractiveShell.separate_out=<string>``
285 285 separator before output prompts.
286 286 Default: nothing.
287 287
288 288 ``TerminalInteractiveShell.separate_out2=<string>``
289 289 separator after output prompts.
290 290 Default: nothing.
291 291 For these three options, use the value 0 to specify no separator.
292 292
293 293 ``--nosep``
294 294 shorthand for setting the above separators to empty strings.
295 295
296 296 Simply removes all input/output separators.
297 297
298 298 ``--init``
299 299 allows you to initialize a profile dir for configuration when you
300 300 install a new version of IPython or want to use a new profile.
301 301 Since new versions may include new command line options or example
302 302 files, this copies updated config files. Note that you should probably
303 303 use %upgrade instead,it's a safer alternative.
304 304
305 305 ``--version`` print version information and exit.
306 306
307 307 ``xmode=<modename>``
308 308
309 309 Mode for exception reporting.
310 310
311 311 Valid modes: Plain, Context and Verbose.
312 312
313 313 * Plain: similar to python's normal traceback printing.
314 314 * Context: prints 5 lines of context source code around each
315 315 line in the traceback.
316 316 * Verbose: similar to Context, but additionally prints the
317 317 variables currently visible where the exception happened
318 318 (shortening their strings if too long). This can potentially be
319 319 very slow, if you happen to have a huge data structure whose
320 320 string representation is complex to compute. Your computer may
321 321 appear to freeze for a while with cpu usage at 100%. If this
322 322 occurs, you can cancel the traceback with Ctrl-C (maybe hitting it
323 323 more than once).
324 324
325 325 Interactive use
326 326 ===============
327 327
328 328 IPython is meant to work as a drop-in
329 329 replacement for the standard interactive interpreter. As such, any code
330 330 which is valid python should execute normally under IPython (cases where
331 331 this is not true should be reported as bugs). It does, however, offer
332 332 many features which are not available at a standard python prompt. What
333 333 follows is a list of these.
334 334
335 335
336 336 Caution for Windows users
337 337 -------------------------
338 338
339 339 Windows, unfortunately, uses the '\\' character as a path
340 340 separator. This is a terrible choice, because '\\' also represents the
341 341 escape character in most modern programming languages, including
342 342 Python. For this reason, using '/' character is recommended if you
343 343 have problems with ``\``. However, in Windows commands '/' flags
344 344 options, so you can not use it for the root directory. This means that
345 345 paths beginning at the root must be typed in a contrived manner like:
346 346 ``%copy \opt/foo/bar.txt \tmp``
347 347
348 348 .. _magic:
349 349
350 350 Magic command system
351 351 --------------------
352 352
353 353 IPython will treat any line whose first character is a % as a special
354 354 call to a 'magic' function. These allow you to control the behavior of
355 355 IPython itself, plus a lot of system-type features. They are all
356 356 prefixed with a % character, but parameters are given without
357 357 parentheses or quotes.
358 358
359 359 Example: typing ``%cd mydir`` changes your working directory to 'mydir', if it
360 360 exists.
361 361
362 362 If you have 'automagic' enabled (as it by default), you don't need
363 363 to type in the % explicitly. IPython will scan its internal list of
364 364 magic functions and call one if it exists. With automagic on you can
365 365 then just type ``cd mydir`` to go to directory 'mydir'. The automagic
366 366 system has the lowest possible precedence in name searches, so defining
367 367 an identifier with the same name as an existing magic function will
368 368 shadow it for automagic use. You can still access the shadowed magic
369 369 function by explicitly using the % character at the beginning of the line.
370 370
371 371 An example (with automagic on) should clarify all this:
372 372
373 373 .. sourcecode:: ipython
374 374
375 375 In [1]: cd ipython # %cd is called by automagic
376 376
377 377 /home/fperez/ipython
378 378
379 379 In [2]: cd=1 # now cd is just a variable
380 380
381 381 In [3]: cd .. # and doesn't work as a function anymore
382 382
383 383 ------------------------------
384 384
385 385 File "<console>", line 1
386 386
387 387 cd ..
388 388
389 389 ^
390 390
391 391 SyntaxError: invalid syntax
392 392
393 393 In [4]: %cd .. # but %cd always works
394 394
395 395 /home/fperez
396 396
397 397 In [5]: del cd # if you remove the cd variable
398 398
399 399 In [6]: cd ipython # automagic can work again
400 400
401 401 /home/fperez/ipython
402 402
403 403 You can define your own magic functions to extend the system. The
404 404 following example defines a new magic command, %impall:
405 405
406 406 .. sourcecode:: python
407 407
408 408 ip = get_ipython()
409 409
410 410 def doimp(self, arg):
411 411
412 412 ip = self.api
413 413
414 414 ip.ex("import %s; reload(%s); from %s import *" % (
415 415
416 416 arg,arg,arg)
417 417
418 418 )
419 419
420 420 ip.expose_magic('impall', doimp)
421 421
422 422 Type %magic for more information, including a list of all available
423 423 magic functions at any time and their docstrings. You can also type
424 424 %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for
425 425 information on the '?' system) to get information about any particular
426 426 magic function you are interested in.
427 427
428 428 The API documentation for the :mod:`IPython.core.magic` module contains the full
429 429 docstrings of all currently available magic commands.
430 430
431 431
432 432 Access to the standard Python help
433 433 ----------------------------------
434 434
435 435 As of Python 2.1, a help system is available with access to object docstrings
436 436 and the Python manuals. Simply type 'help' (no quotes) to access it. You can
437 437 also type help(object) to obtain information about a given object, and
438 438 help('keyword') for information on a keyword. As noted :ref:`here
439 439 <accessing_help>`, you need to properly configure your environment variable
440 440 PYTHONDOCS for this feature to work correctly.
441 441
442 442 .. _dynamic_object_info:
443 443
444 444 Dynamic object information
445 445 --------------------------
446 446
447 447 Typing ?word or word? prints detailed information about an object. If
448 448 certain strings in the object are too long (docstrings, code, etc.) they
449 449 get snipped in the center for brevity. This system gives access variable
450 450 types and values, full source code for any object (if available),
451 451 function prototypes and other useful information.
452 452
453 453 Typing ??word or word?? gives access to the full information without
454 454 snipping long strings. Long strings are sent to the screen through the
455 455 less pager if longer than the screen and printed otherwise. On systems
456 456 lacking the less command, IPython uses a very basic internal pager.
457 457
458 458 The following magic functions are particularly useful for gathering
459 459 information about your working environment. You can get more details by
460 460 typing %magic or querying them individually (use %function_name? with or
461 461 without the %), this is just a summary:
462 462
463 463 * **%pdoc <object>**: Print (or run through a pager if too long) the
464 464 docstring for an object. If the given object is a class, it will
465 465 print both the class and the constructor docstrings.
466 466 * **%pdef <object>**: Print the definition header for any callable
467 467 object. If the object is a class, print the constructor information.
468 468 * **%psource <object>**: Print (or run through a pager if too long)
469 469 the source code for an object.
470 470 * **%pfile <object>**: Show the entire source file where an object was
471 471 defined via a pager, opening it at the line where the object
472 472 definition begins.
473 473 * **%who/%whos**: These functions give information about identifiers
474 474 you have defined interactively (not things you loaded or defined
475 475 in your configuration files). %who just prints a list of
476 476 identifiers and %whos prints a table with some basic details about
477 477 each identifier.
478 478
479 479 Note that the dynamic object information functions (?/??, %pdoc, %pfile,
480 480 %pdef, %psource) give you access to documentation even on things which
481 481 are not really defined as separate identifiers. Try for example typing
482 482 {}.get? or after doing import os, type os.path.abspath??.
483 483
484 484
485 485 .. _readline:
486 486
487 487 Readline-based features
488 488 -----------------------
489 489
490 490 These features require the GNU readline library, so they won't work if
491 491 your Python installation lacks readline support. We will first describe
492 492 the default behavior IPython uses, and then how to change it to suit
493 493 your preferences.
494 494
495 495
496 496 Command line completion
497 497 +++++++++++++++++++++++
498 498
499 499 At any time, hitting TAB will complete any available python commands or
500 500 variable names, and show you a list of the possible completions if
501 501 there's no unambiguous one. It will also complete filenames in the
502 502 current directory if no python names match what you've typed so far.
503 503
504 504
505 505 Search command history
506 506 ++++++++++++++++++++++
507 507
508 508 IPython provides two ways for searching through previous input and thus
509 509 reduce the need for repetitive typing:
510 510
511 511 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
512 512 (next,down) to search through only the history items that match
513 513 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
514 514 prompt, they just behave like normal arrow keys.
515 515 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
516 516 searches your history for lines that contain what you've typed so
517 517 far, completing as much as it can.
518 518
519 519
520 520 Persistent command history across sessions
521 521 ++++++++++++++++++++++++++++++++++++++++++
522 522
523 523 IPython will save your input history when it leaves and reload it next
524 524 time you restart it. By default, the history file is named
525 525 $IPYTHON_DIR/profile_<name>/history.sqlite. This allows you to keep
526 526 separate histories related to various tasks: commands related to
527 527 numerical work will not be clobbered by a system shell history, for
528 528 example.
529 529
530 530
531 531 Autoindent
532 532 ++++++++++
533 533
534 534 IPython can recognize lines ending in ':' and indent the next line,
535 535 while also un-indenting automatically after 'raise' or 'return'.
536 536
537 537 This feature uses the readline library, so it will honor your ~/.inputrc
538 538 configuration (or whatever file your INPUTRC variable points to). Adding
539 539 the following lines to your .inputrc file can make indenting/unindenting
540 540 more convenient (M-i indents, M-u unindents)::
541 541
542 542 $if Python
543 543 "\M-i": " "
544 544 "\M-u": "\d\d\d\d"
545 545 $endif
546 546
547 547 Note that there are 4 spaces between the quote marks after "M-i" above.
548 548
549 549 .. warning::
550 550
551 551 Setting the above indents will cause problems with unicode text entry in the terminal.
552 552
553 553 .. warning::
554 554
555 555 Autoindent is ON by default, but it can cause problems with
556 556 the pasting of multi-line indented code (the pasted code gets
557 557 re-indented on each line). A magic function %autoindent allows you to
558 558 toggle it on/off at runtime. You can also disable it permanently on in
559 559 your :file:`ipython_config.py` file (set TerminalInteractiveShell.autoindent=False).
560 560
561 561 If you want to paste multiple lines, it is recommended that you use ``%paste``.
562 562
563 563
564 564 Customizing readline behavior
565 565 +++++++++++++++++++++++++++++
566 566
567 567 All these features are based on the GNU readline library, which has an
568 568 extremely customizable interface. Normally, readline is configured via a
569 569 file which defines the behavior of the library; the details of the
570 570 syntax for this can be found in the readline documentation available
571 571 with your system or on the Internet. IPython doesn't read this file (if
572 572 it exists) directly, but it does support passing to readline valid
573 573 options via a simple interface. In brief, you can customize readline by
574 574 setting the following options in your ipythonrc configuration file (note
575 575 that these options can not be specified at the command line):
576 576
577 577 * **readline_parse_and_bind**: this option can appear as many times as
578 578 you want, each time defining a string to be executed via a
579 579 readline.parse_and_bind() command. The syntax for valid commands
580 580 of this kind can be found by reading the documentation for the GNU
581 581 readline library, as these commands are of the kind which readline
582 582 accepts in its configuration file.
583 583 * **readline_remove_delims**: a string of characters to be removed
584 584 from the default word-delimiters list used by readline, so that
585 585 completions may be performed on strings which contain them. Do not
586 586 change the default value unless you know what you're doing.
587 587 * **readline_omit__names**: when tab-completion is enabled, hitting
588 588 <tab> after a '.' in a name will complete all attributes of an
589 589 object, including all the special methods whose names include
590 590 double underscores (like __getitem__ or __class__). If you'd
591 591 rather not see these names by default, you can set this option to
592 592 1. Note that even when this option is set, you can still see those
593 593 names by explicitly typing a _ after the period and hitting <tab>:
594 594 'name._<tab>' will always complete attribute names starting with '_'.
595 595
596 596 This option is off by default so that new users see all
597 597 attributes of any objects they are dealing with.
598 598
599 599 You will find the default values along with a corresponding detailed
600 600 explanation in your ipythonrc file.
601 601
602 602
603 603 Session logging and restoring
604 604 -----------------------------
605 605
606 606 You can log all input from a session either by starting IPython with the
607 607 command line switche ``logfile=foo.py`` (see :ref:`here <command_line_options>`)
608 608 or by activating the logging at any moment with the magic function %logstart.
609 609
610 610 Log files can later be reloaded by running them as scripts and IPython
611 611 will attempt to 'replay' the log by executing all the lines in it, thus
612 612 restoring the state of a previous session. This feature is not quite
613 613 perfect, but can still be useful in many cases.
614 614
615 615 The log files can also be used as a way to have a permanent record of
616 616 any code you wrote while experimenting. Log files are regular text files
617 617 which you can later open in your favorite text editor to extract code or
618 618 to 'clean them up' before using them to replay a session.
619 619
620 620 The %logstart function for activating logging in mid-session is used as
621 621 follows:
622 622
623 623 %logstart [log_name [log_mode]]
624 624
625 625 If no name is given, it defaults to a file named 'ipython_log.py' in your
626 626 current working directory, in 'rotate' mode (see below).
627 627
628 628 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
629 629 history up to that point and then continues logging.
630 630
631 631 %logstart takes a second optional parameter: logging mode. This can be
632 632 one of (note that the modes are given unquoted):
633 633
634 634 * [over:] overwrite existing log_name.
635 635 * [backup:] rename (if exists) to log_name~ and start log_name.
636 636 * [append:] well, that says it.
637 637 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
638 638
639 639 The %logoff and %logon functions allow you to temporarily stop and
640 640 resume logging to a file which had previously been started with
641 641 %logstart. They will fail (with an explanation) if you try to use them
642 642 before logging has been started.
643 643
644 644 .. _system_shell_access:
645 645
646 646 System shell access
647 647 -------------------
648 648
649 649 Any input line beginning with a ! character is passed verbatim (minus
650 650 the !, of course) to the underlying operating system. For example,
651 651 typing !ls will run 'ls' in the current directory.
652 652
653 653 Manual capture of command output
654 654 --------------------------------
655 655
656 656 If the input line begins with two exclamation marks, !!, the command is
657 657 executed but its output is captured and returned as a python list, split
658 658 on newlines. Any output sent by the subprocess to standard error is
659 659 printed separately, so that the resulting list only captures standard
660 660 output. The !! syntax is a shorthand for the %sx magic command.
661 661
662 662 Finally, the %sc magic (short for 'shell capture') is similar to %sx,
663 663 but allowing more fine-grained control of the capture details, and
664 664 storing the result directly into a named variable. The direct use of
665 665 %sc is now deprecated, and you should ise the ``var = !cmd`` syntax
666 666 instead.
667 667
668 668 IPython also allows you to expand the value of python variables when
669 669 making system calls. Any python variable or expression which you prepend
670 670 with $ will get expanded before the system call is made::
671 671
672 672 In [1]: pyvar='Hello world'
673 673 In [2]: !echo "A python variable: $pyvar"
674 674 A python variable: Hello world
675 675
676 676 If you want the shell to actually see a literal $, you need to type it
677 677 twice::
678 678
679 679 In [3]: !echo "A system variable: $$HOME"
680 680 A system variable: /home/fperez
681 681
682 682 You can pass arbitrary expressions, though you'll need to delimit them
683 683 with {} if there is ambiguity as to the extent of the expression::
684 684
685 685 In [5]: x=10
686 686 In [6]: y=20
687 687 In [13]: !echo $x+y
688 688 10+y
689 689 In [7]: !echo ${x+y}
690 690 30
691 691
692 692 Even object attributes can be expanded::
693 693
694 694 In [12]: !echo $sys.argv
695 695 [/home/fperez/usr/bin/ipython]
696 696
697 697
698 698 System command aliases
699 699 ----------------------
700 700
701 701 The %alias magic function and the alias option in the ipythonrc
702 702 configuration file allow you to define magic functions which are in fact
703 703 system shell commands. These aliases can have parameters.
704 704
705 705 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
706 706
707 707 Then, typing '%alias_name params' will execute the system command 'cmd
708 708 params' (from your underlying operating system).
709 709
710 710 You can also define aliases with parameters using %s specifiers (one per
711 711 parameter). The following example defines the %parts function as an
712 712 alias to the command 'echo first %s second %s' where each %s will be
713 713 replaced by a positional parameter to the call to %parts::
714 714
715 715 In [1]: alias parts echo first %s second %s
716 716 In [2]: %parts A B
717 717 first A second B
718 718 In [3]: %parts A
719 719 Incorrect number of arguments: 2 expected.
720 720 parts is an alias to: 'echo first %s second %s'
721 721
722 722 If called with no parameters, %alias prints the table of currently
723 723 defined aliases.
724 724
725 725 The %rehash/rehashx magics allow you to load your entire $PATH as
726 726 ipython aliases. See their respective docstrings (or sec. 6.2
727 727 <#sec:magic> for further details).
728 728
729 729
730 730 .. _dreload:
731 731
732 732 Recursive reload
733 733 ----------------
734 734
735 735 The dreload function does a recursive reload of a module: changes made
736 736 to the module since you imported will actually be available without
737 737 having to exit.
738 738
739 739
740 740 Verbose and colored exception traceback printouts
741 741 -------------------------------------------------
742 742
743 743 IPython provides the option to see very detailed exception tracebacks,
744 744 which can be especially useful when debugging large programs. You can
745 745 run any Python file with the %run function to benefit from these
746 746 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
747 747 be colored (if your terminal supports it) which makes them much easier
748 748 to parse visually.
749 749
750 750 See the magic xmode and colors functions for details (just type %magic).
751 751
752 752 These features are basically a terminal version of Ka-Ping Yee's cgitb
753 753 module, now part of the standard Python library.
754 754
755 755
756 756 .. _input_caching:
757 757
758 758 Input caching system
759 759 --------------------
760 760
761 761 IPython offers numbered prompts (In/Out) with input and output caching
762 762 (also referred to as 'input history'). All input is saved and can be
763 763 retrieved as variables (besides the usual arrow key recall), in
764 764 addition to the %rep magic command that brings a history entry
765 765 up for editing on the next command line.
766 766
767 767 The following GLOBAL variables always exist (so don't overwrite them!):
768 768 _i: stores previous input. _ii: next previous. _iii: next-next previous.
769 769 _ih : a list of all input _ih[n] is the input from line n and this list
770 770 is aliased to the global variable In. If you overwrite In with a
771 771 variable of your own, you can remake the assignment to the internal list
772 772 with a simple 'In=_ih'.
773 773
774 774 Additionally, global variables named _i<n> are dynamically created (<n>
775 775 being the prompt counter), such that
776 776 _i<n> == _ih[<n>] == In[<n>].
777 777
778 778 For example, what you typed at prompt 14 is available as _i14, _ih[14]
779 779 and In[14].
780 780
781 781 This allows you to easily cut and paste multi line interactive prompts
782 782 by printing them out: they print like a clean string, without prompt
783 783 characters. You can also manipulate them like regular variables (they
784 784 are strings), modify or exec them (typing 'exec _i9' will re-execute the
785 785 contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines
786 786 9 through 13 and line 18).
787 787
788 788 You can also re-execute multiple lines of input easily by using the
789 789 magic %macro function (which automates the process and allows
790 790 re-execution without having to type 'exec' every time). The macro system
791 791 also allows you to re-execute previous lines which include magic
792 792 function calls (which require special processing). Type %macro? or see
793 793 sec. 6.2 <#sec:magic> for more details on the macro system.
794 794
795 795 A history function %hist allows you to see any part of your input
796 796 history by printing a range of the _i variables.
797 797
798 798 You can also search ('grep') through your history by typing
799 799 '%hist -g somestring'. This also searches through the so called *shadow history*,
800 800 which remembers all the commands (apart from multiline code blocks)
801 801 you have ever entered. Handy for searching for svn/bzr URL's, IP adrresses
802 802 etc. You can bring shadow history entries listed by '%hist -g' up for editing
803 803 (or re-execution by just pressing ENTER) with %rep command. Shadow history
804 804 entries are not available as _iNUMBER variables, and they are identified by
805 805 the '0' prefix in %hist -g output. That is, history entry 12 is a normal
806 806 history entry, but 0231 is a shadow history entry.
807 807
808 808 Shadow history was added because the readline history is inherently very
809 809 unsafe - if you have multiple IPython sessions open, the last session
810 810 to close will overwrite the history of previountly closed session. Likewise,
811 811 if a crash occurs, history is never saved, whereas shadow history entries
812 812 are added after entering every command (so a command executed
813 813 in another IPython session is immediately available in other IPython
814 814 sessions that are open).
815 815
816 816 To conserve space, a command can exist in shadow history only once - it doesn't
817 817 make sense to store a common line like "cd .." a thousand times. The idea is
818 818 mainly to provide a reliable place where valuable, hard-to-remember commands can
819 819 always be retrieved, as opposed to providing an exact sequence of commands
820 820 you have entered in actual order.
821 821
822 822 Because shadow history has all the commands you have ever executed,
823 823 time taken by %hist -g will increase oven time. If it ever starts to take
824 824 too long (or it ends up containing sensitive information like passwords),
825 825 clear the shadow history by `%clear shadow_nuke`.
826 826
827 827 Time taken to add entries to shadow history should be negligible, but
828 828 in any case, if you start noticing performance degradation after using
829 829 IPython for a long time (or running a script that floods the shadow history!),
830 830 you can 'compress' the shadow history by executing
831 831 `%clear shadow_compress`. In practice, this should never be necessary
832 832 in normal use.
833 833
834 834 .. _output_caching:
835 835
836 836 Output caching system
837 837 ---------------------
838 838
839 839 For output that is returned from actions, a system similar to the input
840 840 cache exists but using _ instead of _i. Only actions that produce a
841 841 result (NOT assignments, for example) are cached. If you are familiar
842 842 with Mathematica, IPython's _ variables behave exactly like
843 843 Mathematica's % variables.
844 844
845 845 The following GLOBAL variables always exist (so don't overwrite them!):
846 846
847 847 * [_] (a single underscore) : stores previous output, like Python's
848 848 default interpreter.
849 849 * [__] (two underscores): next previous.
850 850 * [___] (three underscores): next-next previous.
851 851
852 852 Additionally, global variables named _<n> are dynamically created (<n>
853 853 being the prompt counter), such that the result of output <n> is always
854 854 available as _<n> (don't use the angle brackets, just the number, e.g.
855 855 _21).
856 856
857 857 These global variables are all stored in a global dictionary (not a
858 858 list, since it only has entries for lines which returned a result)
859 859 available under the names _oh and Out (similar to _ih and In). So the
860 860 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
861 861 accidentally overwrite the Out variable you can recover it by typing
862 862 'Out=_oh' at the prompt.
863 863
864 864 This system obviously can potentially put heavy memory demands on your
865 865 system, since it prevents Python's garbage collector from removing any
866 866 previously computed results. You can control how many results are kept
867 867 in memory with the option (at the command line or in your ipythonrc
868 868 file) cache_size. If you set it to 0, the whole system is completely
869 869 disabled and the prompts revert to the classic '>>>' of normal Python.
870 870
871 871
872 872 Directory history
873 873 -----------------
874 874
875 875 Your history of visited directories is kept in the global list _dh, and
876 876 the magic %cd command can be used to go to any entry in that list. The
877 877 %dhist command allows you to view this history. Do ``cd -<TAB`` to
878 878 conveniently view the directory history.
879 879
880 880
881 881 Automatic parentheses and quotes
882 882 --------------------------------
883 883
884 884 These features were adapted from Nathan Gray's LazyPython. They are
885 885 meant to allow less typing for common situations.
886 886
887 887
888 888 Automatic parentheses
889 889 ---------------------
890 890
891 891 Callable objects (i.e. functions, methods, etc) can be invoked like this
892 892 (notice the commas between the arguments)::
893 893
894 894 >>> callable_ob arg1, arg2, arg3
895 895
896 896 and the input will be translated to this::
897 897
898 898 -> callable_ob(arg1, arg2, arg3)
899 899
900 900 You can force automatic parentheses by using '/' as the first character
901 901 of a line. For example::
902 902
903 903 >>> /globals # becomes 'globals()'
904 904
905 905 Note that the '/' MUST be the first character on the line! This won't work::
906 906
907 907 >>> print /globals # syntax error
908 908
909 909 In most cases the automatic algorithm should work, so you should rarely
910 910 need to explicitly invoke /. One notable exception is if you are trying
911 911 to call a function with a list of tuples as arguments (the parenthesis
912 912 will confuse IPython)::
913 913
914 914 In [1]: zip (1,2,3),(4,5,6) # won't work
915 915
916 916 but this will work::
917 917
918 918 In [2]: /zip (1,2,3),(4,5,6)
919 919 ---> zip ((1,2,3),(4,5,6))
920 920 Out[2]= [(1, 4), (2, 5), (3, 6)]
921 921
922 922 IPython tells you that it has altered your command line by displaying
923 923 the new command line preceded by ->. e.g.::
924 924
925 925 In [18]: callable list
926 926 ----> callable (list)
927 927
928 928
929 929 Automatic quoting
930 930 -----------------
931 931
932 932 You can force automatic quoting of a function's arguments by using ','
933 933 or ';' as the first character of a line. For example::
934 934
935 935 >>> ,my_function /home/me # becomes my_function("/home/me")
936 936
937 937 If you use ';' instead, the whole argument is quoted as a single string
938 938 (while ',' splits on whitespace)::
939 939
940 940 >>> ,my_function a b c # becomes my_function("a","b","c")
941 941
942 942 >>> ;my_function a b c # becomes my_function("a b c")
943 943
944 944 Note that the ',' or ';' MUST be the first character on the line! This
945 945 won't work::
946 946
947 947 >>> x = ,my_function /home/me # syntax error
948 948
949 949 IPython as your default Python environment
950 950 ==========================================
951 951
952 952 Python honors the environment variable PYTHONSTARTUP and will execute at
953 953 startup the file referenced by this variable. If you put at the end of
954 954 this file the following two lines of code::
955 955
956 956 from IPython.frontend.terminal.ipapp import launch_new_instance
957 957 launch_new_instance()
958 958 raise SystemExit
959 959
960 960 then IPython will be your working environment anytime you start Python.
961 961 The ``raise SystemExit`` is needed to exit Python when
962 962 it finishes, otherwise you'll be back at the normal Python '>>>'
963 963 prompt.
964 964
965 965 This is probably useful to developers who manage multiple Python
966 966 versions and don't want to have correspondingly multiple IPython
967 967 versions. Note that in this mode, there is no way to pass IPython any
968 968 command-line options, as those are trapped first by Python itself.
969 969
970 970 .. _Embedding:
971 971
972 972 Embedding IPython
973 973 =================
974 974
975 975 It is possible to start an IPython instance inside your own Python
976 976 programs. This allows you to evaluate dynamically the state of your
977 977 code, operate with your variables, analyze them, etc. Note however that
978 978 any changes you make to values while in the shell do not propagate back
979 979 to the running code, so it is safe to modify your values because you
980 980 won't break your code in bizarre ways by doing so.
981 981
982 982 This feature allows you to easily have a fully functional python
983 983 environment for doing object introspection anywhere in your code with a
984 984 simple function call. In some cases a simple print statement is enough,
985 985 but if you need to do more detailed analysis of a code fragment this
986 986 feature can be very valuable.
987 987
988 988 It can also be useful in scientific computing situations where it is
989 989 common to need to do some automatic, computationally intensive part and
990 990 then stop to look at data, plots, etc.
991 991 Opening an IPython instance will give you full access to your data and
992 992 functions, and you can resume program execution once you are done with
993 993 the interactive part (perhaps to stop again later, as many times as
994 994 needed).
995 995
996 996 The following code snippet is the bare minimum you need to include in
997 997 your Python programs for this to work (detailed examples follow later)::
998 998
999 999 from IPython import embed
1000 1000
1001 1001 embed() # this call anywhere in your program will start IPython
1002 1002
1003 1003 You can run embedded instances even in code which is itself being run at
1004 1004 the IPython interactive prompt with '%run <filename>'. Since it's easy
1005 1005 to get lost as to where you are (in your top-level IPython or in your
1006 1006 embedded one), it's a good idea in such cases to set the in/out prompts
1007 1007 to something different for the embedded instances. The code examples
1008 1008 below illustrate this.
1009 1009
1010 1010 You can also have multiple IPython instances in your program and open
1011 1011 them separately, for example with different options for data
1012 1012 presentation. If you close and open the same instance multiple times,
1013 1013 its prompt counters simply continue from each execution to the next.
1014 1014
1015 1015 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
1016 1016 module for more details on the use of this system.
1017 1017
1018 1018 The following sample file illustrating how to use the embedding
1019 1019 functionality is provided in the examples directory as example-embed.py.
1020 1020 It should be fairly self-explanatory:
1021 1021
1022 1022 .. literalinclude:: ../../examples/core/example-embed.py
1023 1023 :language: python
1024 1024
1025 1025 Once you understand how the system functions, you can use the following
1026 1026 code fragments in your programs which are ready for cut and paste:
1027 1027
1028 1028 .. literalinclude:: ../../examples/core/example-embed-short.py
1029 1029 :language: python
1030 1030
1031 1031 Using the Python debugger (pdb)
1032 1032 ===============================
1033 1033
1034 1034 Running entire programs via pdb
1035 1035 -------------------------------
1036 1036
1037 1037 pdb, the Python debugger, is a powerful interactive debugger which
1038 1038 allows you to step through code, set breakpoints, watch variables,
1039 1039 etc. IPython makes it very easy to start any script under the control
1040 1040 of pdb, regardless of whether you have wrapped it into a 'main()'
1041 1041 function or not. For this, simply type '%run -d myscript' at an
1042 1042 IPython prompt. See the %run command's documentation (via '%run?' or
1043 1043 in Sec. magic_ for more details, including how to control where pdb
1044 1044 will stop execution first.
1045 1045
1046 1046 For more information on the use of the pdb debugger, read the included
1047 1047 pdb.doc file (part of the standard Python distribution). On a stock
1048 1048 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
1049 1049 easiest way to read it is by using the help() function of the pdb module
1050 1050 as follows (in an IPython prompt)::
1051 1051
1052 1052 In [1]: import pdb
1053 1053 In [2]: pdb.help()
1054 1054
1055 1055 This will load the pdb.doc document in a file viewer for you automatically.
1056 1056
1057 1057
1058 1058 Automatic invocation of pdb on exceptions
1059 1059 -----------------------------------------
1060 1060
1061 1061 IPython, if started with the -pdb option (or if the option is set in
1062 1062 your rc file) can call the Python pdb debugger every time your code
1063 1063 triggers an uncaught exception. This feature
1064 1064 can also be toggled at any time with the %pdb magic command. This can be
1065 1065 extremely useful in order to find the origin of subtle bugs, because pdb
1066 1066 opens up at the point in your code which triggered the exception, and
1067 1067 while your program is at this point 'dead', all the data is still
1068 1068 available and you can walk up and down the stack frame and understand
1069 1069 the origin of the problem.
1070 1070
1071 1071 Furthermore, you can use these debugging facilities both with the
1072 1072 embedded IPython mode and without IPython at all. For an embedded shell
1073 1073 (see sec. Embedding_), simply call the constructor with
1074 1074 '--pdb' in the argument string and automatically pdb will be called if an
1075 1075 uncaught exception is triggered by your code.
1076 1076
1077 1077 For stand-alone use of the feature in your programs which do not use
1078 1078 IPython at all, put the following lines toward the top of your 'main'
1079 1079 routine::
1080 1080
1081 1081 import sys
1082 1082 from IPython.core import ultratb
1083 1083 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
1084 1084 color_scheme='Linux', call_pdb=1)
1085 1085
1086 1086 The mode keyword can be either 'Verbose' or 'Plain', giving either very
1087 1087 detailed or normal tracebacks respectively. The color_scheme keyword can
1088 1088 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
1089 1089 options which can be set in IPython with -colors and -xmode.
1090 1090
1091 1091 This will give any of your programs detailed, colored tracebacks with
1092 1092 automatic invocation of pdb.
1093 1093
1094 1094
1095 1095 Extensions for syntax processing
1096 1096 ================================
1097 1097
1098 1098 This isn't for the faint of heart, because the potential for breaking
1099 1099 things is quite high. But it can be a very powerful and useful feature.
1100 1100 In a nutshell, you can redefine the way IPython processes the user input
1101 1101 line to accept new, special extensions to the syntax without needing to
1102 1102 change any of IPython's own code.
1103 1103
1104 1104 In the IPython/extensions directory you will find some examples
1105 1105 supplied, which we will briefly describe now. These can be used 'as is'
1106 1106 (and both provide very useful functionality), or you can use them as a
1107 1107 starting point for writing your own extensions.
1108 1108
1109 1109
1110 1110 Pasting of code starting with '>>> ' or '... '
1111 1111 ----------------------------------------------
1112 1112
1113 1113 In the python tutorial it is common to find code examples which have
1114 1114 been taken from real python sessions. The problem with those is that all
1115 1115 the lines begin with either '>>> ' or '... ', which makes it impossible
1116 1116 to paste them all at once. One must instead do a line by line manual
1117 1117 copying, carefully removing the leading extraneous characters.
1118 1118
1119 1119 This extension identifies those starting characters and removes them
1120 1120 from the input automatically, so that one can paste multi-line examples
1121 1121 directly into IPython, saving a lot of time. Please look at the file
1122 1122 InterpreterPasteInput.py in the IPython/extensions directory for details
1123 1123 on how this is done.
1124 1124
1125 1125 IPython comes with a special profile enabling this feature, called
1126 1126 tutorial. Simply start IPython via 'ipython -p tutorial' and the feature
1127 1127 will be available. In a normal IPython session you can activate the
1128 1128 feature by importing the corresponding module with:
1129 1129 In [1]: import IPython.extensions.InterpreterPasteInput
1130 1130
1131 1131 The following is a 'screenshot' of how things work when this extension
1132 1132 is on, copying an example from the standard tutorial::
1133 1133
1134 1134 IPython profile: tutorial
1135 1135
1136 1136 *** Pasting of code with ">>>" or "..." has been enabled.
1137 1137
1138 1138 In [1]: >>> def fib2(n): # return Fibonacci series up to n
1139 1139 ...: ... """Return a list containing the Fibonacci series up to
1140 1140 n."""
1141 1141 ...: ... result = []
1142 1142 ...: ... a, b = 0, 1
1143 1143 ...: ... while b < n:
1144 1144 ...: ... result.append(b) # see below
1145 1145 ...: ... a, b = b, a+b
1146 1146 ...: ... return result
1147 1147 ...:
1148 1148
1149 1149 In [2]: fib2(10)
1150 1150 Out[2]: [1, 1, 2, 3, 5, 8]
1151 1151
1152 1152 Note that as currently written, this extension does not recognize
1153 1153 IPython's prompts for pasting. Those are more complicated, since the
1154 1154 user can change them very easily, they involve numbers and can vary in
1155 1155 length. One could however extract all the relevant information from the
1156 1156 IPython instance and build an appropriate regular expression. This is
1157 1157 left as an exercise for the reader.
1158 1158
1159 1159
1160 1160 Input of physical quantities with units
1161 1161 ---------------------------------------
1162 1162
1163 1163 The module PhysicalQInput allows a simplified form of input for physical
1164 1164 quantities with units. This file is meant to be used in conjunction with
1165 1165 the PhysicalQInteractive module (in the same directory) and
1166 1166 Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython
1167 1167 (http://dirac.cnrs-orleans.fr/ScientificPython/).
1168 1168
1169 1169 The Physics.PhysicalQuantities module defines PhysicalQuantity objects,
1170 1170 but these must be declared as instances of a class. For example, to
1171 1171 define v as a velocity of 3 m/s, normally you would write::
1172 1172
1173 1173 In [1]: v = PhysicalQuantity(3,'m/s')
1174 1174
1175 1175 Using the PhysicalQ_Input extension this can be input instead as:
1176 1176 In [1]: v = 3 m/s
1177 1177 which is much more convenient for interactive use (even though it is
1178 1178 blatantly invalid Python syntax).
1179 1179
1180 1180 The physics profile supplied with IPython (enabled via 'ipython -p
1181 1181 physics') uses these extensions, which you can also activate with:
1182 1182
1183 1183 from math import * # math MUST be imported BEFORE PhysicalQInteractive
1184 1184 from IPython.extensions.PhysicalQInteractive import *
1185 1185 import IPython.extensions.PhysicalQInput
1186 1186
1187 1187 .. _gui_support:
1188 1188
1189 1189 GUI event loop support support
1190 1190 ==============================
1191 1191
1192 1192 .. versionadded:: 0.11
1193 1193 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
1194 1194
1195 1195 IPython has excellent support for working interactively with Graphical User
1196 1196 Interface (GUI) toolkits, such as wxPython, PyQt4, PyGTK and Tk. This is
1197 1197 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
1198 1198 is extremely robust compared to our previous threaded based version. The
1199 1199 advantages of this are:
1200 1200
1201 1201 * GUIs can be enabled and disabled dynamically at runtime.
1202 1202 * The active GUI can be switched dynamically at runtime.
1203 1203 * In some cases, multiple GUIs can run simultaneously with no problems.
1204 1204 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
1205 1205 all of these things.
1206 1206
1207 1207 For users, enabling GUI event loop integration is simple. You simple use the
1208 1208 ``%gui`` magic as follows::
1209 1209
1210 1210 %gui [-a] [GUINAME]
1211 1211
1212 1212 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
1213 1213 arguments are ``wx``, ``qt4``, ``gtk`` and ``tk``. The ``-a`` option will
1214 1214 create and return a running application object for the selected GUI toolkit.
1215 1215
1216 1216 Thus, to use wxPython interactively and create a running :class:`wx.App`
1217 1217 object, do::
1218 1218
1219 1219 %gui -a wx
1220 1220
1221 1221 For information on IPython's Matplotlib integration (and the ``pylab`` mode)
1222 1222 see :ref:`this section <matplotlib_support>`.
1223 1223
1224 1224 For developers that want to use IPython's GUI event loop integration in
1225 1225 the form of a library, these capabilities are exposed in library form
1226 1226 in the :mod:`IPython.lib.inputhook`. Interested developers should see the
1227 1227 module docstrings for more information, but there are a few points that
1228 1228 should be mentioned here.
1229 1229
1230 1230 First, the ``PyOSInputHook`` approach only works in command line settings
1231 1231 where readline is activated.
1232 1232
1233 1233 Second, when using the ``PyOSInputHook`` approach, a GUI application should
1234 1234 *not* start its event loop. Instead all of this is handled by the
1235 1235 ``PyOSInputHook``. This means that applications that are meant to be used both
1236 1236 in IPython and as standalone apps need to have special code to detects how the
1237 1237 application is being run. We highly recommend using IPython's
1238 1238 :func:`enable_foo` functions for this. Here is a simple example that shows the
1239 1239 recommended code that should be at the bottom of a wxPython using GUI
1240 1240 application::
1241 1241
1242 1242 try:
1243 1243 from IPython.lib.inputhook import enable_wx
1244 1244 enable_wx(app)
1245 1245 except ImportError:
1246 1246 app.MainLoop()
1247 1247
1248 1248 This pattern should be used instead of the simple ``app.MainLoop()`` code
1249 1249 that a standalone wxPython application would have.
1250 1250
1251 1251 Third, unlike previous versions of IPython, we no longer "hijack" (replace
1252 1252 them with no-ops) the event loops. This is done to allow applications that
1253 1253 actually need to run the real event loops to do so. This is often needed to
1254 1254 process pending events at critical points.
1255 1255
1256 1256 Finally, we also have a number of examples in our source directory
1257 1257 :file:`docs/examples/lib` that demonstrate these capabilities.
1258 1258
1259 1259 PyQt and PySide
1260 1260 ---------------
1261 1261
1262 1262 .. attempt at explanation of the complete mess that is Qt support
1263 1263
1264 1264 When you use ``gui=qt`` or ``pylab=qt``, IPython can work with either
1265 1265 PyQt4 or PySide. There are three options for configuration here, because
1266 1266 PyQt4 has two APIs for QString and QVariant - v1, which is the default on
1267 1267 Python 2, and the more natural v2, which is the only API supported by PySide.
1268 1268 v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole
1269 1269 uses v2, but you can still use any interface in your code, since the
1270 1270 Qt frontend is in a different process.
1271 1271
1272 If you launch IPython in pylab mode with ``ipython pylab=qt``, then IPython
1273 will ask matplotlib which Qt library to use, via the 'backend.qt4' rcParam.
1274 If matplotlib is version 1.0.1 or older, then IPython will always use PyQt4
1275 without setting the v2 APIs.
1276
1277 If you just integrate the Qt event loop with ``ipython gui=qt``, then IPython
1278 has a few more possibilities. The default will be to import PyQt4 without
1279 configuration of the APIs, thus matching what most applications would expect.
1280 It will fall back of PySide if PyQt4 is unavailable.
1272 The default will be to import PyQt4 without configuration of the APIs, thus
1273 matching what most applications would expect. It will fall back of PySide if
1274 PyQt4 is unavailable.
1281 1275
1282 1276 If specified, IPython will respect the environment variable ``QT_API`` used
1283 1277 by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires
1284 PyQt4 to use the v2 API. So if ``QT_API=pyside`` PySide will be used,
1285 and if ``QT_API=pyqt`` then PyQt4 will be used with the v2 API for
1278 PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used,
1279 and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for
1286 1280 QString and QVariant, so ETS codes like MayaVi will also work with IPython.
1287 1281
1282 If you launch IPython in pylab mode with ``ipython pylab=qt``, then IPython
1283 will ask matplotlib which Qt library to use (only if QT_API is *not set*),
1284 via the 'backend.qt4' rcParam.
1285 If matplotlib is version 1.0.1 or older, then IPython will always use PyQt4
1286 without setting the v2 APIs, since neither v2 PyQt nor PySide work.
1287
1288 1288 .. warning::
1289 1289
1290 Note that this means for ETS to work with PyQt4, ``QT_API`` *must* be set to
1290 Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set to
1291 1291 work with IPython's qt integration, because otherwise PyQt4 will be loaded in
1292 1292 an incompatible mode.
1293 1293
1294 It also means that you must not have ``QT_API`` set if you want to
1294 It also means that you must *not* have ``QT_API`` set if you want to
1295 1295 use ``gui=qt`` with code that requires PyQt4 API v1.
1296 1296
1297 1297
1298 1298
1299 1299 .. _matplotlib_support:
1300 1300
1301 1301 Plotting with matplotlib
1302 1302 ========================
1303 1303
1304 1304
1305 1305 `Matplotlib`_ provides high quality 2D and
1306 1306 3D plotting for Python. Matplotlib can produce plots on screen using a variety
1307 1307 of GUI toolkits, including Tk, PyGTK, PyQt4 and wxPython. It also provides a
1308 1308 number of commands useful for scientific computing, all with a syntax
1309 1309 compatible with that of the popular Matlab program.
1310 1310
1311 1311 Many IPython users have come to rely on IPython's ``-pylab`` mode which
1312 1312 automates the integration of Matplotlib with IPython. We are still in the
1313 1313 process of working with the Matplotlib developers to finalize the new pylab
1314 1314 API, but for now you can use Matplotlib interactively using the following
1315 1315 commands::
1316 1316
1317 1317 %gui -a wx
1318 1318 import matplotlib
1319 1319 matplotlib.use('wxagg')
1320 1320 from matplotlib import pylab
1321 1321 pylab.interactive(True)
1322 1322
1323 1323 All of this will soon be automated as Matplotlib begins to include
1324 1324 new logic that uses our new GUI support.
1325 1325
1326 1326 .. _Matplotlib: http://matplotlib.sourceforge.net
1327 1327
1328 1328 .. _interactive_demos:
1329 1329
1330 1330 Interactive demos with IPython
1331 1331 ==============================
1332 1332
1333 1333 IPython ships with a basic system for running scripts interactively in
1334 1334 sections, useful when presenting code to audiences. A few tags embedded
1335 1335 in comments (so that the script remains valid Python code) divide a file
1336 1336 into separate blocks, and the demo can be run one block at a time, with
1337 1337 IPython printing (with syntax highlighting) the block before executing
1338 1338 it, and returning to the interactive prompt after each block. The
1339 1339 interactive namespace is updated after each block is run with the
1340 1340 contents of the demo's namespace.
1341 1341
1342 1342 This allows you to show a piece of code, run it and then execute
1343 1343 interactively commands based on the variables just created. Once you
1344 1344 want to continue, you simply execute the next block of the demo. The
1345 1345 following listing shows the markup necessary for dividing a script into
1346 1346 sections for execution as a demo:
1347 1347
1348 1348 .. literalinclude:: ../../examples/lib/example-demo.py
1349 1349 :language: python
1350 1350
1351 1351
1352 1352 In order to run a file as a demo, you must first make a Demo object out
1353 1353 of it. If the file is named myscript.py, the following code will make a
1354 1354 demo::
1355 1355
1356 1356 from IPython.lib.demo import Demo
1357 1357
1358 1358 mydemo = Demo('myscript.py')
1359 1359
1360 1360 This creates the mydemo object, whose blocks you run one at a time by
1361 1361 simply calling the object with no arguments. If you have autocall active
1362 1362 in IPython (the default), all you need to do is type::
1363 1363
1364 1364 mydemo
1365 1365
1366 1366 and IPython will call it, executing each block. Demo objects can be
1367 1367 restarted, you can move forward or back skipping blocks, re-execute the
1368 1368 last block, etc. Simply use the Tab key on a demo object to see its
1369 1369 methods, and call '?' on them to see their docstrings for more usage
1370 1370 details. In addition, the demo module itself contains a comprehensive
1371 1371 docstring, which you can access via::
1372 1372
1373 1373 from IPython.lib import demo
1374 1374
1375 1375 demo?
1376 1376
1377 1377 Limitations: It is important to note that these demos are limited to
1378 1378 fairly simple uses. In particular, you can not put division marks in
1379 1379 indented code (loops, if statements, function definitions, etc.)
1380 1380 Supporting something like this would basically require tracking the
1381 1381 internal execution state of the Python interpreter, so only top-level
1382 1382 divisions are allowed. If you want to be able to open an IPython
1383 1383 instance at an arbitrary point in a program, you can use IPython's
1384 1384 embedding facilities, described in detail in Sec. 9
1385 1385
General Comments 0
You need to be logged in to leave comments. Login now