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