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