##// END OF EJS Templates
Merge pull request #7822 from mspacek/master...
Min RK -
r20473:450bb8a8 merge
parent child Browse files
Show More
@@ -1,654 +1,654 b''
1 1 .. _qtconsole:
2 2
3 3 =========================
4 4 A Qt Console for IPython
5 5 =========================
6 6
7 7 To start the Qt Console::
8 8
9 9 $> ipython qtconsole
10 10
11 11 We now have a version of IPython, using the new two-process :ref:`ZeroMQ Kernel
12 12 <ipythonzmq>`, running in a PyQt_ GUI. This is a very lightweight widget that
13 13 largely feels like a terminal, but provides a number of enhancements only
14 14 possible in a GUI, such as inline figures, proper multiline editing with syntax
15 15 highlighting, graphical calltips, and much more.
16 16
17 17 .. figure:: ../_images/qtconsole.png
18 18 :width: 400px
19 19 :alt: IPython Qt console with embedded plots
20 20 :align: center
21 21 :target: ../_images/qtconsole.png
22 22
23 23 The Qt console for IPython, using inline matplotlib plots.
24 24
25 25 To get acquainted with the Qt console, type `%guiref` to see a quick
26 26 introduction of its main features.
27 27
28 28 The Qt frontend has hand-coded emacs-style bindings for text navigation. This
29 29 is not yet configurable.
30 30
31 31 .. tip::
32 32
33 33 Since the Qt console tries hard to behave like a terminal, by default it
34 34 immediately executes single lines of input that are complete. If you want
35 35 to force multiline input, hit :kbd:`Ctrl-Enter` at the end of the first line
36 36 instead of :kbd:`Enter`, and it will open a new line for input. At any
37 37 point in a multiline block, you can force its execution (without having to
38 38 go to the bottom) with :kbd:`Shift-Enter`.
39 39
40 40 ``%load``
41 41 =========
42 42
43 43 The new ``%load`` magic (previously ``%loadpy``) takes any script, and pastes
44 44 its contents as your next input, so you can edit it before executing. The
45 45 script may be on your machine, but you can also specify an history range, or a
46 46 url, and it will download the script from the web. This is particularly useful
47 47 for playing with examples from documentation, such as matplotlib.
48 48
49 49 .. sourcecode:: ipython
50 50
51 51 In [6]: %load http://matplotlib.org/plot_directive/mpl_examples/mplot3d/contour3d_demo.py
52 52
53 53 In [7]: from mpl_toolkits.mplot3d import axes3d
54 54 ...: import matplotlib.pyplot as plt
55 55 ...:
56 56 ...: fig = plt.figure()
57 57 ...: ax = fig.add_subplot(111, projection='3d')
58 58 ...: X, Y, Z = axes3d.get_test_data(0.05)
59 59 ...: cset = ax.contour(X, Y, Z)
60 60 ...: ax.clabel(cset, fontsize=9, inline=1)
61 61 ...:
62 62 ...: plt.show()
63 63
64 64 The ``%load`` magic can also load source code from objects in the user or
65 65 global namespace by invoking the ``-n`` option.
66 66
67 67 .. sourcecode:: ipython
68 68
69 69 In [1]: import hello_world
70 70 ...: %load -n hello_world.say_hello
71 71
72 72 In [3]: def say_hello() :
73 73 ...: print("Hello World!")
74 74
75 75 Inline Matplotlib
76 76 =================
77 77
78 78 One of the most exciting features of the QtConsole is embedded matplotlib
79 79 figures. You can use any standard matplotlib GUI backend
80 80 to draw the figures, and since there is now a two-process model, there is no
81 81 longer a conflict between user input and the drawing eventloop.
82 82
83 83 .. image:: figs/besselj.png
84 84 :width: 519px
85 85
86 86 .. _display:
87 87
88 88 :func:`display`
89 89 ***************
90 90
91 91 IPython provides a function :func:`display` for displaying rich representations
92 92 of objects if they are available. The IPython display
93 93 system provides a mechanism for specifying PNG or SVG (and more)
94 94 representations of objects for GUI frontends.
95 95 When you enable matplotlib integration via the ``%matplotlib`` magic, IPython registers
96 96 convenient PNG and SVG renderers for matplotlib figures, so you can embed them
97 97 in your document by calling :func:`display` on one or more of them. This is
98 98 especially useful for saving_ your work.
99 99
100 100 .. sourcecode:: ipython
101 101
102 102 In [4]: from IPython.display import display
103 103
104 104 In [5]: plt.plot(range(5)) # plots in the matplotlib window
105 105
106 106 In [6]: display(plt.gcf()) # embeds the current figure in the qtconsole
107 107
108 108 In [7]: display(*getfigs()) # embeds all active figures in the qtconsole
109 109
110 110 If you have a reference to a matplotlib figure object, you can always display
111 111 that specific figure:
112 112
113 113 .. sourcecode:: ipython
114 114
115 115 In [1]: f = plt.figure()
116 116
117 117 In [2]: plt.plot(np.rand(100))
118 118 Out[2]: [<matplotlib.lines.Line2D at 0x7fc6ac03dd90>]
119 119
120 120 In [3]: display(f)
121 121
122 122 # Plot is shown here
123 123
124 124 In [4]: plt.title('A title')
125 125 Out[4]: <matplotlib.text.Text at 0x7fc6ac023450>
126 126
127 127 In [5]: display(f)
128 128
129 129 # Updated plot with title is shown here.
130 130
131 131 .. _inline:
132 132
133 133 ``--matplotlib inline``
134 134 ***********************
135 135
136 136 If you want to have all of your figures embedded in your session, instead of
137 137 calling :func:`display`, you can specify ``--matplotlib inline`` when you start the
138 138 console, and each time you make a plot, it will show up in your document, as if
139 139 you had called :func:`display(fig)`.
140 140
141 141 The inline backend can use either SVG or PNG figures (PNG being the default).
142 142 It also supports the special key ``'retina'``, which is 2x PNG for high-DPI displays.
143 143 To switch between them, set the ``InlineBackend.figure_format`` configurable
144 144 in a config file, or via the ``%config`` magic:
145 145
146 146 .. sourcecode:: ipython
147 147
148 148 In [10]: %config InlineBackend.figure_format = 'svg'
149 149
150 150 .. note::
151 151
152 152 Changing the inline figure format also affects calls to :func:`display` above,
153 153 even if you are not using the inline backend for all figures.
154 154
155 155 By default, IPython closes all figures at the completion of each execution. This means you
156 156 don't have to manually close figures, which is less convenient when figures aren't attached
157 157 to windows with an obvious close button. It also means that the first matplotlib call in
158 158 each cell will always create a new figure:
159 159
160 160 .. sourcecode:: ipython
161 161
162 162 In [11]: plt.plot(range(100))
163 163 <single-line plot>
164 164
165 165 In [12]: plt.plot([1,3,2])
166 166 <another single-line plot>
167 167
168 168
169 169 However, it does prevent the list of active figures surviving from one input cell to the
170 170 next, so if you want to continue working with a figure, you must hold on to a reference to
171 171 it:
172 172
173 173 .. sourcecode:: ipython
174 174
175 175 In [11]: fig = gcf()
176 176 ....: fig.plot(rand(100))
177 177 <plot>
178 178 In [12]: fig.title('Random Title')
179 179 <redraw plot with title>
180 180
181 181 This behavior is controlled by the :attr:`InlineBackend.close_figures` configurable, and
182 182 if you set it to False, via %config or config file, then IPython will *not* close figures,
183 183 and tools like :func:`gcf`, :func:`gca`, :func:`getfigs` will behave the same as they
184 184 do with other backends. You will, however, have to manually close figures:
185 185
186 186 .. sourcecode:: ipython
187 187
188 188 # close all active figures:
189 189 In [13]: [ fig.close() for fig in getfigs() ]
190 190
191 191
192 192
193 193 .. _saving:
194 194
195 195 Saving and Printing
196 196 ===================
197 197
198 198 IPythonQt has the ability to save your current session, as either HTML or
199 199 XHTML. If you have been using :func:`display` or inline_ matplotlib, your figures
200 200 will be PNG in HTML, or inlined as SVG in XHTML. PNG images have the option to
201 201 be either in an external folder, as in many browsers' "Webpage, Complete"
202 202 option, or inlined as well, for a larger, but more portable file.
203 203
204 204 .. note::
205 205
206 206 Export to SVG+XHTML requires that you are using SVG figures, which is *not*
207 207 the default. To switch the inline figure format to use SVG during an active
208 208 session, do:
209 209
210 210 .. sourcecode:: ipython
211 211
212 212 In [10]: %config InlineBackend.figure_format = 'svg'
213 213
214 214 Or, you can add the same line (c.Inline... instead of %config Inline...) to
215 215 your config files.
216 216
217 217 This will only affect figures plotted after making this call
218 218
219 219
220 220 The widget also exposes the ability to print directly, via the default print
221 221 shortcut or context menu.
222 222
223 223
224 224 .. Note::
225 225
226 226 Saving is only available to richtext Qt widgets, which are used by default,
227 227 but if you pass the ``--plain`` flag, saving will not be available to you.
228 228
229 229
230 230 See these examples of :download:`png/html<figs/jn.html>` and
231 231 :download:`svg/xhtml <figs/jn.xhtml>` output. Note that syntax highlighting
232 232 does not survive export. This is a known issue, and is being investigated.
233 233
234 234
235 235 Colors and Highlighting
236 236 =======================
237 237
238 238 Terminal IPython has always had some coloring, but never syntax
239 239 highlighting. There are a few simple color choices, specified by the ``colors``
240 240 flag or ``%colors`` magic:
241 241
242 242 * LightBG for light backgrounds
243 243 * Linux for dark backgrounds
244 244 * NoColor for a simple colorless terminal
245 245
246 246 The Qt widget has full support for the ``colors`` flag used in the terminal shell.
247 247
248 248 The Qt widget, however, has full syntax highlighting as you type, handled by
249 249 the `pygments`_ library. The ``style`` argument exposes access to any style by
250 250 name that can be found by pygments, and there are several already
251 251 installed. The ``colors`` argument, if unspecified, will be guessed based on
252 252 the chosen style. Similarly, there are default styles associated with each
253 253 ``colors`` option.
254 254
255 255
256 256 Screenshot of ``ipython qtconsole --colors=linux``, which uses the 'monokai'
257 257 theme by default:
258 258
259 259 .. image:: figs/colors_dark.png
260 260 :width: 627px
261 261
262 262 .. Note::
263 263
264 264 Calling ``ipython qtconsole -h`` will show all the style names that
265 265 pygments can find on your system.
266 266
267 267 You can also pass the filename of a custom CSS stylesheet, if you want to do
268 268 your own coloring, via the ``stylesheet`` argument. The default LightBG
269 269 stylesheet:
270 270
271 271 .. sourcecode:: css
272 272
273 273 QPlainTextEdit, QTextEdit { background-color: white;
274 274 color: black ;
275 275 selection-background-color: #ccc}
276 276 .error { color: red; }
277 277 .in-prompt { color: navy; }
278 278 .in-prompt-number { font-weight: bold; }
279 279 .out-prompt { color: darkred; }
280 280 .out-prompt-number { font-weight: bold; }
281 281 /* .inverted is used to highlight selected completion */
282 282 .inverted { background-color: black ; color: white; }
283 283
284 284 Fonts
285 285 =====
286 286
287 287 The QtConsole has configurable via the ConsoleWidget. To change these, set the
288 288 ``font_family`` or ``font_size`` traits of the ConsoleWidget. For instance, to
289 289 use 9pt Anonymous Pro::
290 290
291 291 $> ipython qtconsole --ConsoleWidget.font_family="Anonymous Pro" --ConsoleWidget.font_size=9
292 292
293 293 Process Management
294 294 ==================
295 295
296 296 With the two-process ZMQ model, the frontend does not block input during
297 297 execution. This means that actions can be taken by the frontend while the
298 298 Kernel is executing, or even after it crashes. The most basic such command is
299 299 via 'Ctrl-.', which restarts the kernel. This can be done in the middle of a
300 300 blocking execution. The frontend can also know, via a heartbeat mechanism, that
301 301 the kernel has died. This means that the frontend can safely restart the
302 302 kernel.
303 303
304 304 .. _multiple_consoles:
305 305
306 306 Multiple Consoles
307 307 *****************
308 308
309 309 Since the Kernel listens on the network, multiple frontends can connect to it.
310 310 These do not have to all be qt frontends - any IPython frontend can connect and
311 311 run code. When you start ipython qtconsole, there will be an output line,
312 312 like::
313 313
314 314 [IPKernelApp] To connect another client to this kernel, use:
315 315 [IPKernelApp] --existing kernel-12345.json
316 316
317 317 Other frontends can connect to your kernel, and share in the execution. This is
318 318 great for collaboration. The ``--existing`` flag means connect to a kernel
319 319 that already exists. Starting other consoles
320 320 with that flag will not try to start their own kernel, but rather connect to
321 321 yours. :file:`kernel-12345.json` is a small JSON file with the ip, port, and
322 322 authentication information necessary to connect to your kernel. By default, this file
323 323 will be in your default profile's security directory. If it is somewhere else,
324 324 the output line will print the full path of the connection file, rather than
325 325 just its filename.
326 326
327 327 If you need to find the connection info to send, and don't know where your connection file
328 328 lives, there are a couple of ways to get it. If you are already running an IPython console
329 329 connected to the kernel, you can use the ``%connect_info`` magic to display the information
330 330 necessary to connect another frontend to the kernel.
331 331
332 332 .. sourcecode:: ipython
333 333
334 334 In [2]: %connect_info
335 335 {
336 336 "stdin_port":50255,
337 337 "ip":"127.0.0.1",
338 338 "hb_port":50256,
339 339 "key":"70be6f0f-1564-4218-8cda-31be40a4d6aa",
340 340 "shell_port":50253,
341 341 "iopub_port":50254
342 342 }
343 343
344 344 Paste the above JSON into a file, and connect with:
345 345 $> ipython <app> --existing <file>
346 346 or, if you are local, you can connect with just:
347 347 $> ipython <app> --existing kernel-12345.json
348 348 or even just:
349 349 $> ipython <app> --existing
350 350 if this is the most recent IPython session you have started.
351 351
352 352 Otherwise, you can find a connection file by name (and optionally profile) with
353 353 :func:`IPython.lib.kernel.find_connection_file`:
354 354
355 355 .. sourcecode:: bash
356 356
357 357 $> python -c "from IPython.lib.kernel import find_connection_file;\
358 358 print find_connection_file('kernel-12345.json')"
359 359 /home/you/.ipython/profile_default/security/kernel-12345.json
360 360
361 361 And if you are using a particular IPython profile:
362 362
363 363 .. sourcecode:: bash
364 364
365 365 $> python -c "from IPython.lib.kernel import find_connection_file;\
366 366 print find_connection_file('kernel-12345.json', profile='foo')"
367 367 /home/you/.ipython/profile_foo/security/kernel-12345.json
368 368
369 369 You can even launch a standalone kernel, and connect and disconnect Qt Consoles
370 370 from various machines. This lets you keep the same running IPython session
371 371 on your work machine (with matplotlib plots and everything), logging in from home,
372 372 cafΓ©s, etc.::
373 373
374 374 $> ipython kernel
375 375 [IPKernelApp] To connect another client to this kernel, use:
376 376 [IPKernelApp] --existing kernel-12345.json
377 377
378 378 This is actually exactly the same as the subprocess launched by the qtconsole, so
379 379 all the information about connecting to a standalone kernel is identical to that
380 380 of connecting to the kernel attached to a running console.
381 381
382 382 .. _kernel_security:
383 383
384 384 Security
385 385 --------
386 386
387 387 .. warning::
388 388
389 389 Since the ZMQ code currently has no encryption, listening on an
390 390 external-facing IP is dangerous. You are giving any computer that can see
391 391 you on the network the ability to connect to your kernel, and view your traffic.
392 392 Read the rest of this section before listening on external ports
393 393 or running an IPython kernel on a shared machine.
394 394
395 395 By default (for security reasons), the kernel only listens on localhost, so you
396 396 can only connect multiple frontends to the kernel from your local machine. You
397 397 can specify to listen on an external interface by specifying the ``ip``
398 398 argument::
399 399
400 400 $> ipython qtconsole --ip=192.168.1.123
401 401
402 402 If you specify the ip as 0.0.0.0 or '*', that means all interfaces, so any
403 403 computer that can see yours on the network can connect to the kernel.
404 404
405 405 Messages are not encrypted, so users with access to the ports your kernel is using will be
406 406 able to see any output of the kernel. They will **NOT** be able to issue shell commands as
407 407 you due to message signatures, which are enabled by default as of IPython 0.12.
408 408
409 409 .. warning::
410 410
411 411 If you disable message signatures, then any user with access to the ports your
412 412 kernel is listening on can issue arbitrary code as you. **DO NOT** disable message
413 413 signatures unless you have a lot of trust in your environment.
414 414
415 415 The one security feature IPython does provide is protection from unauthorized execution.
416 416 IPython's messaging system will sign messages with HMAC digests using a shared-key. The key
417 417 is never sent over the network, it is only used to generate a unique hash for each message,
418 418 based on its content. When IPython receives a message, it will check that the digest
419 419 matches, and discard the message. You can use any file that only you have access to to
420 420 generate this key, but the default is just to generate a new UUID. You can generate a random
421 421 private key with::
422 422
423 423 # generate 1024b of random data, and store in a file only you can read:
424 424 # (assumes IPYTHONDIR is defined, otherwise use your IPython directory)
425 425 $> python -c "import os; print os.urandom(128).encode('base64')" > $IPYTHONDIR/sessionkey
426 426 $> chmod 600 $IPYTHONDIR/sessionkey
427 427
428 428 The *contents* of this file will be stored in the JSON connection file, so that file
429 429 contains everything you need to connect to and use a kernel.
430 430
431 431 To use this generated key, simply specify the ``Session.keyfile`` configurable
432 432 in :file:`ipython_config.py` or at the command-line, as in::
433 433
434 434 # instruct IPython to sign messages with that key, instead of a new UUID
435 435 $> ipython qtconsole --Session.keyfile=$IPYTHONDIR/sessionkey
436 436
437 437 .. _ssh_tunnels:
438 438
439 439 SSH Tunnels
440 440 -----------
441 441
442 442 Sometimes you want to connect to machines across the internet, or just across
443 443 a LAN that either doesn't permit open ports or you don't trust the other
444 444 machines on the network. To do this, you can use SSH tunnels. SSH tunnels
445 445 are a way to securely forward ports on your local machine to ports on another
446 446 machine, to which you have SSH access.
447 447
448 448 In simple cases, IPython's tools can forward ports over ssh by simply adding the
449 449 ``--ssh=remote`` argument to the usual ``--existing...`` set of flags for connecting
450 450 to a running kernel, after copying the JSON connection file (or its contents) to
451 451 the second computer.
452 452
453 453 .. warning::
454 454
455 455 Using SSH tunnels does *not* increase localhost security. In fact, when
456 456 tunneling from one machine to another *both* machines have open
457 457 ports on localhost available for connections to the kernel.
458 458
459 459 There are two primary models for using SSH tunnels with IPython. The first
460 460 is to have the Kernel listen only on localhost, and connect to it from
461 461 another machine on the same LAN.
462 462
463 463 First, let's start a kernel on machine **worker**, listening only
464 464 on loopback::
465 465
466 466 user@worker $> ipython kernel
467 467 [IPKernelApp] To connect another client to this kernel, use:
468 468 [IPKernelApp] --existing kernel-12345.json
469 469
470 470 In this case, the IP that you would connect
471 471 to would still be 127.0.0.1, but you want to specify the additional ``--ssh`` argument
472 472 with the hostname of the kernel (in this example, it's 'worker')::
473 473
474 474 user@client $> ipython qtconsole --ssh=worker --existing /path/to/kernel-12345.json
475 475
476 476 Which will write a new connection file with the forwarded ports, so you can reuse them::
477 477
478 478 [IPythonQtConsoleApp] To connect another client via this tunnel, use:
479 479 [IPythonQtConsoleApp] --existing kernel-12345-ssh.json
480 480
481 481 Note again that this opens ports on the *client* machine that point to your kernel.
482 482
483 483 .. note::
484 484
485 485 the ssh argument is simply passed to openssh, so it can be fully specified ``user@host:port``
486 486 but it will also respect your aliases, etc. in :file:`.ssh/config` if you have any.
487 487
488 488 The second pattern is for connecting to a machine behind a firewall across the internet
489 489 (or otherwise wide network). This time, we have a machine **login** that you have ssh access
490 490 to, which can see **kernel**, but **client** is on another network. The important difference
491 491 now is that **client** can see **login**, but *not* **worker**. So we need to forward ports from
492 492 client to worker *via* login. This means that the kernel must be started listening
493 493 on external interfaces, so that its ports are visible to `login`::
494 494
495 495 user@worker $> ipython kernel --ip=0.0.0.0
496 496 [IPKernelApp] To connect another client to this kernel, use:
497 497 [IPKernelApp] --existing kernel-12345.json
498 498
499 499 Which we can connect to from the client with::
500 500
501 501 user@client $> ipython qtconsole --ssh=login --ip=192.168.1.123 --existing /path/to/kernel-12345.json
502 502
503 503 .. note::
504 504
505 505 The IP here is the address of worker as seen from *login*, and need only be specified if
506 506 the kernel used the ambiguous 0.0.0.0 (all interfaces) address. If it had used
507 507 192.168.1.123 to start with, it would not be needed.
508 508
509 509
510 510 Manual SSH tunnels
511 511 ------------------
512 512
513 513 It's possible that IPython's ssh helper functions won't work for you, for various
514 514 reasons. You can still connect to remote machines, as long as you set up the tunnels
515 515 yourself. The basic format of forwarding a local port to a remote one is::
516 516
517 517 [client] $> ssh <server> <localport>:<remoteip>:<remoteport> -f -N
518 518
519 519 This will forward local connections to **localport** on client to **remoteip:remoteport**
520 520 *via* **server**. Note that remoteip is interpreted relative to *server*, not the client.
521 521 So if you have direct ssh access to the machine to which you want to forward connections,
522 522 then the server *is* the remote machine, and remoteip should be server's IP as seen from the
523 523 server itself, i.e. 127.0.0.1. Thus, to forward local port 12345 to remote port 54321 on
524 524 a machine you can see, do::
525 525
526 526 [client] $> ssh machine 12345:127.0.0.1:54321 -f -N
527 527
528 528 But if your target is actually on a LAN at 192.168.1.123, behind another machine called **login**,
529 529 then you would do::
530 530
531 531 [client] $> ssh login 12345:192.168.1.16:54321 -f -N
532 532
533 533 The ``-f -N`` on the end are flags that tell ssh to run in the background,
534 534 and don't actually run any commands beyond creating the tunnel.
535 535
536 536 .. seealso::
537 537
538 538 A short discussion of ssh tunnels: http://www.revsys.com/writings/quicktips/ssh-tunnel.html
539 539
540 540
541 541
542 542 Stopping Kernels and Consoles
543 543 *****************************
544 544
545 545 Since there can be many consoles per kernel, the shutdown mechanism and dialog
546 546 are probably more complicated than you are used to. Since you don't always want
547 547 to shutdown a kernel when you close a window, you are given the option to just
548 548 close the console window or also close the Kernel and *all other windows*. Note
549 549 that this only refers to all other *local* windows, as remote Consoles are not
550 550 allowed to shutdown the kernel, and shutdowns do not close Remote consoles (to
551 551 allow for saving, etc.).
552 552
553 553 Rules:
554 554
555 555 * Restarting the kernel automatically clears all *local* Consoles, and prompts remote
556 556 Consoles about the reset.
557 557 * Shutdown closes all *local* Consoles, and notifies remotes that
558 558 the Kernel has been shutdown.
559 559 * Remote Consoles may not restart or shutdown the kernel.
560 560
561 561 Qt and the QtConsole
562 562 ====================
563 563
564 564 An important part of working with the QtConsole when you are writing your own
565 565 Qt code is to remember that user code (in the kernel) is *not* in the same
566 566 process as the frontend. This means that there is not necessarily any Qt code
567 567 running in the kernel, and under most normal circumstances there isn't. If,
568 568 however, you specify ``--matplotlib qt`` at the command-line, then there *will* be a
569 569 :class:`QCoreApplication` instance running in the kernel process along with
570 570 user-code. To get a reference to this application, do:
571 571
572 572 .. sourcecode:: python
573 573
574 574 from PyQt4 import QtCore
575 575 app = QtCore.QCoreApplication.instance()
576 576 # app will be None if there is no such instance
577 577
578 578 A common problem listed in the PyQt4 Gotchas_ is the fact that Python's garbage
579 579 collection will destroy Qt objects (Windows, etc.) once there is no longer a
580 580 Python reference to them, so you have to hold on to them. For instance, in:
581 581
582 582 .. sourcecode:: python
583 583
584 584 def make_window():
585 585 win = QtGui.QMainWindow()
586 586
587 587 def make_and_return_window():
588 588 win = QtGui.QMainWindow()
589 589 return win
590 590
591 591 :func:`make_window` will never draw a window, because garbage collection will
592 592 destroy it before it is drawn, whereas :func:`make_and_return_window` lets the
593 593 caller decide when the window object should be destroyed. If, as a developer,
594 594 you know that you always want your objects to last as long as the process, you
595 595 can attach them to the QApplication instance itself:
596 596
597 597 .. sourcecode:: python
598 598
599 599 # do this just once:
600 600 app = QtCore.QCoreApplication.instance()
601 601 app.references = set()
602 602 # then when you create Windows, add them to the set
603 603 def make_window():
604 604 win = QtGui.QMainWindow()
605 605 app.references.add(win)
606 606
607 607 Now the QApplication itself holds a reference to ``win``, so it will never be
608 608 garbage collected until the application itself is destroyed.
609 609
610 610 .. _Gotchas: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/gotchas.html#garbage-collection
611 611
612 612 Embedding the QtConsole in a Qt application
613 613 *******************************************
614 614
615 615 In order to make the QtConsole available to an external Qt GUI application (just as
616 616 :func:`IPython.embed` enables one to embed a terminal session of IPython in a
617 617 command-line application), there are a few options:
618 618
619 619 * First start IPython, and then start the external Qt application from IPython,
620 620 as described above. Effectively, this embeds your application in IPython
621 621 rather than the other way round.
622 622
623 623 * Use :class:`IPython.qt.console.rich_ipython_widget.RichIPythonWidget` in your
624 624 Qt application. This will embed the console widget in your GUI and start the
625 625 kernel in a separate process, so code typed into the console cannot access
626 626 objects in your application.
627 627
628 628 * Start a standard IPython kernel in the process of the external Qt
629 application. See :file:`examples/lib/ipkernel_qtapp.py` for an example. Due
629 application. See :file:`examples/Embedding/ipkernel_qtapp.py` for an example. Due
630 630 to IPython's two-process model, the QtConsole itself will live in another
631 631 process with its own QApplication, and thus cannot be embedded in the main
632 632 GUI.
633 633
634 634 * Start a special IPython kernel, the
635 635 :class:`IPython.kernel.inprocess.ipkernel.InProcessKernel`, that allows a
636 QtConsole in the same process. See :file:`examples/inprocess/embedded_qtconsole.py`
636 QtConsole in the same process. See :file:`examples/Embedding/inprocess_qtconsole.py`
637 637 for an example. While the QtConsole can now be embedded in the main GUI, one
638 638 cannot connect to the kernel from other consoles as there are no real ZMQ
639 639 sockets anymore.
640 640
641 641 Regressions
642 642 ===========
643 643
644 644 There are some features, where the qt console lags behind the Terminal
645 645 frontend:
646 646
647 647 * !cmd input: Due to our use of pexpect, we cannot pass input to subprocesses
648 648 launched using the '!' escape, so you should never call a command that
649 649 requires interactive input. For such cases, use the terminal IPython. This
650 650 will not be fixed, as abandoning pexpect would significantly degrade the
651 651 console experience.
652 652
653 653 .. _PyQt: http://www.riverbankcomputing.co.uk/software/pyqt/download
654 654 .. _pygments: http://pygments.org/
@@ -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 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 149 ``l = %sx ls`` (which in this particular case returns the result of `ls` as a python list).
150 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 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` magic 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 (However, ``!!`` 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 examples in our source directory :file:`examples/lib` that demonstrate
856 examples in our source directory :file:`examples/Embedding` 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 :file:`examples/lib` that demonstrate these capabilities.
865 :file:`examples/Embedding` 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