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