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