##// END OF EJS Templates
Merge pull request #10596 from Carreau/display-builtin...
Kyle Kelley -
r23717:4f93bf15 merge
parent child Browse files
Show More
@@ -1,1203 +1,1311 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Top-level display functions for displaying object in different formats."""
3 3
4 4 # Copyright (c) IPython Development Team.
5 5 # Distributed under the terms of the Modified BSD License.
6 6
7 7
8 8 try:
9 9 from base64 import encodebytes as base64_encode
10 10 except ImportError:
11 11 from base64 import encodestring as base64_encode
12 12
13 13 from binascii import b2a_hex
14 14 import json
15 15 import mimetypes
16 16 import os
17 17 import struct
18 18 import sys
19 19 import warnings
20 20
21 21 from IPython.utils.py3compat import cast_unicode
22 22 from IPython.testing.skipdoctest import skip_doctest
23 23
24 24 __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown',
25 25 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json',
26 26 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject',
27 27 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'JSON', 'GeoJSON', 'Javascript',
28 28 'Image', 'clear_output', 'set_matplotlib_formats', 'set_matplotlib_close',
29 29 'publish_display_data', 'update_display', 'DisplayHandle', 'Video']
30 30
31 31 #-----------------------------------------------------------------------------
32 32 # utility functions
33 33 #-----------------------------------------------------------------------------
34 34
35 35 def _safe_exists(path):
36 36 """Check path, but don't let exceptions raise"""
37 37 try:
38 38 return os.path.exists(path)
39 39 except Exception:
40 40 return False
41 41
42 42 def _merge(d1, d2):
43 43 """Like update, but merges sub-dicts instead of clobbering at the top level.
44 44
45 45 Updates d1 in-place
46 46 """
47 47
48 48 if not isinstance(d2, dict) or not isinstance(d1, dict):
49 49 return d2
50 50 for key, value in d2.items():
51 51 d1[key] = _merge(d1.get(key), value)
52 52 return d1
53 53
54 54 def _display_mimetype(mimetype, objs, raw=False, metadata=None):
55 55 """internal implementation of all display_foo methods
56 56
57 57 Parameters
58 58 ----------
59 59 mimetype : str
60 60 The mimetype to be published (e.g. 'image/png')
61 61 objs : tuple of objects
62 62 The Python objects to display, or if raw=True raw text data to
63 63 display.
64 64 raw : bool
65 65 Are the data objects raw data or Python objects that need to be
66 66 formatted before display? [default: False]
67 67 metadata : dict (optional)
68 68 Metadata to be associated with the specific mimetype output.
69 69 """
70 70 if metadata:
71 71 metadata = {mimetype: metadata}
72 72 if raw:
73 73 # turn list of pngdata into list of { 'image/png': pngdata }
74 74 objs = [ {mimetype: obj} for obj in objs ]
75 75 display(*objs, raw=raw, metadata=metadata, include=[mimetype])
76 76
77 77 #-----------------------------------------------------------------------------
78 78 # Main functions
79 79 #-----------------------------------------------------------------------------
80 80
81 81 # use * to indicate transient is keyword-only
82 82 def publish_display_data(data, metadata=None, source=None, *, transient=None, **kwargs):
83 83 """Publish data and metadata to all frontends.
84 84
85 85 See the ``display_data`` message in the messaging documentation for
86 86 more details about this message type.
87 87
88 88 The following MIME types are currently implemented:
89 89
90 90 * text/plain
91 91 * text/html
92 92 * text/markdown
93 93 * text/latex
94 94 * application/json
95 95 * application/javascript
96 96 * image/png
97 97 * image/jpeg
98 98 * image/svg+xml
99 99
100 100 Parameters
101 101 ----------
102 102 data : dict
103 103 A dictionary having keys that are valid MIME types (like
104 104 'text/plain' or 'image/svg+xml') and values that are the data for
105 105 that MIME type. The data itself must be a JSON'able data
106 106 structure. Minimally all data should have the 'text/plain' data,
107 107 which can be displayed by all frontends. If more than the plain
108 108 text is given, it is up to the frontend to decide which
109 109 representation to use.
110 110 metadata : dict
111 111 A dictionary for metadata related to the data. This can contain
112 112 arbitrary key, value pairs that frontends can use to interpret
113 113 the data. mime-type keys matching those in data can be used
114 114 to specify metadata about particular representations.
115 115 source : str, deprecated
116 116 Unused.
117 117 transient : dict, keyword-only
118 118 A dictionary of transient data, such as display_id.
119 119 """
120 120 from IPython.core.interactiveshell import InteractiveShell
121 121
122 122 display_pub = InteractiveShell.instance().display_pub
123 123
124 124 # only pass transient if supplied,
125 125 # to avoid errors with older ipykernel.
126 126 # TODO: We could check for ipykernel version and provide a detailed upgrade message.
127 127 if transient:
128 128 kwargs['transient'] = transient
129 129
130 130 display_pub.publish(
131 131 data=data,
132 132 metadata=metadata,
133 133 **kwargs
134 134 )
135 135
136 136
137 137 def _new_id():
138 138 """Generate a new random text id with urandom"""
139 139 return b2a_hex(os.urandom(16)).decode('ascii')
140 140
141 141
142 142 def display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, **kwargs):
143 143 """Display a Python object in all frontends.
144 144
145 145 By default all representations will be computed and sent to the frontends.
146 146 Frontends can decide which representation is used and how.
147 147
148 In terminal IPython this will be similar to using :func:`print`, for use in richer
149 frontends see Jupyter notebook examples with rich display logic.
150
148 151 Parameters
149 152 ----------
150 153 objs : tuple of objects
151 154 The Python objects to display.
152 155 raw : bool, optional
153 156 Are the objects to be displayed already mimetype-keyed dicts of raw display data,
154 157 or Python objects that need to be formatted before display? [default: False]
155 include : list or tuple, optional
158 include : list, tuple or set, optional
156 159 A list of format type strings (MIME types) to include in the
157 160 format data dict. If this is set *only* the format types included
158 161 in this list will be computed.
159 exclude : list or tuple, optional
162 exclude : list, tuple or set, optional
160 163 A list of format type strings (MIME types) to exclude in the format
161 164 data dict. If this is set all format types will be computed,
162 165 except for those included in this argument.
163 166 metadata : dict, optional
164 167 A dictionary of metadata to associate with the output.
165 168 mime-type keys in this dictionary will be associated with the individual
166 169 representation formats, if they exist.
167 170 transient : dict, optional
168 171 A dictionary of transient data to associate with the output.
169 172 Data in this dict should not be persisted to files (e.g. notebooks).
170 display_id : str, optional
173 display_id : str, bool optional
171 174 Set an id for the display.
172 175 This id can be used for updating this display area later via update_display.
173 If given as True, generate a new display_id
176 If given as `True`, generate a new `display_id`
174 177 kwargs: additional keyword-args, optional
175 178 Additional keyword-arguments are passed through to the display publisher.
176
179
177 180 Returns
178 181 -------
179
182
180 183 handle: DisplayHandle
181 Returns a handle on updatable displays, if display_id is given.
182 Returns None if no display_id is given (default).
184 Returns a handle on updatable displays for use with :func:`update_display`,
185 if `display_id` is given. Returns :any:`None` if no `display_id` is given
186 (default).
187
188 Examples
189 --------
190
191 >>> class Json(object):
192 ... def __init__(self, json):
193 ... self.json = json
194 ... def _repr_pretty_(self, pp, cycle):
195 ... import json
196 ... pp.text(json.dumps(self.json, indent=2))
197 ... def __repr__(self):
198 ... return str(self.json)
199 ...
200
201 >>> d = Json({1:2, 3: {4:5}})
202
203 >>> print(d)
204 {1: 2, 3: {4: 5}}
205
206 >>> display(d)
207 {
208 "1": 2,
209 "3": {
210 "4": 5
211 }
212 }
213
214 >>> def int_formatter(integer, pp, cycle):
215 ... pp.text('I'*integer)
216
217 >>> plain = get_ipython().display_formatter.formatters['text/plain']
218 >>> plain.for_type(int, int_formatter)
219 <function _repr_pprint at 0x...>
220 >>> display(7-5)
221 II
222
223 >>> del plain.type_printers[int]
224 >>> display(7-5)
225 2
226
227 See Also
228 --------
229
230 :func:`update_display`
231
232 Notes
233 -----
234
235 In Python, objects can declare their textual representation using the
236 `__repr__` method. IPython expands on this idea and allows objects to declare
237 other, rich representations including:
238
239 - HTML
240 - JSON
241 - PNG
242 - JPEG
243 - SVG
244 - LaTeX
245
246 A single object can declare some or all of these representations; all are
247 handled by IPython's display system.
248
249 The main idea of the first approach is that you have to implement special
250 display methods when you define your class, one for each representation you
251 want to use. Here is a list of the names of the special methods and the
252 values they must return:
253
254 - `_repr_html_`: return raw HTML as a string
255 - `_repr_json_`: return a JSONable dict
256 - `_repr_jpeg_`: return raw JPEG data
257 - `_repr_png_`: return raw PNG data
258 - `_repr_svg_`: return raw SVG data as a string
259 - `_repr_latex_`: return LaTeX commands in a string surrounded by "$".
260 - `_repr_mimebundle_`: return a full mimebundle containing the mapping
261 from all mimetypes to data
262
263 When you are directly writing your own classes, you can adapt them for
264 display in IPython by following the above approach. But in practice, you
265 often need to work with existing classes that you can't easily modify.
266
267 You can refer to the documentation on IPython display formatters in order to
268 register custom formatters for already existing types.
269
270 .. versionadded:: 5.4 display available without import
271 .. versionadded:: 6.1 display available without import
272
273 Since IPython 5.4 and 6.1 :func:`display` is automatically made available to
274 the user without import. If you are using display in a document that might
275 be used in a pure python context or with older version of IPython, use the
276 following import at the top of your file::
277
278 from IPython.display import display
279
183 280 """
184 281 raw = kwargs.pop('raw', False)
185 282 if transient is None:
186 283 transient = {}
187 284 if display_id:
188 if display_id == True:
285 if display_id is True:
189 286 display_id = _new_id()
190 287 transient['display_id'] = display_id
191 288 if kwargs.get('update') and 'display_id' not in transient:
192 289 raise TypeError('display_id required for update_display')
193 290 if transient:
194 291 kwargs['transient'] = transient
195 292
196 293 from IPython.core.interactiveshell import InteractiveShell
197 294
198 295 if not raw:
199 296 format = InteractiveShell.instance().display_formatter.format
200 297
201 298 for obj in objs:
202 299 if raw:
203 300 publish_display_data(data=obj, metadata=metadata, **kwargs)
204 301 else:
205 302 format_dict, md_dict = format(obj, include=include, exclude=exclude)
206 303 if not format_dict:
207 304 # nothing to display (e.g. _ipython_display_ took over)
208 305 continue
209 306 if metadata:
210 307 # kwarg-specified metadata gets precedence
211 308 _merge(md_dict, metadata)
212 309 publish_display_data(data=format_dict, metadata=md_dict, **kwargs)
213 310 if display_id:
214 311 return DisplayHandle(display_id)
215 312
216 313
217 314 # use * for keyword-only display_id arg
218 315 def update_display(obj, *, display_id, **kwargs):
219 316 """Update an existing display by id
220 317
221 318 Parameters
222 319 ----------
223 320
224 321 obj:
225 322 The object with which to update the display
226 323 display_id: keyword-only
227 324 The id of the display to update
325
326 See Also
327 --------
328
329 :func:`display`
228 330 """
229 331 kwargs['update'] = True
230 332 display(obj, display_id=display_id, **kwargs)
231 333
232 334
233 335 class DisplayHandle(object):
234 336 """A handle on an updatable display
235 337
236 Call .update(obj) to display a new object.
338 Call `.update(obj)` to display a new object.
237 339
238 Call .display(obj) to add a new instance of this display,
340 Call `.display(obj`) to add a new instance of this display,
239 341 and update existing instances.
342
343 See Also
344 --------
345
346 :func:`display`, :func:`update_display`
347
240 348 """
241 349
242 350 def __init__(self, display_id=None):
243 351 if display_id is None:
244 352 display_id = _new_id()
245 353 self.display_id = display_id
246 354
247 355 def __repr__(self):
248 356 return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id)
249 357
250 358 def display(self, obj, **kwargs):
251 359 """Make a new display with my id, updating existing instances.
252 360
253 361 Parameters
254 362 ----------
255 363
256 364 obj:
257 365 object to display
258 366 **kwargs:
259 367 additional keyword arguments passed to display
260 368 """
261 369 display(obj, display_id=self.display_id, **kwargs)
262 370
263 371 def update(self, obj, **kwargs):
264 372 """Update existing displays with my id
265 373
266 374 Parameters
267 375 ----------
268 376
269 377 obj:
270 378 object to display
271 379 **kwargs:
272 380 additional keyword arguments passed to update_display
273 381 """
274 382 update_display(obj, display_id=self.display_id, **kwargs)
275 383
276 384
277 385 def display_pretty(*objs, **kwargs):
278 386 """Display the pretty (default) representation of an object.
279 387
280 388 Parameters
281 389 ----------
282 390 objs : tuple of objects
283 391 The Python objects to display, or if raw=True raw text data to
284 392 display.
285 393 raw : bool
286 394 Are the data objects raw data or Python objects that need to be
287 395 formatted before display? [default: False]
288 396 metadata : dict (optional)
289 397 Metadata to be associated with the specific mimetype output.
290 398 """
291 399 _display_mimetype('text/plain', objs, **kwargs)
292 400
293 401
294 402 def display_html(*objs, **kwargs):
295 403 """Display the HTML representation of an object.
296 404
297 405 Note: If raw=False and the object does not have a HTML
298 406 representation, no HTML will be shown.
299 407
300 408 Parameters
301 409 ----------
302 410 objs : tuple of objects
303 411 The Python objects to display, or if raw=True raw HTML data to
304 412 display.
305 413 raw : bool
306 414 Are the data objects raw data or Python objects that need to be
307 415 formatted before display? [default: False]
308 416 metadata : dict (optional)
309 417 Metadata to be associated with the specific mimetype output.
310 418 """
311 419 _display_mimetype('text/html', objs, **kwargs)
312 420
313 421
314 422 def display_markdown(*objs, **kwargs):
315 423 """Displays the Markdown representation of an object.
316 424
317 425 Parameters
318 426 ----------
319 427 objs : tuple of objects
320 428 The Python objects to display, or if raw=True raw markdown data to
321 429 display.
322 430 raw : bool
323 431 Are the data objects raw data or Python objects that need to be
324 432 formatted before display? [default: False]
325 433 metadata : dict (optional)
326 434 Metadata to be associated with the specific mimetype output.
327 435 """
328 436
329 437 _display_mimetype('text/markdown', objs, **kwargs)
330 438
331 439
332 440 def display_svg(*objs, **kwargs):
333 441 """Display the SVG representation of an object.
334 442
335 443 Parameters
336 444 ----------
337 445 objs : tuple of objects
338 446 The Python objects to display, or if raw=True raw svg data to
339 447 display.
340 448 raw : bool
341 449 Are the data objects raw data or Python objects that need to be
342 450 formatted before display? [default: False]
343 451 metadata : dict (optional)
344 452 Metadata to be associated with the specific mimetype output.
345 453 """
346 454 _display_mimetype('image/svg+xml', objs, **kwargs)
347 455
348 456
349 457 def display_png(*objs, **kwargs):
350 458 """Display the PNG representation of an object.
351 459
352 460 Parameters
353 461 ----------
354 462 objs : tuple of objects
355 463 The Python objects to display, or if raw=True raw png data to
356 464 display.
357 465 raw : bool
358 466 Are the data objects raw data or Python objects that need to be
359 467 formatted before display? [default: False]
360 468 metadata : dict (optional)
361 469 Metadata to be associated with the specific mimetype output.
362 470 """
363 471 _display_mimetype('image/png', objs, **kwargs)
364 472
365 473
366 474 def display_jpeg(*objs, **kwargs):
367 475 """Display the JPEG representation of an object.
368 476
369 477 Parameters
370 478 ----------
371 479 objs : tuple of objects
372 480 The Python objects to display, or if raw=True raw JPEG data to
373 481 display.
374 482 raw : bool
375 483 Are the data objects raw data or Python objects that need to be
376 484 formatted before display? [default: False]
377 485 metadata : dict (optional)
378 486 Metadata to be associated with the specific mimetype output.
379 487 """
380 488 _display_mimetype('image/jpeg', objs, **kwargs)
381 489
382 490
383 491 def display_latex(*objs, **kwargs):
384 492 """Display the LaTeX representation of an object.
385 493
386 494 Parameters
387 495 ----------
388 496 objs : tuple of objects
389 497 The Python objects to display, or if raw=True raw latex data to
390 498 display.
391 499 raw : bool
392 500 Are the data objects raw data or Python objects that need to be
393 501 formatted before display? [default: False]
394 502 metadata : dict (optional)
395 503 Metadata to be associated with the specific mimetype output.
396 504 """
397 505 _display_mimetype('text/latex', objs, **kwargs)
398 506
399 507
400 508 def display_json(*objs, **kwargs):
401 509 """Display the JSON representation of an object.
402 510
403 511 Note that not many frontends support displaying JSON.
404 512
405 513 Parameters
406 514 ----------
407 515 objs : tuple of objects
408 516 The Python objects to display, or if raw=True raw json data to
409 517 display.
410 518 raw : bool
411 519 Are the data objects raw data or Python objects that need to be
412 520 formatted before display? [default: False]
413 521 metadata : dict (optional)
414 522 Metadata to be associated with the specific mimetype output.
415 523 """
416 524 _display_mimetype('application/json', objs, **kwargs)
417 525
418 526
419 527 def display_javascript(*objs, **kwargs):
420 528 """Display the Javascript representation of an object.
421 529
422 530 Parameters
423 531 ----------
424 532 objs : tuple of objects
425 533 The Python objects to display, or if raw=True raw javascript data to
426 534 display.
427 535 raw : bool
428 536 Are the data objects raw data or Python objects that need to be
429 537 formatted before display? [default: False]
430 538 metadata : dict (optional)
431 539 Metadata to be associated with the specific mimetype output.
432 540 """
433 541 _display_mimetype('application/javascript', objs, **kwargs)
434 542
435 543
436 544 def display_pdf(*objs, **kwargs):
437 545 """Display the PDF representation of an object.
438 546
439 547 Parameters
440 548 ----------
441 549 objs : tuple of objects
442 550 The Python objects to display, or if raw=True raw javascript data to
443 551 display.
444 552 raw : bool
445 553 Are the data objects raw data or Python objects that need to be
446 554 formatted before display? [default: False]
447 555 metadata : dict (optional)
448 556 Metadata to be associated with the specific mimetype output.
449 557 """
450 558 _display_mimetype('application/pdf', objs, **kwargs)
451 559
452 560
453 561 #-----------------------------------------------------------------------------
454 562 # Smart classes
455 563 #-----------------------------------------------------------------------------
456 564
457 565
458 566 class DisplayObject(object):
459 567 """An object that wraps data to be displayed."""
460 568
461 569 _read_flags = 'r'
462 570 _show_mem_addr = False
463 571
464 572 def __init__(self, data=None, url=None, filename=None):
465 573 """Create a display object given raw data.
466 574
467 575 When this object is returned by an expression or passed to the
468 576 display function, it will result in the data being displayed
469 577 in the frontend. The MIME type of the data should match the
470 578 subclasses used, so the Png subclass should be used for 'image/png'
471 579 data. If the data is a URL, the data will first be downloaded
472 580 and then displayed. If
473 581
474 582 Parameters
475 583 ----------
476 584 data : unicode, str or bytes
477 585 The raw data or a URL or file to load the data from
478 586 url : unicode
479 587 A URL to download the data from.
480 588 filename : unicode
481 589 Path to a local file to load the data from.
482 590 """
483 591 if data is not None and isinstance(data, str):
484 592 if data.startswith('http') and url is None:
485 593 url = data
486 594 filename = None
487 595 data = None
488 596 elif _safe_exists(data) and filename is None:
489 597 url = None
490 598 filename = data
491 599 data = None
492 600
493 601 self.data = data
494 602 self.url = url
495 603 self.filename = filename
496 604
497 605 self.reload()
498 606 self._check_data()
499 607
500 608 def __repr__(self):
501 609 if not self._show_mem_addr:
502 610 cls = self.__class__
503 611 r = "<%s.%s object>" % (cls.__module__, cls.__name__)
504 612 else:
505 613 r = super(DisplayObject, self).__repr__()
506 614 return r
507 615
508 616 def _check_data(self):
509 617 """Override in subclasses if there's something to check."""
510 618 pass
511 619
512 620 def reload(self):
513 621 """Reload the raw data from file or URL."""
514 622 if self.filename is not None:
515 623 with open(self.filename, self._read_flags) as f:
516 624 self.data = f.read()
517 625 elif self.url is not None:
518 626 try:
519 627 # Deferred import
520 628 from urllib.request import urlopen
521 629 response = urlopen(self.url)
522 630 self.data = response.read()
523 631 # extract encoding from header, if there is one:
524 632 encoding = None
525 633 for sub in response.headers['content-type'].split(';'):
526 634 sub = sub.strip()
527 635 if sub.startswith('charset'):
528 636 encoding = sub.split('=')[-1].strip()
529 637 break
530 638 # decode data, if an encoding was specified
531 639 if encoding:
532 640 self.data = self.data.decode(encoding, 'replace')
533 641 except:
534 642 self.data = None
535 643
536 644 class TextDisplayObject(DisplayObject):
537 645 """Validate that display data is text"""
538 646 def _check_data(self):
539 647 if self.data is not None and not isinstance(self.data, str):
540 648 raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data))
541 649
542 650 class Pretty(TextDisplayObject):
543 651
544 652 def _repr_pretty_(self):
545 653 return self.data
546 654
547 655
548 656 class HTML(TextDisplayObject):
549 657
550 658 def _repr_html_(self):
551 659 return self.data
552 660
553 661 def __html__(self):
554 662 """
555 663 This method exists to inform other HTML-using modules (e.g. Markupsafe,
556 664 htmltag, etc) that this object is HTML and does not need things like
557 665 special characters (<>&) escaped.
558 666 """
559 667 return self._repr_html_()
560 668
561 669
562 670 class Markdown(TextDisplayObject):
563 671
564 672 def _repr_markdown_(self):
565 673 return self.data
566 674
567 675
568 676 class Math(TextDisplayObject):
569 677
570 678 def _repr_latex_(self):
571 679 s = self.data.strip('$')
572 680 return "$$%s$$" % s
573 681
574 682
575 683 class Latex(TextDisplayObject):
576 684
577 685 def _repr_latex_(self):
578 686 return self.data
579 687
580 688
581 689 class SVG(DisplayObject):
582 690
583 691 _read_flags = 'rb'
584 692 # wrap data in a property, which extracts the <svg> tag, discarding
585 693 # document headers
586 694 _data = None
587 695
588 696 @property
589 697 def data(self):
590 698 return self._data
591 699
592 700 @data.setter
593 701 def data(self, svg):
594 702 if svg is None:
595 703 self._data = None
596 704 return
597 705 # parse into dom object
598 706 from xml.dom import minidom
599 707 x = minidom.parseString(svg)
600 708 # get svg tag (should be 1)
601 709 found_svg = x.getElementsByTagName('svg')
602 710 if found_svg:
603 711 svg = found_svg[0].toxml()
604 712 else:
605 713 # fallback on the input, trust the user
606 714 # but this is probably an error.
607 715 pass
608 716 svg = cast_unicode(svg)
609 717 self._data = svg
610 718
611 719 def _repr_svg_(self):
612 720 return self.data
613 721
614 722
615 723 class JSON(DisplayObject):
616 724 """JSON expects a JSON-able dict or list
617 725
618 726 not an already-serialized JSON string.
619 727
620 728 Scalar types (None, number, string) are not allowed, only dict or list containers.
621 729 """
622 730 # wrap data in a property, which warns about passing already-serialized JSON
623 731 _data = None
624 732 def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None, **kwargs):
625 733 """Create a JSON display object given raw data.
626 734
627 735 Parameters
628 736 ----------
629 737 data : dict or list
630 738 JSON data to display. Not an already-serialized JSON string.
631 739 Scalar types (None, number, string) are not allowed, only dict
632 740 or list containers.
633 741 url : unicode
634 742 A URL to download the data from.
635 743 filename : unicode
636 744 Path to a local file to load the data from.
637 745 expanded : boolean
638 746 Metadata to control whether a JSON display component is expanded.
639 747 metadata: dict
640 748 Specify extra metadata to attach to the json display object.
641 749 """
642 750 self.metadata = {'expanded': expanded}
643 751 if metadata:
644 752 self.metadata.update(metadata)
645 753 if kwargs:
646 754 self.metadata.update(kwargs)
647 755 super(JSON, self).__init__(data=data, url=url, filename=filename)
648 756
649 757 def _check_data(self):
650 758 if self.data is not None and not isinstance(self.data, (dict, list)):
651 759 raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data))
652 760
653 761 @property
654 762 def data(self):
655 763 return self._data
656 764
657 765 @data.setter
658 766 def data(self, data):
659 767 if isinstance(data, str):
660 768 if getattr(self, 'filename', None) is None:
661 769 warnings.warn("JSON expects JSONable dict or list, not JSON strings")
662 770 data = json.loads(data)
663 771 self._data = data
664 772
665 773 def _data_and_metadata(self):
666 774 return self.data, self.metadata
667 775
668 776 def _repr_json_(self):
669 777 return self._data_and_metadata()
670 778
671 779 _css_t = """$("head").append($("<link/>").attr({
672 780 rel: "stylesheet",
673 781 type: "text/css",
674 782 href: "%s"
675 783 }));
676 784 """
677 785
678 786 _lib_t1 = """$.getScript("%s", function () {
679 787 """
680 788 _lib_t2 = """});
681 789 """
682 790
683 791 class GeoJSON(JSON):
684 792 """GeoJSON expects JSON-able dict
685 793
686 794 not an already-serialized JSON string.
687 795
688 796 Scalar types (None, number, string) are not allowed, only dict containers.
689 797 """
690 798
691 799 def __init__(self, *args, **kwargs):
692 800 """Create a GeoJSON display object given raw data.
693 801
694 802 Parameters
695 803 ----------
696 804 data : dict or list
697 805 VegaLite data. Not an already-serialized JSON string.
698 806 Scalar types (None, number, string) are not allowed, only dict
699 807 or list containers.
700 808 url_template : string
701 809 Leaflet TileLayer URL template: http://leafletjs.com/reference.html#url-template
702 810 layer_options : dict
703 811 Leaflet TileLayer options: http://leafletjs.com/reference.html#tilelayer-options
704 812 url : unicode
705 813 A URL to download the data from.
706 814 filename : unicode
707 815 Path to a local file to load the data from.
708 816 metadata: dict
709 817 Specify extra metadata to attach to the json display object.
710 818
711 819 Examples
712 820 --------
713 821
714 822 The following will display an interactive map of Mars with a point of
715 823 interest on frontend that do support GeoJSON display.
716 824
717 825 >>> from IPython.display import GeoJSON
718 826
719 827 >>> GeoJSON(data={
720 828 ... "type": "Feature",
721 829 ... "geometry": {
722 830 ... "type": "Point",
723 831 ... "coordinates": [-81.327, 296.038]
724 832 ... }
725 833 ... },
726 834 ... url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png",
727 835 ... layer_options={
728 836 ... "basemap_id": "celestia_mars-shaded-16k_global",
729 837 ... "attribution" : "Celestia/praesepe",
730 838 ... "minZoom" : 0,
731 839 ... "maxZoom" : 18,
732 840 ... })
733 841 <IPython.core.display.GeoJSON object>
734 842
735 843 In the terminal IPython, you will only see the text representation of
736 844 the GeoJSON object.
737 845
738 846 """
739 847
740 848 super(GeoJSON, self).__init__(*args, **kwargs)
741 849
742 850
743 851 def _ipython_display_(self):
744 852 bundle = {
745 853 'application/geo+json': self.data,
746 854 'text/plain': '<IPython.display.GeoJSON object>'
747 855 }
748 856 metadata = {
749 857 'application/geo+json': self.metadata
750 858 }
751 859 display(bundle, metadata=metadata, raw=True)
752 860
753 861 class Javascript(TextDisplayObject):
754 862
755 863 def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
756 864 """Create a Javascript display object given raw data.
757 865
758 866 When this object is returned by an expression or passed to the
759 867 display function, it will result in the data being displayed
760 868 in the frontend. If the data is a URL, the data will first be
761 869 downloaded and then displayed.
762 870
763 871 In the Notebook, the containing element will be available as `element`,
764 872 and jQuery will be available. Content appended to `element` will be
765 873 visible in the output area.
766 874
767 875 Parameters
768 876 ----------
769 877 data : unicode, str or bytes
770 878 The Javascript source code or a URL to download it from.
771 879 url : unicode
772 880 A URL to download the data from.
773 881 filename : unicode
774 882 Path to a local file to load the data from.
775 883 lib : list or str
776 884 A sequence of Javascript library URLs to load asynchronously before
777 885 running the source code. The full URLs of the libraries should
778 886 be given. A single Javascript library URL can also be given as a
779 887 string.
780 888 css: : list or str
781 889 A sequence of css files to load before running the source code.
782 890 The full URLs of the css files should be given. A single css URL
783 891 can also be given as a string.
784 892 """
785 893 if isinstance(lib, str):
786 894 lib = [lib]
787 895 elif lib is None:
788 896 lib = []
789 897 if isinstance(css, str):
790 898 css = [css]
791 899 elif css is None:
792 900 css = []
793 901 if not isinstance(lib, (list,tuple)):
794 902 raise TypeError('expected sequence, got: %r' % lib)
795 903 if not isinstance(css, (list,tuple)):
796 904 raise TypeError('expected sequence, got: %r' % css)
797 905 self.lib = lib
798 906 self.css = css
799 907 super(Javascript, self).__init__(data=data, url=url, filename=filename)
800 908
801 909 def _repr_javascript_(self):
802 910 r = ''
803 911 for c in self.css:
804 912 r += _css_t % c
805 913 for l in self.lib:
806 914 r += _lib_t1 % l
807 915 r += self.data
808 916 r += _lib_t2*len(self.lib)
809 917 return r
810 918
811 919 # constants for identifying png/jpeg data
812 920 _PNG = b'\x89PNG\r\n\x1a\n'
813 921 _JPEG = b'\xff\xd8'
814 922
815 923 def _pngxy(data):
816 924 """read the (width, height) from a PNG header"""
817 925 ihdr = data.index(b'IHDR')
818 926 # next 8 bytes are width/height
819 927 w4h4 = data[ihdr+4:ihdr+12]
820 928 return struct.unpack('>ii', w4h4)
821 929
822 930 def _jpegxy(data):
823 931 """read the (width, height) from a JPEG header"""
824 932 # adapted from http://www.64lines.com/jpeg-width-height
825 933
826 934 idx = 4
827 935 while True:
828 936 block_size = struct.unpack('>H', data[idx:idx+2])[0]
829 937 idx = idx + block_size
830 938 if data[idx:idx+2] == b'\xFF\xC0':
831 939 # found Start of Frame
832 940 iSOF = idx
833 941 break
834 942 else:
835 943 # read another block
836 944 idx += 2
837 945
838 946 h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9])
839 947 return w, h
840 948
841 949 class Image(DisplayObject):
842 950
843 951 _read_flags = 'rb'
844 952 _FMT_JPEG = u'jpeg'
845 953 _FMT_PNG = u'png'
846 954 _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG]
847 955
848 956 def __init__(self, data=None, url=None, filename=None, format=None,
849 957 embed=None, width=None, height=None, retina=False,
850 958 unconfined=False, metadata=None):
851 959 """Create a PNG/JPEG image object given raw data.
852 960
853 961 When this object is returned by an input cell or passed to the
854 962 display function, it will result in the image being displayed
855 963 in the frontend.
856 964
857 965 Parameters
858 966 ----------
859 967 data : unicode, str or bytes
860 968 The raw image data or a URL or filename to load the data from.
861 969 This always results in embedded image data.
862 970 url : unicode
863 971 A URL to download the data from. If you specify `url=`,
864 972 the image data will not be embedded unless you also specify `embed=True`.
865 973 filename : unicode
866 974 Path to a local file to load the data from.
867 975 Images from a file are always embedded.
868 976 format : unicode
869 977 The format of the image data (png/jpeg/jpg). If a filename or URL is given
870 978 for format will be inferred from the filename extension.
871 979 embed : bool
872 980 Should the image data be embedded using a data URI (True) or be
873 981 loaded using an <img> tag. Set this to True if you want the image
874 982 to be viewable later with no internet connection in the notebook.
875 983
876 984 Default is `True`, unless the keyword argument `url` is set, then
877 985 default value is `False`.
878 986
879 987 Note that QtConsole is not able to display images if `embed` is set to `False`
880 988 width : int
881 989 Width in pixels to which to constrain the image in html
882 990 height : int
883 991 Height in pixels to which to constrain the image in html
884 992 retina : bool
885 993 Automatically set the width and height to half of the measured
886 994 width and height.
887 995 This only works for embedded images because it reads the width/height
888 996 from image data.
889 997 For non-embedded images, you can just set the desired display width
890 998 and height directly.
891 999 unconfined: bool
892 1000 Set unconfined=True to disable max-width confinement of the image.
893 1001 metadata: dict
894 1002 Specify extra metadata to attach to the image.
895 1003
896 1004 Examples
897 1005 --------
898 1006 # embedded image data, works in qtconsole and notebook
899 1007 # when passed positionally, the first arg can be any of raw image data,
900 1008 # a URL, or a filename from which to load image data.
901 1009 # The result is always embedding image data for inline images.
902 1010 Image('http://www.google.fr/images/srpr/logo3w.png')
903 1011 Image('/path/to/image.jpg')
904 1012 Image(b'RAW_PNG_DATA...')
905 1013
906 1014 # Specifying Image(url=...) does not embed the image data,
907 1015 # it only generates `<img>` tag with a link to the source.
908 1016 # This will not work in the qtconsole or offline.
909 1017 Image(url='http://www.google.fr/images/srpr/logo3w.png')
910 1018
911 1019 """
912 1020 if filename is not None:
913 1021 ext = self._find_ext(filename)
914 1022 elif url is not None:
915 1023 ext = self._find_ext(url)
916 1024 elif data is None:
917 1025 raise ValueError("No image data found. Expecting filename, url, or data.")
918 1026 elif isinstance(data, str) and (
919 1027 data.startswith('http') or _safe_exists(data)
920 1028 ):
921 1029 ext = self._find_ext(data)
922 1030 else:
923 1031 ext = None
924 1032
925 1033 if format is None:
926 1034 if ext is not None:
927 1035 if ext == u'jpg' or ext == u'jpeg':
928 1036 format = self._FMT_JPEG
929 1037 if ext == u'png':
930 1038 format = self._FMT_PNG
931 1039 else:
932 1040 format = ext.lower()
933 1041 elif isinstance(data, bytes):
934 1042 # infer image type from image data header,
935 1043 # only if format has not been specified.
936 1044 if data[:2] == _JPEG:
937 1045 format = self._FMT_JPEG
938 1046
939 1047 # failed to detect format, default png
940 1048 if format is None:
941 1049 format = 'png'
942 1050
943 1051 if format.lower() == 'jpg':
944 1052 # jpg->jpeg
945 1053 format = self._FMT_JPEG
946 1054
947 1055 self.format = format.lower()
948 1056 self.embed = embed if embed is not None else (url is None)
949 1057
950 1058 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
951 1059 raise ValueError("Cannot embed the '%s' image format" % (self.format))
952 1060 self.width = width
953 1061 self.height = height
954 1062 self.retina = retina
955 1063 self.unconfined = unconfined
956 1064 self.metadata = metadata
957 1065 super(Image, self).__init__(data=data, url=url, filename=filename)
958 1066
959 1067 if retina:
960 1068 self._retina_shape()
961 1069
962 1070 def _retina_shape(self):
963 1071 """load pixel-doubled width and height from image data"""
964 1072 if not self.embed:
965 1073 return
966 1074 if self.format == 'png':
967 1075 w, h = _pngxy(self.data)
968 1076 elif self.format == 'jpeg':
969 1077 w, h = _jpegxy(self.data)
970 1078 else:
971 1079 # retina only supports png
972 1080 return
973 1081 self.width = w // 2
974 1082 self.height = h // 2
975 1083
976 1084 def reload(self):
977 1085 """Reload the raw data from file or URL."""
978 1086 if self.embed:
979 1087 super(Image,self).reload()
980 1088 if self.retina:
981 1089 self._retina_shape()
982 1090
983 1091 def _repr_html_(self):
984 1092 if not self.embed:
985 1093 width = height = klass = ''
986 1094 if self.width:
987 1095 width = ' width="%d"' % self.width
988 1096 if self.height:
989 1097 height = ' height="%d"' % self.height
990 1098 if self.unconfined:
991 1099 klass = ' class="unconfined"'
992 1100 return u'<img src="{url}"{width}{height}{klass}/>'.format(
993 1101 url=self.url,
994 1102 width=width,
995 1103 height=height,
996 1104 klass=klass,
997 1105 )
998 1106
999 1107 def _data_and_metadata(self):
1000 1108 """shortcut for returning metadata with shape information, if defined"""
1001 1109 md = {}
1002 1110 if self.width:
1003 1111 md['width'] = self.width
1004 1112 if self.height:
1005 1113 md['height'] = self.height
1006 1114 if self.unconfined:
1007 1115 md['unconfined'] = self.unconfined
1008 1116 if self.metadata:
1009 1117 md.update(self.metadata)
1010 1118 if md:
1011 1119 return self.data, md
1012 1120 else:
1013 1121 return self.data
1014 1122
1015 1123 def _repr_png_(self):
1016 1124 if self.embed and self.format == u'png':
1017 1125 return self._data_and_metadata()
1018 1126
1019 1127 def _repr_jpeg_(self):
1020 1128 if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
1021 1129 return self._data_and_metadata()
1022 1130
1023 1131 def _find_ext(self, s):
1024 1132 return s.split('.')[-1].lower()
1025 1133
1026 1134 class Video(DisplayObject):
1027 1135
1028 1136 def __init__(self, data=None, url=None, filename=None, embed=False, mimetype=None):
1029 1137 """Create a video object given raw data or an URL.
1030 1138
1031 1139 When this object is returned by an input cell or passed to the
1032 1140 display function, it will result in the video being displayed
1033 1141 in the frontend.
1034 1142
1035 1143 Parameters
1036 1144 ----------
1037 1145 data : unicode, str or bytes
1038 1146 The raw video data or a URL or filename to load the data from.
1039 1147 Raw data will require passing `embed=True`.
1040 1148 url : unicode
1041 1149 A URL for the video. If you specify `url=`,
1042 1150 the image data will not be embedded.
1043 1151 filename : unicode
1044 1152 Path to a local file containing the video.
1045 1153 Will be interpreted as a local URL unless `embed=True`.
1046 1154 embed : bool
1047 1155 Should the video be embedded using a data URI (True) or be
1048 1156 loaded using a <video> tag (False).
1049 1157
1050 1158 Since videos are large, embedding them should be avoided, if possible.
1051 1159 You must confirm embedding as your intention by passing `embed=True`.
1052 1160
1053 1161 Local files can be displayed with URLs without embedding the content, via::
1054 1162
1055 1163 Video('./video.mp4')
1056 1164
1057 1165 mimetype: unicode
1058 1166 Specify the mimetype for embedded videos.
1059 1167 Default will be guessed from file extension, if available.
1060 1168
1061 1169 Examples
1062 1170 --------
1063 1171
1064 1172 Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4')
1065 1173 Video('path/to/video.mp4')
1066 1174 Video('path/to/video.mp4', embed=True)
1067 1175 Video(b'raw-videodata', embed=True)
1068 1176 """
1069 1177 if url is None and isinstance(data, str) and data.startswith(('http:', 'https:')):
1070 1178 url = data
1071 1179 data = None
1072 1180 elif os.path.exists(data):
1073 1181 filename = data
1074 1182 data = None
1075 1183
1076 1184 if data and not embed:
1077 1185 msg = ''.join([
1078 1186 "To embed videos, you must pass embed=True ",
1079 1187 "(this may make your notebook files huge)\n",
1080 1188 "Consider passing Video(url='...')",
1081 1189 ])
1082 1190 raise ValueError(msg)
1083 1191
1084 1192 self.mimetype = mimetype
1085 1193 self.embed = embed
1086 1194 super(Video, self).__init__(data=data, url=url, filename=filename)
1087 1195
1088 1196 def _repr_html_(self):
1089 1197 # External URLs and potentially local files are not embedded into the
1090 1198 # notebook output.
1091 1199 if not self.embed:
1092 1200 url = self.url if self.url is not None else self.filename
1093 1201 output = """<video src="{0}" controls>
1094 1202 Your browser does not support the <code>video</code> element.
1095 1203 </video>""".format(url)
1096 1204 return output
1097 1205
1098 1206 # Embedded videos are base64-encoded.
1099 1207 mimetype = self.mimetype
1100 1208 if self.filename is not None:
1101 1209 if not mimetype:
1102 1210 mimetype, _ = mimetypes.guess_type(self.filename)
1103 1211
1104 1212 with open(self.filename, 'rb') as f:
1105 1213 video = f.read()
1106 1214 else:
1107 1215 video = self.data
1108 1216 if isinstance(video, str):
1109 1217 # unicode input is already b64-encoded
1110 1218 b64_video = video
1111 1219 else:
1112 1220 b64_video = base64_encode(video).decode('ascii').rstrip()
1113 1221
1114 1222 output = """<video controls>
1115 1223 <source src="data:{0};base64,{1}" type="{0}">
1116 1224 Your browser does not support the video tag.
1117 1225 </video>""".format(mimetype, b64_video)
1118 1226 return output
1119 1227
1120 1228 def reload(self):
1121 1229 # TODO
1122 1230 pass
1123 1231
1124 1232 def _repr_png_(self):
1125 1233 # TODO
1126 1234 pass
1127 1235 def _repr_jpeg_(self):
1128 1236 # TODO
1129 1237 pass
1130 1238
1131 1239 def clear_output(wait=False):
1132 1240 """Clear the output of the current cell receiving output.
1133 1241
1134 1242 Parameters
1135 1243 ----------
1136 1244 wait : bool [default: false]
1137 1245 Wait to clear the output until new output is available to replace it."""
1138 1246 from IPython.core.interactiveshell import InteractiveShell
1139 1247 if InteractiveShell.initialized():
1140 1248 InteractiveShell.instance().display_pub.clear_output(wait)
1141 1249 else:
1142 1250 print('\033[2K\r', end='')
1143 1251 sys.stdout.flush()
1144 1252 print('\033[2K\r', end='')
1145 1253 sys.stderr.flush()
1146 1254
1147 1255
1148 1256 @skip_doctest
1149 1257 def set_matplotlib_formats(*formats, **kwargs):
1150 1258 """Select figure formats for the inline backend. Optionally pass quality for JPEG.
1151 1259
1152 1260 For example, this enables PNG and JPEG output with a JPEG quality of 90%::
1153 1261
1154 1262 In [1]: set_matplotlib_formats('png', 'jpeg', quality=90)
1155 1263
1156 1264 To set this in your config files use the following::
1157 1265
1158 1266 c.InlineBackend.figure_formats = {'png', 'jpeg'}
1159 1267 c.InlineBackend.print_figure_kwargs.update({'quality' : 90})
1160 1268
1161 1269 Parameters
1162 1270 ----------
1163 1271 *formats : strs
1164 1272 One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
1165 1273 **kwargs :
1166 1274 Keyword args will be relayed to ``figure.canvas.print_figure``.
1167 1275 """
1168 1276 from IPython.core.interactiveshell import InteractiveShell
1169 1277 from IPython.core.pylabtools import select_figure_formats
1170 1278 # build kwargs, starting with InlineBackend config
1171 1279 kw = {}
1172 1280 from ipykernel.pylab.config import InlineBackend
1173 1281 cfg = InlineBackend.instance()
1174 1282 kw.update(cfg.print_figure_kwargs)
1175 1283 kw.update(**kwargs)
1176 1284 shell = InteractiveShell.instance()
1177 1285 select_figure_formats(shell, formats, **kw)
1178 1286
1179 1287 @skip_doctest
1180 1288 def set_matplotlib_close(close=True):
1181 1289 """Set whether the inline backend closes all figures automatically or not.
1182 1290
1183 1291 By default, the inline backend used in the IPython Notebook will close all
1184 1292 matplotlib figures automatically after each cell is run. This means that
1185 1293 plots in different cells won't interfere. Sometimes, you may want to make
1186 1294 a plot in one cell and then refine it in later cells. This can be accomplished
1187 1295 by::
1188 1296
1189 1297 In [1]: set_matplotlib_close(False)
1190 1298
1191 1299 To set this in your config files use the following::
1192 1300
1193 1301 c.InlineBackend.close_figures = False
1194 1302
1195 1303 Parameters
1196 1304 ----------
1197 1305 close : bool
1198 1306 Should all matplotlib figures be automatically closed after each cell is
1199 1307 run?
1200 1308 """
1201 1309 from ipykernel.pylab.config import InlineBackend
1202 1310 cfg = InlineBackend.instance()
1203 1311 cfg.close_figures = close
@@ -1,3223 +1,3225 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2011 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13
14 14 import abc
15 15 import ast
16 16 import atexit
17 17 import builtins as builtin_mod
18 18 import functools
19 19 import os
20 20 import re
21 21 import runpy
22 22 import sys
23 23 import tempfile
24 24 import traceback
25 25 import types
26 26 import subprocess
27 27 import warnings
28 28 from io import open as io_open
29 29
30 30 from pickleshare import PickleShareDB
31 31
32 32 from traitlets.config.configurable import SingletonConfigurable
33 33 from IPython.core import oinspect
34 34 from IPython.core import magic
35 35 from IPython.core import page
36 36 from IPython.core import prefilter
37 37 from IPython.core import ultratb
38 38 from IPython.core.alias import Alias, AliasManager
39 39 from IPython.core.autocall import ExitAutocall
40 40 from IPython.core.builtin_trap import BuiltinTrap
41 41 from IPython.core.events import EventManager, available_events
42 42 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
43 43 from IPython.core.debugger import Pdb
44 44 from IPython.core.display_trap import DisplayTrap
45 45 from IPython.core.displayhook import DisplayHook
46 46 from IPython.core.displaypub import DisplayPublisher
47 47 from IPython.core.error import InputRejected, UsageError
48 48 from IPython.core.extensions import ExtensionManager
49 49 from IPython.core.formatters import DisplayFormatter
50 50 from IPython.core.history import HistoryManager
51 51 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
52 52 from IPython.core.logger import Logger
53 53 from IPython.core.macro import Macro
54 54 from IPython.core.payload import PayloadManager
55 55 from IPython.core.prefilter import PrefilterManager
56 56 from IPython.core.profiledir import ProfileDir
57 57 from IPython.core.usage import default_banner
58 from IPython.display import display
58 59 from IPython.testing.skipdoctest import skip_doctest
59 60 from IPython.utils import PyColorize
60 61 from IPython.utils import io
61 62 from IPython.utils import py3compat
62 63 from IPython.utils import openpy
63 64 from IPython.utils.decorators import undoc
64 65 from IPython.utils.io import ask_yes_no
65 66 from IPython.utils.ipstruct import Struct
66 67 from IPython.paths import get_ipython_dir
67 68 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
68 69 from IPython.utils.process import system, getoutput
69 70 from IPython.utils.strdispatch import StrDispatch
70 71 from IPython.utils.syspathcontext import prepended_to_syspath
71 72 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
72 73 from IPython.utils.tempdir import TemporaryDirectory
73 74 from traitlets import (
74 75 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
75 76 observe, default,
76 77 )
77 78 from warnings import warn
78 79 from logging import error
79 80 import IPython.core.hooks
80 81
81 82 # NoOpContext is deprecated, but ipykernel imports it from here.
82 83 # See https://github.com/ipython/ipykernel/issues/157
83 84 from IPython.utils.contexts import NoOpContext
84 85
85 86 try:
86 87 import docrepr.sphinxify as sphx
87 88
88 89 def sphinxify(doc):
89 90 with TemporaryDirectory() as dirname:
90 91 return {
91 92 'text/html': sphx.sphinxify(doc, dirname),
92 93 'text/plain': doc
93 94 }
94 95 except ImportError:
95 96 sphinxify = None
96 97
97 98
98 99 class ProvisionalWarning(DeprecationWarning):
99 100 """
100 101 Warning class for unstable features
101 102 """
102 103 pass
103 104
104 105 #-----------------------------------------------------------------------------
105 106 # Globals
106 107 #-----------------------------------------------------------------------------
107 108
108 109 # compiled regexps for autoindent management
109 110 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
110 111
111 112 #-----------------------------------------------------------------------------
112 113 # Utilities
113 114 #-----------------------------------------------------------------------------
114 115
115 116 @undoc
116 117 def softspace(file, newvalue):
117 118 """Copied from code.py, to remove the dependency"""
118 119
119 120 oldvalue = 0
120 121 try:
121 122 oldvalue = file.softspace
122 123 except AttributeError:
123 124 pass
124 125 try:
125 126 file.softspace = newvalue
126 127 except (AttributeError, TypeError):
127 128 # "attribute-less object" or "read-only attributes"
128 129 pass
129 130 return oldvalue
130 131
131 132 @undoc
132 133 def no_op(*a, **kw):
133 134 pass
134 135
135 136
136 137 class SpaceInInput(Exception): pass
137 138
138 139
139 140 def get_default_colors():
140 141 "DEPRECATED"
141 142 warn('get_default_color is deprecated since IPython 5.0, and returns `Neutral` on all platforms.',
142 143 DeprecationWarning, stacklevel=2)
143 144 return 'Neutral'
144 145
145 146
146 147 class SeparateUnicode(Unicode):
147 148 r"""A Unicode subclass to validate separate_in, separate_out, etc.
148 149
149 150 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
150 151 """
151 152
152 153 def validate(self, obj, value):
153 154 if value == '0': value = ''
154 155 value = value.replace('\\n','\n')
155 156 return super(SeparateUnicode, self).validate(obj, value)
156 157
157 158
158 159 @undoc
159 160 class DummyMod(object):
160 161 """A dummy module used for IPython's interactive module when
161 162 a namespace must be assigned to the module's __dict__."""
162 163 pass
163 164
164 165
165 166 class ExecutionResult(object):
166 167 """The result of a call to :meth:`InteractiveShell.run_cell`
167 168
168 169 Stores information about what took place.
169 170 """
170 171 execution_count = None
171 172 error_before_exec = None
172 173 error_in_exec = None
173 174 result = None
174 175
175 176 @property
176 177 def success(self):
177 178 return (self.error_before_exec is None) and (self.error_in_exec is None)
178 179
179 180 def raise_error(self):
180 181 """Reraises error if `success` is `False`, otherwise does nothing"""
181 182 if self.error_before_exec is not None:
182 183 raise self.error_before_exec
183 184 if self.error_in_exec is not None:
184 185 raise self.error_in_exec
185 186
186 187 def __repr__(self):
187 188 name = self.__class__.__qualname__
188 189 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
189 190 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
190 191
191 192
192 193 class InteractiveShell(SingletonConfigurable):
193 194 """An enhanced, interactive shell for Python."""
194 195
195 196 _instance = None
196 197
197 198 ast_transformers = List([], help=
198 199 """
199 200 A list of ast.NodeTransformer subclass instances, which will be applied
200 201 to user input before code is run.
201 202 """
202 203 ).tag(config=True)
203 204
204 205 autocall = Enum((0,1,2), default_value=0, help=
205 206 """
206 207 Make IPython automatically call any callable object even if you didn't
207 208 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
208 209 automatically. The value can be '0' to disable the feature, '1' for
209 210 'smart' autocall, where it is not applied if there are no more
210 211 arguments on the line, and '2' for 'full' autocall, where all callable
211 212 objects are automatically called (even if no arguments are present).
212 213 """
213 214 ).tag(config=True)
214 215 # TODO: remove all autoindent logic and put into frontends.
215 216 # We can't do this yet because even runlines uses the autoindent.
216 217 autoindent = Bool(True, help=
217 218 """
218 219 Autoindent IPython code entered interactively.
219 220 """
220 221 ).tag(config=True)
221 222
222 223 automagic = Bool(True, help=
223 224 """
224 225 Enable magic commands to be called without the leading %.
225 226 """
226 227 ).tag(config=True)
227 228
228 229 banner1 = Unicode(default_banner,
229 230 help="""The part of the banner to be printed before the profile"""
230 231 ).tag(config=True)
231 232 banner2 = Unicode('',
232 233 help="""The part of the banner to be printed after the profile"""
233 234 ).tag(config=True)
234 235
235 236 cache_size = Integer(1000, help=
236 237 """
237 238 Set the size of the output cache. The default is 1000, you can
238 239 change it permanently in your config file. Setting it to 0 completely
239 240 disables the caching system, and the minimum value accepted is 3 (if
240 241 you provide a value less than 3, it is reset to 0 and a warning is
241 242 issued). This limit is defined because otherwise you'll spend more
242 243 time re-flushing a too small cache than working
243 244 """
244 245 ).tag(config=True)
245 246 color_info = Bool(True, help=
246 247 """
247 248 Use colors for displaying information about objects. Because this
248 249 information is passed through a pager (like 'less'), and some pagers
249 250 get confused with color codes, this capability can be turned off.
250 251 """
251 252 ).tag(config=True)
252 253 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
253 254 default_value='Neutral',
254 255 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
255 256 ).tag(config=True)
256 257 debug = Bool(False).tag(config=True)
257 258 disable_failing_post_execute = Bool(False,
258 259 help="Don't call post-execute functions that have failed in the past."
259 260 ).tag(config=True)
260 261 display_formatter = Instance(DisplayFormatter, allow_none=True)
261 262 displayhook_class = Type(DisplayHook)
262 263 display_pub_class = Type(DisplayPublisher)
263 264
264 265 sphinxify_docstring = Bool(False, help=
265 266 """
266 267 Enables rich html representation of docstrings. (This requires the
267 268 docrepr module).
268 269 """).tag(config=True)
269 270
270 271 @observe("sphinxify_docstring")
271 272 def _sphinxify_docstring_changed(self, change):
272 273 if change['new']:
273 274 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
274 275
275 276 enable_html_pager = Bool(False, help=
276 277 """
277 278 (Provisional API) enables html representation in mime bundles sent
278 279 to pagers.
279 280 """).tag(config=True)
280 281
281 282 @observe("enable_html_pager")
282 283 def _enable_html_pager_changed(self, change):
283 284 if change['new']:
284 285 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
285 286
286 287 data_pub_class = None
287 288
288 289 exit_now = Bool(False)
289 290 exiter = Instance(ExitAutocall)
290 291 @default('exiter')
291 292 def _exiter_default(self):
292 293 return ExitAutocall(self)
293 294 # Monotonically increasing execution counter
294 295 execution_count = Integer(1)
295 296 filename = Unicode("<ipython console>")
296 297 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
297 298
298 299 # Input splitter, to transform input line by line and detect when a block
299 300 # is ready to be executed.
300 301 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
301 302 (), {'line_input_checker': True})
302 303
303 304 # This InputSplitter instance is used to transform completed cells before
304 305 # running them. It allows cell magics to contain blank lines.
305 306 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
306 307 (), {'line_input_checker': False})
307 308
308 309 logstart = Bool(False, help=
309 310 """
310 311 Start logging to the default log file in overwrite mode.
311 312 Use `logappend` to specify a log file to **append** logs to.
312 313 """
313 314 ).tag(config=True)
314 315 logfile = Unicode('', help=
315 316 """
316 317 The name of the logfile to use.
317 318 """
318 319 ).tag(config=True)
319 320 logappend = Unicode('', help=
320 321 """
321 322 Start logging to the given file in append mode.
322 323 Use `logfile` to specify a log file to **overwrite** logs to.
323 324 """
324 325 ).tag(config=True)
325 326 object_info_string_level = Enum((0,1,2), default_value=0,
326 327 ).tag(config=True)
327 328 pdb = Bool(False, help=
328 329 """
329 330 Automatically call the pdb debugger after every exception.
330 331 """
331 332 ).tag(config=True)
332 333 display_page = Bool(False,
333 334 help="""If True, anything that would be passed to the pager
334 335 will be displayed as regular output instead."""
335 336 ).tag(config=True)
336 337
337 338 # deprecated prompt traits:
338 339
339 340 prompt_in1 = Unicode('In [\\#]: ',
340 341 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
341 342 ).tag(config=True)
342 343 prompt_in2 = Unicode(' .\\D.: ',
343 344 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
344 345 ).tag(config=True)
345 346 prompt_out = Unicode('Out[\\#]: ',
346 347 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
347 348 ).tag(config=True)
348 349 prompts_pad_left = Bool(True,
349 350 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
350 351 ).tag(config=True)
351 352
352 353 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
353 354 def _prompt_trait_changed(self, change):
354 355 name = change['name']
355 356 warn("InteractiveShell.{name} is deprecated since IPython 4.0"
356 357 " and ignored since 5.0, set TerminalInteractiveShell.prompts"
357 358 " object directly.".format(name=name))
358 359
359 360 # protect against weird cases where self.config may not exist:
360 361
361 362 show_rewritten_input = Bool(True,
362 363 help="Show rewritten input, e.g. for autocall."
363 364 ).tag(config=True)
364 365
365 366 quiet = Bool(False).tag(config=True)
366 367
367 368 history_length = Integer(10000,
368 369 help='Total length of command history'
369 370 ).tag(config=True)
370 371
371 372 history_load_length = Integer(1000, help=
372 373 """
373 374 The number of saved history entries to be loaded
374 375 into the history buffer at startup.
375 376 """
376 377 ).tag(config=True)
377 378
378 379 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
379 380 default_value='last_expr',
380 381 help="""
381 382 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
382 383 run interactively (displaying output from expressions)."""
383 384 ).tag(config=True)
384 385
385 386 # TODO: this part of prompt management should be moved to the frontends.
386 387 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
387 388 separate_in = SeparateUnicode('\n').tag(config=True)
388 389 separate_out = SeparateUnicode('').tag(config=True)
389 390 separate_out2 = SeparateUnicode('').tag(config=True)
390 391 wildcards_case_sensitive = Bool(True).tag(config=True)
391 392 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
392 393 default_value='Context',
393 394 help="Switch modes for the IPython exception handlers."
394 395 ).tag(config=True)
395 396
396 397 # Subcomponents of InteractiveShell
397 398 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
398 399 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
399 400 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
400 401 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
401 402 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
402 403 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
403 404 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
404 405 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
405 406
406 407 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
407 408 @property
408 409 def profile(self):
409 410 if self.profile_dir is not None:
410 411 name = os.path.basename(self.profile_dir.location)
411 412 return name.replace('profile_','')
412 413
413 414
414 415 # Private interface
415 416 _post_execute = Dict()
416 417
417 418 # Tracks any GUI loop loaded for pylab
418 419 pylab_gui_select = None
419 420
420 421 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
421 422
422 423 def __init__(self, ipython_dir=None, profile_dir=None,
423 424 user_module=None, user_ns=None,
424 425 custom_exceptions=((), None), **kwargs):
425 426
426 427 # This is where traits with a config_key argument are updated
427 428 # from the values on config.
428 429 super(InteractiveShell, self).__init__(**kwargs)
429 430 if 'PromptManager' in self.config:
430 431 warn('As of IPython 5.0 `PromptManager` config will have no effect'
431 432 ' and has been replaced by TerminalInteractiveShell.prompts_class')
432 433 self.configurables = [self]
433 434
434 435 # These are relatively independent and stateless
435 436 self.init_ipython_dir(ipython_dir)
436 437 self.init_profile_dir(profile_dir)
437 438 self.init_instance_attrs()
438 439 self.init_environment()
439 440
440 441 # Check if we're in a virtualenv, and set up sys.path.
441 442 self.init_virtualenv()
442 443
443 444 # Create namespaces (user_ns, user_global_ns, etc.)
444 445 self.init_create_namespaces(user_module, user_ns)
445 446 # This has to be done after init_create_namespaces because it uses
446 447 # something in self.user_ns, but before init_sys_modules, which
447 448 # is the first thing to modify sys.
448 449 # TODO: When we override sys.stdout and sys.stderr before this class
449 450 # is created, we are saving the overridden ones here. Not sure if this
450 451 # is what we want to do.
451 452 self.save_sys_module_state()
452 453 self.init_sys_modules()
453 454
454 455 # While we're trying to have each part of the code directly access what
455 456 # it needs without keeping redundant references to objects, we have too
456 457 # much legacy code that expects ip.db to exist.
457 458 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
458 459
459 460 self.init_history()
460 461 self.init_encoding()
461 462 self.init_prefilter()
462 463
463 464 self.init_syntax_highlighting()
464 465 self.init_hooks()
465 466 self.init_events()
466 467 self.init_pushd_popd_magic()
467 468 self.init_user_ns()
468 469 self.init_logger()
469 470 self.init_builtins()
470 471
471 472 # The following was in post_config_initialization
472 473 self.init_inspector()
473 474 self.raw_input_original = input
474 475 self.init_completer()
475 476 # TODO: init_io() needs to happen before init_traceback handlers
476 477 # because the traceback handlers hardcode the stdout/stderr streams.
477 478 # This logic in in debugger.Pdb and should eventually be changed.
478 479 self.init_io()
479 480 self.init_traceback_handlers(custom_exceptions)
480 481 self.init_prompts()
481 482 self.init_display_formatter()
482 483 self.init_display_pub()
483 484 self.init_data_pub()
484 485 self.init_displayhook()
485 486 self.init_magics()
486 487 self.init_alias()
487 488 self.init_logstart()
488 489 self.init_pdb()
489 490 self.init_extension_manager()
490 491 self.init_payload()
491 492 self.init_deprecation_warnings()
492 493 self.hooks.late_startup_hook()
493 494 self.events.trigger('shell_initialized', self)
494 495 atexit.register(self.atexit_operations)
495 496
496 497 def get_ipython(self):
497 498 """Return the currently running IPython instance."""
498 499 return self
499 500
500 501 #-------------------------------------------------------------------------
501 502 # Trait changed handlers
502 503 #-------------------------------------------------------------------------
503 504 @observe('ipython_dir')
504 505 def _ipython_dir_changed(self, change):
505 506 ensure_dir_exists(change['new'])
506 507
507 508 def set_autoindent(self,value=None):
508 509 """Set the autoindent flag.
509 510
510 511 If called with no arguments, it acts as a toggle."""
511 512 if value is None:
512 513 self.autoindent = not self.autoindent
513 514 else:
514 515 self.autoindent = value
515 516
516 517 #-------------------------------------------------------------------------
517 518 # init_* methods called by __init__
518 519 #-------------------------------------------------------------------------
519 520
520 521 def init_ipython_dir(self, ipython_dir):
521 522 if ipython_dir is not None:
522 523 self.ipython_dir = ipython_dir
523 524 return
524 525
525 526 self.ipython_dir = get_ipython_dir()
526 527
527 528 def init_profile_dir(self, profile_dir):
528 529 if profile_dir is not None:
529 530 self.profile_dir = profile_dir
530 531 return
531 532 self.profile_dir =\
532 533 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
533 534
534 535 def init_instance_attrs(self):
535 536 self.more = False
536 537
537 538 # command compiler
538 539 self.compile = CachingCompiler()
539 540
540 541 # Make an empty namespace, which extension writers can rely on both
541 542 # existing and NEVER being used by ipython itself. This gives them a
542 543 # convenient location for storing additional information and state
543 544 # their extensions may require, without fear of collisions with other
544 545 # ipython names that may develop later.
545 546 self.meta = Struct()
546 547
547 548 # Temporary files used for various purposes. Deleted at exit.
548 549 self.tempfiles = []
549 550 self.tempdirs = []
550 551
551 552 # keep track of where we started running (mainly for crash post-mortem)
552 553 # This is not being used anywhere currently.
553 554 self.starting_dir = os.getcwd()
554 555
555 556 # Indentation management
556 557 self.indent_current_nsp = 0
557 558
558 559 # Dict to track post-execution functions that have been registered
559 560 self._post_execute = {}
560 561
561 562 def init_environment(self):
562 563 """Any changes we need to make to the user's environment."""
563 564 pass
564 565
565 566 def init_encoding(self):
566 567 # Get system encoding at startup time. Certain terminals (like Emacs
567 568 # under Win32 have it set to None, and we need to have a known valid
568 569 # encoding to use in the raw_input() method
569 570 try:
570 571 self.stdin_encoding = sys.stdin.encoding or 'ascii'
571 572 except AttributeError:
572 573 self.stdin_encoding = 'ascii'
573 574
574 575
575 576 @observe('colors')
576 577 def init_syntax_highlighting(self, changes=None):
577 578 # Python source parser/formatter for syntax highlighting
578 579 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
579 580 self.pycolorize = lambda src: pyformat(src,'str')
580 581
581 582 def refresh_style(self):
582 583 # No-op here, used in subclass
583 584 pass
584 585
585 586 def init_pushd_popd_magic(self):
586 587 # for pushd/popd management
587 588 self.home_dir = get_home_dir()
588 589
589 590 self.dir_stack = []
590 591
591 592 def init_logger(self):
592 593 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
593 594 logmode='rotate')
594 595
595 596 def init_logstart(self):
596 597 """Initialize logging in case it was requested at the command line.
597 598 """
598 599 if self.logappend:
599 600 self.magic('logstart %s append' % self.logappend)
600 601 elif self.logfile:
601 602 self.magic('logstart %s' % self.logfile)
602 603 elif self.logstart:
603 604 self.magic('logstart')
604 605
605 606 def init_deprecation_warnings(self):
606 607 """
607 608 register default filter for deprecation warning.
608 609
609 610 This will allow deprecation warning of function used interactively to show
610 611 warning to users, and still hide deprecation warning from libraries import.
611 612 """
612 613 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
613 614
614 615 def init_builtins(self):
615 616 # A single, static flag that we set to True. Its presence indicates
616 617 # that an IPython shell has been created, and we make no attempts at
617 618 # removing on exit or representing the existence of more than one
618 619 # IPython at a time.
619 620 builtin_mod.__dict__['__IPYTHON__'] = True
621 builtin_mod.__dict__['display'] = display
620 622
621 623 self.builtin_trap = BuiltinTrap(shell=self)
622 624
623 625 def init_inspector(self):
624 626 # Object inspector
625 627 self.inspector = oinspect.Inspector(oinspect.InspectColors,
626 628 PyColorize.ANSICodeColors,
627 629 self.colors,
628 630 self.object_info_string_level)
629 631
630 632 def init_io(self):
631 633 # This will just use sys.stdout and sys.stderr. If you want to
632 634 # override sys.stdout and sys.stderr themselves, you need to do that
633 635 # *before* instantiating this class, because io holds onto
634 636 # references to the underlying streams.
635 637 # io.std* are deprecated, but don't show our own deprecation warnings
636 638 # during initialization of the deprecated API.
637 639 with warnings.catch_warnings():
638 640 warnings.simplefilter('ignore', DeprecationWarning)
639 641 io.stdout = io.IOStream(sys.stdout)
640 642 io.stderr = io.IOStream(sys.stderr)
641 643
642 644 def init_prompts(self):
643 645 # Set system prompts, so that scripts can decide if they are running
644 646 # interactively.
645 647 sys.ps1 = 'In : '
646 648 sys.ps2 = '...: '
647 649 sys.ps3 = 'Out: '
648 650
649 651 def init_display_formatter(self):
650 652 self.display_formatter = DisplayFormatter(parent=self)
651 653 self.configurables.append(self.display_formatter)
652 654
653 655 def init_display_pub(self):
654 656 self.display_pub = self.display_pub_class(parent=self)
655 657 self.configurables.append(self.display_pub)
656 658
657 659 def init_data_pub(self):
658 660 if not self.data_pub_class:
659 661 self.data_pub = None
660 662 return
661 663 self.data_pub = self.data_pub_class(parent=self)
662 664 self.configurables.append(self.data_pub)
663 665
664 666 def init_displayhook(self):
665 667 # Initialize displayhook, set in/out prompts and printing system
666 668 self.displayhook = self.displayhook_class(
667 669 parent=self,
668 670 shell=self,
669 671 cache_size=self.cache_size,
670 672 )
671 673 self.configurables.append(self.displayhook)
672 674 # This is a context manager that installs/revmoes the displayhook at
673 675 # the appropriate time.
674 676 self.display_trap = DisplayTrap(hook=self.displayhook)
675 677
676 678 def init_virtualenv(self):
677 679 """Add a virtualenv to sys.path so the user can import modules from it.
678 680 This isn't perfect: it doesn't use the Python interpreter with which the
679 681 virtualenv was built, and it ignores the --no-site-packages option. A
680 682 warning will appear suggesting the user installs IPython in the
681 683 virtualenv, but for many cases, it probably works well enough.
682 684
683 685 Adapted from code snippets online.
684 686
685 687 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
686 688 """
687 689 if 'VIRTUAL_ENV' not in os.environ:
688 690 # Not in a virtualenv
689 691 return
690 692
691 693 # venv detection:
692 694 # stdlib venv may symlink sys.executable, so we can't use realpath.
693 695 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
694 696 # So we just check every item in the symlink tree (generally <= 3)
695 697 p = os.path.normcase(sys.executable)
696 698 paths = [p]
697 699 while os.path.islink(p):
698 700 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
699 701 paths.append(p)
700 702 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
701 703
702 704 # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
703 705 if p_venv.startswith('\\cygdrive'):
704 706 p_venv = p_venv[11:]
705 707 elif p_venv[1] == ':':
706 708 p_venv = p_venv[2:]
707 709
708 710 if any(p_venv in p for p in paths):
709 711 # Running properly in the virtualenv, don't need to do anything
710 712 return
711 713
712 714 warn("Attempting to work in a virtualenv. If you encounter problems, please "
713 715 "install IPython inside the virtualenv.")
714 716 if sys.platform == "win32":
715 717 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
716 718 else:
717 719 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
718 720 'python%d.%d' % sys.version_info[:2], 'site-packages')
719 721
720 722 import site
721 723 sys.path.insert(0, virtual_env)
722 724 site.addsitedir(virtual_env)
723 725
724 726 #-------------------------------------------------------------------------
725 727 # Things related to injections into the sys module
726 728 #-------------------------------------------------------------------------
727 729
728 730 def save_sys_module_state(self):
729 731 """Save the state of hooks in the sys module.
730 732
731 733 This has to be called after self.user_module is created.
732 734 """
733 735 self._orig_sys_module_state = {'stdin': sys.stdin,
734 736 'stdout': sys.stdout,
735 737 'stderr': sys.stderr,
736 738 'excepthook': sys.excepthook}
737 739 self._orig_sys_modules_main_name = self.user_module.__name__
738 740 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
739 741
740 742 def restore_sys_module_state(self):
741 743 """Restore the state of the sys module."""
742 744 try:
743 745 for k, v in self._orig_sys_module_state.items():
744 746 setattr(sys, k, v)
745 747 except AttributeError:
746 748 pass
747 749 # Reset what what done in self.init_sys_modules
748 750 if self._orig_sys_modules_main_mod is not None:
749 751 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
750 752
751 753 #-------------------------------------------------------------------------
752 754 # Things related to the banner
753 755 #-------------------------------------------------------------------------
754 756
755 757 @property
756 758 def banner(self):
757 759 banner = self.banner1
758 760 if self.profile and self.profile != 'default':
759 761 banner += '\nIPython profile: %s\n' % self.profile
760 762 if self.banner2:
761 763 banner += '\n' + self.banner2
762 764 return banner
763 765
764 766 def show_banner(self, banner=None):
765 767 if banner is None:
766 768 banner = self.banner
767 769 sys.stdout.write(banner)
768 770
769 771 #-------------------------------------------------------------------------
770 772 # Things related to hooks
771 773 #-------------------------------------------------------------------------
772 774
773 775 def init_hooks(self):
774 776 # hooks holds pointers used for user-side customizations
775 777 self.hooks = Struct()
776 778
777 779 self.strdispatchers = {}
778 780
779 781 # Set all default hooks, defined in the IPython.hooks module.
780 782 hooks = IPython.core.hooks
781 783 for hook_name in hooks.__all__:
782 784 # default hooks have priority 100, i.e. low; user hooks should have
783 785 # 0-100 priority
784 786 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
785 787
786 788 if self.display_page:
787 789 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
788 790
789 791 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
790 792 _warn_deprecated=True):
791 793 """set_hook(name,hook) -> sets an internal IPython hook.
792 794
793 795 IPython exposes some of its internal API as user-modifiable hooks. By
794 796 adding your function to one of these hooks, you can modify IPython's
795 797 behavior to call at runtime your own routines."""
796 798
797 799 # At some point in the future, this should validate the hook before it
798 800 # accepts it. Probably at least check that the hook takes the number
799 801 # of args it's supposed to.
800 802
801 803 f = types.MethodType(hook,self)
802 804
803 805 # check if the hook is for strdispatcher first
804 806 if str_key is not None:
805 807 sdp = self.strdispatchers.get(name, StrDispatch())
806 808 sdp.add_s(str_key, f, priority )
807 809 self.strdispatchers[name] = sdp
808 810 return
809 811 if re_key is not None:
810 812 sdp = self.strdispatchers.get(name, StrDispatch())
811 813 sdp.add_re(re.compile(re_key), f, priority )
812 814 self.strdispatchers[name] = sdp
813 815 return
814 816
815 817 dp = getattr(self.hooks, name, None)
816 818 if name not in IPython.core.hooks.__all__:
817 819 print("Warning! Hook '%s' is not one of %s" % \
818 820 (name, IPython.core.hooks.__all__ ))
819 821
820 822 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
821 823 alternative = IPython.core.hooks.deprecated[name]
822 824 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2)
823 825
824 826 if not dp:
825 827 dp = IPython.core.hooks.CommandChainDispatcher()
826 828
827 829 try:
828 830 dp.add(f,priority)
829 831 except AttributeError:
830 832 # it was not commandchain, plain old func - replace
831 833 dp = f
832 834
833 835 setattr(self.hooks,name, dp)
834 836
835 837 #-------------------------------------------------------------------------
836 838 # Things related to events
837 839 #-------------------------------------------------------------------------
838 840
839 841 def init_events(self):
840 842 self.events = EventManager(self, available_events)
841 843
842 844 self.events.register("pre_execute", self._clear_warning_registry)
843 845
844 846 def register_post_execute(self, func):
845 847 """DEPRECATED: Use ip.events.register('post_run_cell', func)
846 848
847 849 Register a function for calling after code execution.
848 850 """
849 851 warn("ip.register_post_execute is deprecated, use "
850 852 "ip.events.register('post_run_cell', func) instead.", stacklevel=2)
851 853 self.events.register('post_run_cell', func)
852 854
853 855 def _clear_warning_registry(self):
854 856 # clear the warning registry, so that different code blocks with
855 857 # overlapping line number ranges don't cause spurious suppression of
856 858 # warnings (see gh-6611 for details)
857 859 if "__warningregistry__" in self.user_global_ns:
858 860 del self.user_global_ns["__warningregistry__"]
859 861
860 862 #-------------------------------------------------------------------------
861 863 # Things related to the "main" module
862 864 #-------------------------------------------------------------------------
863 865
864 866 def new_main_mod(self, filename, modname):
865 867 """Return a new 'main' module object for user code execution.
866 868
867 869 ``filename`` should be the path of the script which will be run in the
868 870 module. Requests with the same filename will get the same module, with
869 871 its namespace cleared.
870 872
871 873 ``modname`` should be the module name - normally either '__main__' or
872 874 the basename of the file without the extension.
873 875
874 876 When scripts are executed via %run, we must keep a reference to their
875 877 __main__ module around so that Python doesn't
876 878 clear it, rendering references to module globals useless.
877 879
878 880 This method keeps said reference in a private dict, keyed by the
879 881 absolute path of the script. This way, for multiple executions of the
880 882 same script we only keep one copy of the namespace (the last one),
881 883 thus preventing memory leaks from old references while allowing the
882 884 objects from the last execution to be accessible.
883 885 """
884 886 filename = os.path.abspath(filename)
885 887 try:
886 888 main_mod = self._main_mod_cache[filename]
887 889 except KeyError:
888 890 main_mod = self._main_mod_cache[filename] = types.ModuleType(
889 891 modname,
890 892 doc="Module created for script run in IPython")
891 893 else:
892 894 main_mod.__dict__.clear()
893 895 main_mod.__name__ = modname
894 896
895 897 main_mod.__file__ = filename
896 898 # It seems pydoc (and perhaps others) needs any module instance to
897 899 # implement a __nonzero__ method
898 900 main_mod.__nonzero__ = lambda : True
899 901
900 902 return main_mod
901 903
902 904 def clear_main_mod_cache(self):
903 905 """Clear the cache of main modules.
904 906
905 907 Mainly for use by utilities like %reset.
906 908
907 909 Examples
908 910 --------
909 911
910 912 In [15]: import IPython
911 913
912 914 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
913 915
914 916 In [17]: len(_ip._main_mod_cache) > 0
915 917 Out[17]: True
916 918
917 919 In [18]: _ip.clear_main_mod_cache()
918 920
919 921 In [19]: len(_ip._main_mod_cache) == 0
920 922 Out[19]: True
921 923 """
922 924 self._main_mod_cache.clear()
923 925
924 926 #-------------------------------------------------------------------------
925 927 # Things related to debugging
926 928 #-------------------------------------------------------------------------
927 929
928 930 def init_pdb(self):
929 931 # Set calling of pdb on exceptions
930 932 # self.call_pdb is a property
931 933 self.call_pdb = self.pdb
932 934
933 935 def _get_call_pdb(self):
934 936 return self._call_pdb
935 937
936 938 def _set_call_pdb(self,val):
937 939
938 940 if val not in (0,1,False,True):
939 941 raise ValueError('new call_pdb value must be boolean')
940 942
941 943 # store value in instance
942 944 self._call_pdb = val
943 945
944 946 # notify the actual exception handlers
945 947 self.InteractiveTB.call_pdb = val
946 948
947 949 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
948 950 'Control auto-activation of pdb at exceptions')
949 951
950 952 def debugger(self,force=False):
951 953 """Call the pdb debugger.
952 954
953 955 Keywords:
954 956
955 957 - force(False): by default, this routine checks the instance call_pdb
956 958 flag and does not actually invoke the debugger if the flag is false.
957 959 The 'force' option forces the debugger to activate even if the flag
958 960 is false.
959 961 """
960 962
961 963 if not (force or self.call_pdb):
962 964 return
963 965
964 966 if not hasattr(sys,'last_traceback'):
965 967 error('No traceback has been produced, nothing to debug.')
966 968 return
967 969
968 970 self.InteractiveTB.debugger(force=True)
969 971
970 972 #-------------------------------------------------------------------------
971 973 # Things related to IPython's various namespaces
972 974 #-------------------------------------------------------------------------
973 975 default_user_namespaces = True
974 976
975 977 def init_create_namespaces(self, user_module=None, user_ns=None):
976 978 # Create the namespace where the user will operate. user_ns is
977 979 # normally the only one used, and it is passed to the exec calls as
978 980 # the locals argument. But we do carry a user_global_ns namespace
979 981 # given as the exec 'globals' argument, This is useful in embedding
980 982 # situations where the ipython shell opens in a context where the
981 983 # distinction between locals and globals is meaningful. For
982 984 # non-embedded contexts, it is just the same object as the user_ns dict.
983 985
984 986 # FIXME. For some strange reason, __builtins__ is showing up at user
985 987 # level as a dict instead of a module. This is a manual fix, but I
986 988 # should really track down where the problem is coming from. Alex
987 989 # Schmolck reported this problem first.
988 990
989 991 # A useful post by Alex Martelli on this topic:
990 992 # Re: inconsistent value from __builtins__
991 993 # Von: Alex Martelli <aleaxit@yahoo.com>
992 994 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
993 995 # Gruppen: comp.lang.python
994 996
995 997 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
996 998 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
997 999 # > <type 'dict'>
998 1000 # > >>> print type(__builtins__)
999 1001 # > <type 'module'>
1000 1002 # > Is this difference in return value intentional?
1001 1003
1002 1004 # Well, it's documented that '__builtins__' can be either a dictionary
1003 1005 # or a module, and it's been that way for a long time. Whether it's
1004 1006 # intentional (or sensible), I don't know. In any case, the idea is
1005 1007 # that if you need to access the built-in namespace directly, you
1006 1008 # should start with "import __builtin__" (note, no 's') which will
1007 1009 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1008 1010
1009 1011 # These routines return a properly built module and dict as needed by
1010 1012 # the rest of the code, and can also be used by extension writers to
1011 1013 # generate properly initialized namespaces.
1012 1014 if (user_ns is not None) or (user_module is not None):
1013 1015 self.default_user_namespaces = False
1014 1016 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1015 1017
1016 1018 # A record of hidden variables we have added to the user namespace, so
1017 1019 # we can list later only variables defined in actual interactive use.
1018 1020 self.user_ns_hidden = {}
1019 1021
1020 1022 # Now that FakeModule produces a real module, we've run into a nasty
1021 1023 # problem: after script execution (via %run), the module where the user
1022 1024 # code ran is deleted. Now that this object is a true module (needed
1023 1025 # so doctest and other tools work correctly), the Python module
1024 1026 # teardown mechanism runs over it, and sets to None every variable
1025 1027 # present in that module. Top-level references to objects from the
1026 1028 # script survive, because the user_ns is updated with them. However,
1027 1029 # calling functions defined in the script that use other things from
1028 1030 # the script will fail, because the function's closure had references
1029 1031 # to the original objects, which are now all None. So we must protect
1030 1032 # these modules from deletion by keeping a cache.
1031 1033 #
1032 1034 # To avoid keeping stale modules around (we only need the one from the
1033 1035 # last run), we use a dict keyed with the full path to the script, so
1034 1036 # only the last version of the module is held in the cache. Note,
1035 1037 # however, that we must cache the module *namespace contents* (their
1036 1038 # __dict__). Because if we try to cache the actual modules, old ones
1037 1039 # (uncached) could be destroyed while still holding references (such as
1038 1040 # those held by GUI objects that tend to be long-lived)>
1039 1041 #
1040 1042 # The %reset command will flush this cache. See the cache_main_mod()
1041 1043 # and clear_main_mod_cache() methods for details on use.
1042 1044
1043 1045 # This is the cache used for 'main' namespaces
1044 1046 self._main_mod_cache = {}
1045 1047
1046 1048 # A table holding all the namespaces IPython deals with, so that
1047 1049 # introspection facilities can search easily.
1048 1050 self.ns_table = {'user_global':self.user_module.__dict__,
1049 1051 'user_local':self.user_ns,
1050 1052 'builtin':builtin_mod.__dict__
1051 1053 }
1052 1054
1053 1055 @property
1054 1056 def user_global_ns(self):
1055 1057 return self.user_module.__dict__
1056 1058
1057 1059 def prepare_user_module(self, user_module=None, user_ns=None):
1058 1060 """Prepare the module and namespace in which user code will be run.
1059 1061
1060 1062 When IPython is started normally, both parameters are None: a new module
1061 1063 is created automatically, and its __dict__ used as the namespace.
1062 1064
1063 1065 If only user_module is provided, its __dict__ is used as the namespace.
1064 1066 If only user_ns is provided, a dummy module is created, and user_ns
1065 1067 becomes the global namespace. If both are provided (as they may be
1066 1068 when embedding), user_ns is the local namespace, and user_module
1067 1069 provides the global namespace.
1068 1070
1069 1071 Parameters
1070 1072 ----------
1071 1073 user_module : module, optional
1072 1074 The current user module in which IPython is being run. If None,
1073 1075 a clean module will be created.
1074 1076 user_ns : dict, optional
1075 1077 A namespace in which to run interactive commands.
1076 1078
1077 1079 Returns
1078 1080 -------
1079 1081 A tuple of user_module and user_ns, each properly initialised.
1080 1082 """
1081 1083 if user_module is None and user_ns is not None:
1082 1084 user_ns.setdefault("__name__", "__main__")
1083 1085 user_module = DummyMod()
1084 1086 user_module.__dict__ = user_ns
1085 1087
1086 1088 if user_module is None:
1087 1089 user_module = types.ModuleType("__main__",
1088 1090 doc="Automatically created module for IPython interactive environment")
1089 1091
1090 1092 # We must ensure that __builtin__ (without the final 's') is always
1091 1093 # available and pointing to the __builtin__ *module*. For more details:
1092 1094 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1093 1095 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1094 1096 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1095 1097
1096 1098 if user_ns is None:
1097 1099 user_ns = user_module.__dict__
1098 1100
1099 1101 return user_module, user_ns
1100 1102
1101 1103 def init_sys_modules(self):
1102 1104 # We need to insert into sys.modules something that looks like a
1103 1105 # module but which accesses the IPython namespace, for shelve and
1104 1106 # pickle to work interactively. Normally they rely on getting
1105 1107 # everything out of __main__, but for embedding purposes each IPython
1106 1108 # instance has its own private namespace, so we can't go shoving
1107 1109 # everything into __main__.
1108 1110
1109 1111 # note, however, that we should only do this for non-embedded
1110 1112 # ipythons, which really mimic the __main__.__dict__ with their own
1111 1113 # namespace. Embedded instances, on the other hand, should not do
1112 1114 # this because they need to manage the user local/global namespaces
1113 1115 # only, but they live within a 'normal' __main__ (meaning, they
1114 1116 # shouldn't overtake the execution environment of the script they're
1115 1117 # embedded in).
1116 1118
1117 1119 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1118 1120 main_name = self.user_module.__name__
1119 1121 sys.modules[main_name] = self.user_module
1120 1122
1121 1123 def init_user_ns(self):
1122 1124 """Initialize all user-visible namespaces to their minimum defaults.
1123 1125
1124 1126 Certain history lists are also initialized here, as they effectively
1125 1127 act as user namespaces.
1126 1128
1127 1129 Notes
1128 1130 -----
1129 1131 All data structures here are only filled in, they are NOT reset by this
1130 1132 method. If they were not empty before, data will simply be added to
1131 1133 therm.
1132 1134 """
1133 1135 # This function works in two parts: first we put a few things in
1134 1136 # user_ns, and we sync that contents into user_ns_hidden so that these
1135 1137 # initial variables aren't shown by %who. After the sync, we add the
1136 1138 # rest of what we *do* want the user to see with %who even on a new
1137 1139 # session (probably nothing, so they really only see their own stuff)
1138 1140
1139 1141 # The user dict must *always* have a __builtin__ reference to the
1140 1142 # Python standard __builtin__ namespace, which must be imported.
1141 1143 # This is so that certain operations in prompt evaluation can be
1142 1144 # reliably executed with builtins. Note that we can NOT use
1143 1145 # __builtins__ (note the 's'), because that can either be a dict or a
1144 1146 # module, and can even mutate at runtime, depending on the context
1145 1147 # (Python makes no guarantees on it). In contrast, __builtin__ is
1146 1148 # always a module object, though it must be explicitly imported.
1147 1149
1148 1150 # For more details:
1149 1151 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1150 1152 ns = {}
1151 1153
1152 1154 # make global variables for user access to the histories
1153 1155 ns['_ih'] = self.history_manager.input_hist_parsed
1154 1156 ns['_oh'] = self.history_manager.output_hist
1155 1157 ns['_dh'] = self.history_manager.dir_hist
1156 1158
1157 1159 # user aliases to input and output histories. These shouldn't show up
1158 1160 # in %who, as they can have very large reprs.
1159 1161 ns['In'] = self.history_manager.input_hist_parsed
1160 1162 ns['Out'] = self.history_manager.output_hist
1161 1163
1162 1164 # Store myself as the public api!!!
1163 1165 ns['get_ipython'] = self.get_ipython
1164 1166
1165 1167 ns['exit'] = self.exiter
1166 1168 ns['quit'] = self.exiter
1167 1169
1168 1170 # Sync what we've added so far to user_ns_hidden so these aren't seen
1169 1171 # by %who
1170 1172 self.user_ns_hidden.update(ns)
1171 1173
1172 1174 # Anything put into ns now would show up in %who. Think twice before
1173 1175 # putting anything here, as we really want %who to show the user their
1174 1176 # stuff, not our variables.
1175 1177
1176 1178 # Finally, update the real user's namespace
1177 1179 self.user_ns.update(ns)
1178 1180
1179 1181 @property
1180 1182 def all_ns_refs(self):
1181 1183 """Get a list of references to all the namespace dictionaries in which
1182 1184 IPython might store a user-created object.
1183 1185
1184 1186 Note that this does not include the displayhook, which also caches
1185 1187 objects from the output."""
1186 1188 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1187 1189 [m.__dict__ for m in self._main_mod_cache.values()]
1188 1190
1189 1191 def reset(self, new_session=True):
1190 1192 """Clear all internal namespaces, and attempt to release references to
1191 1193 user objects.
1192 1194
1193 1195 If new_session is True, a new history session will be opened.
1194 1196 """
1195 1197 # Clear histories
1196 1198 self.history_manager.reset(new_session)
1197 1199 # Reset counter used to index all histories
1198 1200 if new_session:
1199 1201 self.execution_count = 1
1200 1202
1201 1203 # Flush cached output items
1202 1204 if self.displayhook.do_full_cache:
1203 1205 self.displayhook.flush()
1204 1206
1205 1207 # The main execution namespaces must be cleared very carefully,
1206 1208 # skipping the deletion of the builtin-related keys, because doing so
1207 1209 # would cause errors in many object's __del__ methods.
1208 1210 if self.user_ns is not self.user_global_ns:
1209 1211 self.user_ns.clear()
1210 1212 ns = self.user_global_ns
1211 1213 drop_keys = set(ns.keys())
1212 1214 drop_keys.discard('__builtin__')
1213 1215 drop_keys.discard('__builtins__')
1214 1216 drop_keys.discard('__name__')
1215 1217 for k in drop_keys:
1216 1218 del ns[k]
1217 1219
1218 1220 self.user_ns_hidden.clear()
1219 1221
1220 1222 # Restore the user namespaces to minimal usability
1221 1223 self.init_user_ns()
1222 1224
1223 1225 # Restore the default and user aliases
1224 1226 self.alias_manager.clear_aliases()
1225 1227 self.alias_manager.init_aliases()
1226 1228
1227 1229 # Flush the private list of module references kept for script
1228 1230 # execution protection
1229 1231 self.clear_main_mod_cache()
1230 1232
1231 1233 def del_var(self, varname, by_name=False):
1232 1234 """Delete a variable from the various namespaces, so that, as
1233 1235 far as possible, we're not keeping any hidden references to it.
1234 1236
1235 1237 Parameters
1236 1238 ----------
1237 1239 varname : str
1238 1240 The name of the variable to delete.
1239 1241 by_name : bool
1240 1242 If True, delete variables with the given name in each
1241 1243 namespace. If False (default), find the variable in the user
1242 1244 namespace, and delete references to it.
1243 1245 """
1244 1246 if varname in ('__builtin__', '__builtins__'):
1245 1247 raise ValueError("Refusing to delete %s" % varname)
1246 1248
1247 1249 ns_refs = self.all_ns_refs
1248 1250
1249 1251 if by_name: # Delete by name
1250 1252 for ns in ns_refs:
1251 1253 try:
1252 1254 del ns[varname]
1253 1255 except KeyError:
1254 1256 pass
1255 1257 else: # Delete by object
1256 1258 try:
1257 1259 obj = self.user_ns[varname]
1258 1260 except KeyError:
1259 1261 raise NameError("name '%s' is not defined" % varname)
1260 1262 # Also check in output history
1261 1263 ns_refs.append(self.history_manager.output_hist)
1262 1264 for ns in ns_refs:
1263 1265 to_delete = [n for n, o in ns.items() if o is obj]
1264 1266 for name in to_delete:
1265 1267 del ns[name]
1266 1268
1267 1269 # displayhook keeps extra references, but not in a dictionary
1268 1270 for name in ('_', '__', '___'):
1269 1271 if getattr(self.displayhook, name) is obj:
1270 1272 setattr(self.displayhook, name, None)
1271 1273
1272 1274 def reset_selective(self, regex=None):
1273 1275 """Clear selective variables from internal namespaces based on a
1274 1276 specified regular expression.
1275 1277
1276 1278 Parameters
1277 1279 ----------
1278 1280 regex : string or compiled pattern, optional
1279 1281 A regular expression pattern that will be used in searching
1280 1282 variable names in the users namespaces.
1281 1283 """
1282 1284 if regex is not None:
1283 1285 try:
1284 1286 m = re.compile(regex)
1285 1287 except TypeError:
1286 1288 raise TypeError('regex must be a string or compiled pattern')
1287 1289 # Search for keys in each namespace that match the given regex
1288 1290 # If a match is found, delete the key/value pair.
1289 1291 for ns in self.all_ns_refs:
1290 1292 for var in ns:
1291 1293 if m.search(var):
1292 1294 del ns[var]
1293 1295
1294 1296 def push(self, variables, interactive=True):
1295 1297 """Inject a group of variables into the IPython user namespace.
1296 1298
1297 1299 Parameters
1298 1300 ----------
1299 1301 variables : dict, str or list/tuple of str
1300 1302 The variables to inject into the user's namespace. If a dict, a
1301 1303 simple update is done. If a str, the string is assumed to have
1302 1304 variable names separated by spaces. A list/tuple of str can also
1303 1305 be used to give the variable names. If just the variable names are
1304 1306 give (list/tuple/str) then the variable values looked up in the
1305 1307 callers frame.
1306 1308 interactive : bool
1307 1309 If True (default), the variables will be listed with the ``who``
1308 1310 magic.
1309 1311 """
1310 1312 vdict = None
1311 1313
1312 1314 # We need a dict of name/value pairs to do namespace updates.
1313 1315 if isinstance(variables, dict):
1314 1316 vdict = variables
1315 1317 elif isinstance(variables, (str, list, tuple)):
1316 1318 if isinstance(variables, str):
1317 1319 vlist = variables.split()
1318 1320 else:
1319 1321 vlist = variables
1320 1322 vdict = {}
1321 1323 cf = sys._getframe(1)
1322 1324 for name in vlist:
1323 1325 try:
1324 1326 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1325 1327 except:
1326 1328 print('Could not get variable %s from %s' %
1327 1329 (name,cf.f_code.co_name))
1328 1330 else:
1329 1331 raise ValueError('variables must be a dict/str/list/tuple')
1330 1332
1331 1333 # Propagate variables to user namespace
1332 1334 self.user_ns.update(vdict)
1333 1335
1334 1336 # And configure interactive visibility
1335 1337 user_ns_hidden = self.user_ns_hidden
1336 1338 if interactive:
1337 1339 for name in vdict:
1338 1340 user_ns_hidden.pop(name, None)
1339 1341 else:
1340 1342 user_ns_hidden.update(vdict)
1341 1343
1342 1344 def drop_by_id(self, variables):
1343 1345 """Remove a dict of variables from the user namespace, if they are the
1344 1346 same as the values in the dictionary.
1345 1347
1346 1348 This is intended for use by extensions: variables that they've added can
1347 1349 be taken back out if they are unloaded, without removing any that the
1348 1350 user has overwritten.
1349 1351
1350 1352 Parameters
1351 1353 ----------
1352 1354 variables : dict
1353 1355 A dictionary mapping object names (as strings) to the objects.
1354 1356 """
1355 1357 for name, obj in variables.items():
1356 1358 if name in self.user_ns and self.user_ns[name] is obj:
1357 1359 del self.user_ns[name]
1358 1360 self.user_ns_hidden.pop(name, None)
1359 1361
1360 1362 #-------------------------------------------------------------------------
1361 1363 # Things related to object introspection
1362 1364 #-------------------------------------------------------------------------
1363 1365
1364 1366 def _ofind(self, oname, namespaces=None):
1365 1367 """Find an object in the available namespaces.
1366 1368
1367 1369 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1368 1370
1369 1371 Has special code to detect magic functions.
1370 1372 """
1371 1373 oname = oname.strip()
1372 1374 if not oname.startswith(ESC_MAGIC) and \
1373 1375 not oname.startswith(ESC_MAGIC2) and \
1374 1376 not all(a.isidentifier() for a in oname.split(".")):
1375 1377 return {'found': False}
1376 1378
1377 1379 if namespaces is None:
1378 1380 # Namespaces to search in:
1379 1381 # Put them in a list. The order is important so that we
1380 1382 # find things in the same order that Python finds them.
1381 1383 namespaces = [ ('Interactive', self.user_ns),
1382 1384 ('Interactive (global)', self.user_global_ns),
1383 1385 ('Python builtin', builtin_mod.__dict__),
1384 1386 ]
1385 1387
1386 1388 ismagic = False
1387 1389 isalias = False
1388 1390 found = False
1389 1391 ospace = None
1390 1392 parent = None
1391 1393 obj = None
1392 1394
1393 1395 # Look for the given name by splitting it in parts. If the head is
1394 1396 # found, then we look for all the remaining parts as members, and only
1395 1397 # declare success if we can find them all.
1396 1398 oname_parts = oname.split('.')
1397 1399 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1398 1400 for nsname,ns in namespaces:
1399 1401 try:
1400 1402 obj = ns[oname_head]
1401 1403 except KeyError:
1402 1404 continue
1403 1405 else:
1404 1406 for idx, part in enumerate(oname_rest):
1405 1407 try:
1406 1408 parent = obj
1407 1409 # The last part is looked up in a special way to avoid
1408 1410 # descriptor invocation as it may raise or have side
1409 1411 # effects.
1410 1412 if idx == len(oname_rest) - 1:
1411 1413 obj = self._getattr_property(obj, part)
1412 1414 else:
1413 1415 obj = getattr(obj, part)
1414 1416 except:
1415 1417 # Blanket except b/c some badly implemented objects
1416 1418 # allow __getattr__ to raise exceptions other than
1417 1419 # AttributeError, which then crashes IPython.
1418 1420 break
1419 1421 else:
1420 1422 # If we finish the for loop (no break), we got all members
1421 1423 found = True
1422 1424 ospace = nsname
1423 1425 break # namespace loop
1424 1426
1425 1427 # Try to see if it's magic
1426 1428 if not found:
1427 1429 obj = None
1428 1430 if oname.startswith(ESC_MAGIC2):
1429 1431 oname = oname.lstrip(ESC_MAGIC2)
1430 1432 obj = self.find_cell_magic(oname)
1431 1433 elif oname.startswith(ESC_MAGIC):
1432 1434 oname = oname.lstrip(ESC_MAGIC)
1433 1435 obj = self.find_line_magic(oname)
1434 1436 else:
1435 1437 # search without prefix, so run? will find %run?
1436 1438 obj = self.find_line_magic(oname)
1437 1439 if obj is None:
1438 1440 obj = self.find_cell_magic(oname)
1439 1441 if obj is not None:
1440 1442 found = True
1441 1443 ospace = 'IPython internal'
1442 1444 ismagic = True
1443 1445 isalias = isinstance(obj, Alias)
1444 1446
1445 1447 # Last try: special-case some literals like '', [], {}, etc:
1446 1448 if not found and oname_head in ["''",'""','[]','{}','()']:
1447 1449 obj = eval(oname_head)
1448 1450 found = True
1449 1451 ospace = 'Interactive'
1450 1452
1451 1453 return {
1452 1454 'obj':obj,
1453 1455 'found':found,
1454 1456 'parent':parent,
1455 1457 'ismagic':ismagic,
1456 1458 'isalias':isalias,
1457 1459 'namespace':ospace
1458 1460 }
1459 1461
1460 1462 @staticmethod
1461 1463 def _getattr_property(obj, attrname):
1462 1464 """Property-aware getattr to use in object finding.
1463 1465
1464 1466 If attrname represents a property, return it unevaluated (in case it has
1465 1467 side effects or raises an error.
1466 1468
1467 1469 """
1468 1470 if not isinstance(obj, type):
1469 1471 try:
1470 1472 # `getattr(type(obj), attrname)` is not guaranteed to return
1471 1473 # `obj`, but does so for property:
1472 1474 #
1473 1475 # property.__get__(self, None, cls) -> self
1474 1476 #
1475 1477 # The universal alternative is to traverse the mro manually
1476 1478 # searching for attrname in class dicts.
1477 1479 attr = getattr(type(obj), attrname)
1478 1480 except AttributeError:
1479 1481 pass
1480 1482 else:
1481 1483 # This relies on the fact that data descriptors (with both
1482 1484 # __get__ & __set__ magic methods) take precedence over
1483 1485 # instance-level attributes:
1484 1486 #
1485 1487 # class A(object):
1486 1488 # @property
1487 1489 # def foobar(self): return 123
1488 1490 # a = A()
1489 1491 # a.__dict__['foobar'] = 345
1490 1492 # a.foobar # == 123
1491 1493 #
1492 1494 # So, a property may be returned right away.
1493 1495 if isinstance(attr, property):
1494 1496 return attr
1495 1497
1496 1498 # Nothing helped, fall back.
1497 1499 return getattr(obj, attrname)
1498 1500
1499 1501 def _object_find(self, oname, namespaces=None):
1500 1502 """Find an object and return a struct with info about it."""
1501 1503 return Struct(self._ofind(oname, namespaces))
1502 1504
1503 1505 def _inspect(self, meth, oname, namespaces=None, **kw):
1504 1506 """Generic interface to the inspector system.
1505 1507
1506 1508 This function is meant to be called by pdef, pdoc & friends.
1507 1509 """
1508 1510 info = self._object_find(oname, namespaces)
1509 1511 docformat = sphinxify if self.sphinxify_docstring else None
1510 1512 if info.found:
1511 1513 pmethod = getattr(self.inspector, meth)
1512 1514 # TODO: only apply format_screen to the plain/text repr of the mime
1513 1515 # bundle.
1514 1516 formatter = format_screen if info.ismagic else docformat
1515 1517 if meth == 'pdoc':
1516 1518 pmethod(info.obj, oname, formatter)
1517 1519 elif meth == 'pinfo':
1518 1520 pmethod(info.obj, oname, formatter, info,
1519 1521 enable_html_pager=self.enable_html_pager, **kw)
1520 1522 else:
1521 1523 pmethod(info.obj, oname)
1522 1524 else:
1523 1525 print('Object `%s` not found.' % oname)
1524 1526 return 'not found' # so callers can take other action
1525 1527
1526 1528 def object_inspect(self, oname, detail_level=0):
1527 1529 """Get object info about oname"""
1528 1530 with self.builtin_trap:
1529 1531 info = self._object_find(oname)
1530 1532 if info.found:
1531 1533 return self.inspector.info(info.obj, oname, info=info,
1532 1534 detail_level=detail_level
1533 1535 )
1534 1536 else:
1535 1537 return oinspect.object_info(name=oname, found=False)
1536 1538
1537 1539 def object_inspect_text(self, oname, detail_level=0):
1538 1540 """Get object info as formatted text"""
1539 1541 return self.object_inspect_mime(oname, detail_level)['text/plain']
1540 1542
1541 1543 def object_inspect_mime(self, oname, detail_level=0):
1542 1544 """Get object info as a mimebundle of formatted representations.
1543 1545
1544 1546 A mimebundle is a dictionary, keyed by mime-type.
1545 1547 It must always have the key `'text/plain'`.
1546 1548 """
1547 1549 with self.builtin_trap:
1548 1550 info = self._object_find(oname)
1549 1551 if info.found:
1550 1552 return self.inspector._get_info(info.obj, oname, info=info,
1551 1553 detail_level=detail_level
1552 1554 )
1553 1555 else:
1554 1556 raise KeyError(oname)
1555 1557
1556 1558 #-------------------------------------------------------------------------
1557 1559 # Things related to history management
1558 1560 #-------------------------------------------------------------------------
1559 1561
1560 1562 def init_history(self):
1561 1563 """Sets up the command history, and starts regular autosaves."""
1562 1564 self.history_manager = HistoryManager(shell=self, parent=self)
1563 1565 self.configurables.append(self.history_manager)
1564 1566
1565 1567 #-------------------------------------------------------------------------
1566 1568 # Things related to exception handling and tracebacks (not debugging)
1567 1569 #-------------------------------------------------------------------------
1568 1570
1569 1571 debugger_cls = Pdb
1570 1572
1571 1573 def init_traceback_handlers(self, custom_exceptions):
1572 1574 # Syntax error handler.
1573 1575 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1574 1576
1575 1577 # The interactive one is initialized with an offset, meaning we always
1576 1578 # want to remove the topmost item in the traceback, which is our own
1577 1579 # internal code. Valid modes: ['Plain','Context','Verbose']
1578 1580 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1579 1581 color_scheme='NoColor',
1580 1582 tb_offset = 1,
1581 1583 check_cache=check_linecache_ipython,
1582 1584 debugger_cls=self.debugger_cls, parent=self)
1583 1585
1584 1586 # The instance will store a pointer to the system-wide exception hook,
1585 1587 # so that runtime code (such as magics) can access it. This is because
1586 1588 # during the read-eval loop, it may get temporarily overwritten.
1587 1589 self.sys_excepthook = sys.excepthook
1588 1590
1589 1591 # and add any custom exception handlers the user may have specified
1590 1592 self.set_custom_exc(*custom_exceptions)
1591 1593
1592 1594 # Set the exception mode
1593 1595 self.InteractiveTB.set_mode(mode=self.xmode)
1594 1596
1595 1597 def set_custom_exc(self, exc_tuple, handler):
1596 1598 """set_custom_exc(exc_tuple, handler)
1597 1599
1598 1600 Set a custom exception handler, which will be called if any of the
1599 1601 exceptions in exc_tuple occur in the mainloop (specifically, in the
1600 1602 run_code() method).
1601 1603
1602 1604 Parameters
1603 1605 ----------
1604 1606
1605 1607 exc_tuple : tuple of exception classes
1606 1608 A *tuple* of exception classes, for which to call the defined
1607 1609 handler. It is very important that you use a tuple, and NOT A
1608 1610 LIST here, because of the way Python's except statement works. If
1609 1611 you only want to trap a single exception, use a singleton tuple::
1610 1612
1611 1613 exc_tuple == (MyCustomException,)
1612 1614
1613 1615 handler : callable
1614 1616 handler must have the following signature::
1615 1617
1616 1618 def my_handler(self, etype, value, tb, tb_offset=None):
1617 1619 ...
1618 1620 return structured_traceback
1619 1621
1620 1622 Your handler must return a structured traceback (a list of strings),
1621 1623 or None.
1622 1624
1623 1625 This will be made into an instance method (via types.MethodType)
1624 1626 of IPython itself, and it will be called if any of the exceptions
1625 1627 listed in the exc_tuple are caught. If the handler is None, an
1626 1628 internal basic one is used, which just prints basic info.
1627 1629
1628 1630 To protect IPython from crashes, if your handler ever raises an
1629 1631 exception or returns an invalid result, it will be immediately
1630 1632 disabled.
1631 1633
1632 1634 WARNING: by putting in your own exception handler into IPython's main
1633 1635 execution loop, you run a very good chance of nasty crashes. This
1634 1636 facility should only be used if you really know what you are doing."""
1635 1637 if not isinstance(exc_tuple, tuple):
1636 1638 raise TypeError("The custom exceptions must be given as a tuple.")
1637 1639
1638 1640 def dummy_handler(self, etype, value, tb, tb_offset=None):
1639 1641 print('*** Simple custom exception handler ***')
1640 1642 print('Exception type :', etype)
1641 1643 print('Exception value:', value)
1642 1644 print('Traceback :', tb)
1643 1645
1644 1646 def validate_stb(stb):
1645 1647 """validate structured traceback return type
1646 1648
1647 1649 return type of CustomTB *should* be a list of strings, but allow
1648 1650 single strings or None, which are harmless.
1649 1651
1650 1652 This function will *always* return a list of strings,
1651 1653 and will raise a TypeError if stb is inappropriate.
1652 1654 """
1653 1655 msg = "CustomTB must return list of strings, not %r" % stb
1654 1656 if stb is None:
1655 1657 return []
1656 1658 elif isinstance(stb, str):
1657 1659 return [stb]
1658 1660 elif not isinstance(stb, list):
1659 1661 raise TypeError(msg)
1660 1662 # it's a list
1661 1663 for line in stb:
1662 1664 # check every element
1663 1665 if not isinstance(line, str):
1664 1666 raise TypeError(msg)
1665 1667 return stb
1666 1668
1667 1669 if handler is None:
1668 1670 wrapped = dummy_handler
1669 1671 else:
1670 1672 def wrapped(self,etype,value,tb,tb_offset=None):
1671 1673 """wrap CustomTB handler, to protect IPython from user code
1672 1674
1673 1675 This makes it harder (but not impossible) for custom exception
1674 1676 handlers to crash IPython.
1675 1677 """
1676 1678 try:
1677 1679 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1678 1680 return validate_stb(stb)
1679 1681 except:
1680 1682 # clear custom handler immediately
1681 1683 self.set_custom_exc((), None)
1682 1684 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1683 1685 # show the exception in handler first
1684 1686 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1685 1687 print(self.InteractiveTB.stb2text(stb))
1686 1688 print("The original exception:")
1687 1689 stb = self.InteractiveTB.structured_traceback(
1688 1690 (etype,value,tb), tb_offset=tb_offset
1689 1691 )
1690 1692 return stb
1691 1693
1692 1694 self.CustomTB = types.MethodType(wrapped,self)
1693 1695 self.custom_exceptions = exc_tuple
1694 1696
1695 1697 def excepthook(self, etype, value, tb):
1696 1698 """One more defense for GUI apps that call sys.excepthook.
1697 1699
1698 1700 GUI frameworks like wxPython trap exceptions and call
1699 1701 sys.excepthook themselves. I guess this is a feature that
1700 1702 enables them to keep running after exceptions that would
1701 1703 otherwise kill their mainloop. This is a bother for IPython
1702 1704 which excepts to catch all of the program exceptions with a try:
1703 1705 except: statement.
1704 1706
1705 1707 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1706 1708 any app directly invokes sys.excepthook, it will look to the user like
1707 1709 IPython crashed. In order to work around this, we can disable the
1708 1710 CrashHandler and replace it with this excepthook instead, which prints a
1709 1711 regular traceback using our InteractiveTB. In this fashion, apps which
1710 1712 call sys.excepthook will generate a regular-looking exception from
1711 1713 IPython, and the CrashHandler will only be triggered by real IPython
1712 1714 crashes.
1713 1715
1714 1716 This hook should be used sparingly, only in places which are not likely
1715 1717 to be true IPython errors.
1716 1718 """
1717 1719 self.showtraceback((etype, value, tb), tb_offset=0)
1718 1720
1719 1721 def _get_exc_info(self, exc_tuple=None):
1720 1722 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1721 1723
1722 1724 Ensures sys.last_type,value,traceback hold the exc_info we found,
1723 1725 from whichever source.
1724 1726
1725 1727 raises ValueError if none of these contain any information
1726 1728 """
1727 1729 if exc_tuple is None:
1728 1730 etype, value, tb = sys.exc_info()
1729 1731 else:
1730 1732 etype, value, tb = exc_tuple
1731 1733
1732 1734 if etype is None:
1733 1735 if hasattr(sys, 'last_type'):
1734 1736 etype, value, tb = sys.last_type, sys.last_value, \
1735 1737 sys.last_traceback
1736 1738
1737 1739 if etype is None:
1738 1740 raise ValueError("No exception to find")
1739 1741
1740 1742 # Now store the exception info in sys.last_type etc.
1741 1743 # WARNING: these variables are somewhat deprecated and not
1742 1744 # necessarily safe to use in a threaded environment, but tools
1743 1745 # like pdb depend on their existence, so let's set them. If we
1744 1746 # find problems in the field, we'll need to revisit their use.
1745 1747 sys.last_type = etype
1746 1748 sys.last_value = value
1747 1749 sys.last_traceback = tb
1748 1750
1749 1751 return etype, value, tb
1750 1752
1751 1753 def show_usage_error(self, exc):
1752 1754 """Show a short message for UsageErrors
1753 1755
1754 1756 These are special exceptions that shouldn't show a traceback.
1755 1757 """
1756 1758 print("UsageError: %s" % exc, file=sys.stderr)
1757 1759
1758 1760 def get_exception_only(self, exc_tuple=None):
1759 1761 """
1760 1762 Return as a string (ending with a newline) the exception that
1761 1763 just occurred, without any traceback.
1762 1764 """
1763 1765 etype, value, tb = self._get_exc_info(exc_tuple)
1764 1766 msg = traceback.format_exception_only(etype, value)
1765 1767 return ''.join(msg)
1766 1768
1767 1769 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1768 1770 exception_only=False, running_compiled_code=False):
1769 1771 """Display the exception that just occurred.
1770 1772
1771 1773 If nothing is known about the exception, this is the method which
1772 1774 should be used throughout the code for presenting user tracebacks,
1773 1775 rather than directly invoking the InteractiveTB object.
1774 1776
1775 1777 A specific showsyntaxerror() also exists, but this method can take
1776 1778 care of calling it if needed, so unless you are explicitly catching a
1777 1779 SyntaxError exception, don't try to analyze the stack manually and
1778 1780 simply call this method."""
1779 1781
1780 1782 try:
1781 1783 try:
1782 1784 etype, value, tb = self._get_exc_info(exc_tuple)
1783 1785 except ValueError:
1784 1786 print('No traceback available to show.', file=sys.stderr)
1785 1787 return
1786 1788
1787 1789 if issubclass(etype, SyntaxError):
1788 1790 # Though this won't be called by syntax errors in the input
1789 1791 # line, there may be SyntaxError cases with imported code.
1790 1792 self.showsyntaxerror(filename, running_compiled_code)
1791 1793 elif etype is UsageError:
1792 1794 self.show_usage_error(value)
1793 1795 else:
1794 1796 if exception_only:
1795 1797 stb = ['An exception has occurred, use %tb to see '
1796 1798 'the full traceback.\n']
1797 1799 stb.extend(self.InteractiveTB.get_exception_only(etype,
1798 1800 value))
1799 1801 else:
1800 1802 try:
1801 1803 # Exception classes can customise their traceback - we
1802 1804 # use this in IPython.parallel for exceptions occurring
1803 1805 # in the engines. This should return a list of strings.
1804 1806 stb = value._render_traceback_()
1805 1807 except Exception:
1806 1808 stb = self.InteractiveTB.structured_traceback(etype,
1807 1809 value, tb, tb_offset=tb_offset)
1808 1810
1809 1811 self._showtraceback(etype, value, stb)
1810 1812 if self.call_pdb:
1811 1813 # drop into debugger
1812 1814 self.debugger(force=True)
1813 1815 return
1814 1816
1815 1817 # Actually show the traceback
1816 1818 self._showtraceback(etype, value, stb)
1817 1819
1818 1820 except KeyboardInterrupt:
1819 1821 print('\n' + self.get_exception_only(), file=sys.stderr)
1820 1822
1821 1823 def _showtraceback(self, etype, evalue, stb):
1822 1824 """Actually show a traceback.
1823 1825
1824 1826 Subclasses may override this method to put the traceback on a different
1825 1827 place, like a side channel.
1826 1828 """
1827 1829 print(self.InteractiveTB.stb2text(stb))
1828 1830
1829 1831 def showsyntaxerror(self, filename=None, running_compiled_code=False):
1830 1832 """Display the syntax error that just occurred.
1831 1833
1832 1834 This doesn't display a stack trace because there isn't one.
1833 1835
1834 1836 If a filename is given, it is stuffed in the exception instead
1835 1837 of what was there before (because Python's parser always uses
1836 1838 "<string>" when reading from a string).
1837 1839
1838 1840 If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
1839 1841 longer stack trace will be displayed.
1840 1842 """
1841 1843 etype, value, last_traceback = self._get_exc_info()
1842 1844
1843 1845 if filename and issubclass(etype, SyntaxError):
1844 1846 try:
1845 1847 value.filename = filename
1846 1848 except:
1847 1849 # Not the format we expect; leave it alone
1848 1850 pass
1849 1851
1850 1852 # If the error occured when executing compiled code, we should provide full stacktrace.
1851 1853 elist = traceback.extract_tb(last_traceback) if running_compiled_code else []
1852 1854 stb = self.SyntaxTB.structured_traceback(etype, value, elist)
1853 1855 self._showtraceback(etype, value, stb)
1854 1856
1855 1857 # This is overridden in TerminalInteractiveShell to show a message about
1856 1858 # the %paste magic.
1857 1859 def showindentationerror(self):
1858 1860 """Called by run_cell when there's an IndentationError in code entered
1859 1861 at the prompt.
1860 1862
1861 1863 This is overridden in TerminalInteractiveShell to show a message about
1862 1864 the %paste magic."""
1863 1865 self.showsyntaxerror()
1864 1866
1865 1867 #-------------------------------------------------------------------------
1866 1868 # Things related to readline
1867 1869 #-------------------------------------------------------------------------
1868 1870
1869 1871 def init_readline(self):
1870 1872 """DEPRECATED
1871 1873
1872 1874 Moved to terminal subclass, here only to simplify the init logic."""
1873 1875 # Set a number of methods that depend on readline to be no-op
1874 1876 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1875 1877 DeprecationWarning, stacklevel=2)
1876 1878 self.set_custom_completer = no_op
1877 1879
1878 1880 @skip_doctest
1879 1881 def set_next_input(self, s, replace=False):
1880 1882 """ Sets the 'default' input string for the next command line.
1881 1883
1882 1884 Example::
1883 1885
1884 1886 In [1]: _ip.set_next_input("Hello Word")
1885 1887 In [2]: Hello Word_ # cursor is here
1886 1888 """
1887 1889 self.rl_next_input = s
1888 1890
1889 1891 def _indent_current_str(self):
1890 1892 """return the current level of indentation as a string"""
1891 1893 return self.input_splitter.indent_spaces * ' '
1892 1894
1893 1895 #-------------------------------------------------------------------------
1894 1896 # Things related to text completion
1895 1897 #-------------------------------------------------------------------------
1896 1898
1897 1899 def init_completer(self):
1898 1900 """Initialize the completion machinery.
1899 1901
1900 1902 This creates completion machinery that can be used by client code,
1901 1903 either interactively in-process (typically triggered by the readline
1902 1904 library), programmatically (such as in test suites) or out-of-process
1903 1905 (typically over the network by remote frontends).
1904 1906 """
1905 1907 from IPython.core.completer import IPCompleter
1906 1908 from IPython.core.completerlib import (module_completer,
1907 1909 magic_run_completer, cd_completer, reset_completer)
1908 1910
1909 1911 self.Completer = IPCompleter(shell=self,
1910 1912 namespace=self.user_ns,
1911 1913 global_namespace=self.user_global_ns,
1912 1914 parent=self,
1913 1915 )
1914 1916 self.configurables.append(self.Completer)
1915 1917
1916 1918 # Add custom completers to the basic ones built into IPCompleter
1917 1919 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1918 1920 self.strdispatchers['complete_command'] = sdisp
1919 1921 self.Completer.custom_completers = sdisp
1920 1922
1921 1923 self.set_hook('complete_command', module_completer, str_key = 'import')
1922 1924 self.set_hook('complete_command', module_completer, str_key = 'from')
1923 1925 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1924 1926 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1925 1927 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1926 1928 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1927 1929
1928 1930
1929 1931 def complete(self, text, line=None, cursor_pos=None):
1930 1932 """Return the completed text and a list of completions.
1931 1933
1932 1934 Parameters
1933 1935 ----------
1934 1936
1935 1937 text : string
1936 1938 A string of text to be completed on. It can be given as empty and
1937 1939 instead a line/position pair are given. In this case, the
1938 1940 completer itself will split the line like readline does.
1939 1941
1940 1942 line : string, optional
1941 1943 The complete line that text is part of.
1942 1944
1943 1945 cursor_pos : int, optional
1944 1946 The position of the cursor on the input line.
1945 1947
1946 1948 Returns
1947 1949 -------
1948 1950 text : string
1949 1951 The actual text that was completed.
1950 1952
1951 1953 matches : list
1952 1954 A sorted list with all possible completions.
1953 1955
1954 1956 The optional arguments allow the completion to take more context into
1955 1957 account, and are part of the low-level completion API.
1956 1958
1957 1959 This is a wrapper around the completion mechanism, similar to what
1958 1960 readline does at the command line when the TAB key is hit. By
1959 1961 exposing it as a method, it can be used by other non-readline
1960 1962 environments (such as GUIs) for text completion.
1961 1963
1962 1964 Simple usage example:
1963 1965
1964 1966 In [1]: x = 'hello'
1965 1967
1966 1968 In [2]: _ip.complete('x.l')
1967 1969 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1968 1970 """
1969 1971
1970 1972 # Inject names into __builtin__ so we can complete on the added names.
1971 1973 with self.builtin_trap:
1972 1974 return self.Completer.complete(text, line, cursor_pos)
1973 1975
1974 1976 def set_custom_completer(self, completer, pos=0):
1975 1977 """Adds a new custom completer function.
1976 1978
1977 1979 The position argument (defaults to 0) is the index in the completers
1978 1980 list where you want the completer to be inserted."""
1979 1981
1980 1982 newcomp = types.MethodType(completer,self.Completer)
1981 1983 self.Completer.matchers.insert(pos,newcomp)
1982 1984
1983 1985 def set_completer_frame(self, frame=None):
1984 1986 """Set the frame of the completer."""
1985 1987 if frame:
1986 1988 self.Completer.namespace = frame.f_locals
1987 1989 self.Completer.global_namespace = frame.f_globals
1988 1990 else:
1989 1991 self.Completer.namespace = self.user_ns
1990 1992 self.Completer.global_namespace = self.user_global_ns
1991 1993
1992 1994 #-------------------------------------------------------------------------
1993 1995 # Things related to magics
1994 1996 #-------------------------------------------------------------------------
1995 1997
1996 1998 def init_magics(self):
1997 1999 from IPython.core import magics as m
1998 2000 self.magics_manager = magic.MagicsManager(shell=self,
1999 2001 parent=self,
2000 2002 user_magics=m.UserMagics(self))
2001 2003 self.configurables.append(self.magics_manager)
2002 2004
2003 2005 # Expose as public API from the magics manager
2004 2006 self.register_magics = self.magics_manager.register
2005 2007
2006 2008 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2007 2009 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2008 2010 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2009 2011 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2010 2012 )
2011 2013
2012 2014 # Register Magic Aliases
2013 2015 mman = self.magics_manager
2014 2016 # FIXME: magic aliases should be defined by the Magics classes
2015 2017 # or in MagicsManager, not here
2016 2018 mman.register_alias('ed', 'edit')
2017 2019 mman.register_alias('hist', 'history')
2018 2020 mman.register_alias('rep', 'recall')
2019 2021 mman.register_alias('SVG', 'svg', 'cell')
2020 2022 mman.register_alias('HTML', 'html', 'cell')
2021 2023 mman.register_alias('file', 'writefile', 'cell')
2022 2024
2023 2025 # FIXME: Move the color initialization to the DisplayHook, which
2024 2026 # should be split into a prompt manager and displayhook. We probably
2025 2027 # even need a centralize colors management object.
2026 2028 self.magic('colors %s' % self.colors)
2027 2029
2028 2030 # Defined here so that it's included in the documentation
2029 2031 @functools.wraps(magic.MagicsManager.register_function)
2030 2032 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2031 2033 self.magics_manager.register_function(func,
2032 2034 magic_kind=magic_kind, magic_name=magic_name)
2033 2035
2034 2036 def run_line_magic(self, magic_name, line):
2035 2037 """Execute the given line magic.
2036 2038
2037 2039 Parameters
2038 2040 ----------
2039 2041 magic_name : str
2040 2042 Name of the desired magic function, without '%' prefix.
2041 2043
2042 2044 line : str
2043 2045 The rest of the input line as a single string.
2044 2046 """
2045 2047 fn = self.find_line_magic(magic_name)
2046 2048 if fn is None:
2047 2049 cm = self.find_cell_magic(magic_name)
2048 2050 etpl = "Line magic function `%%%s` not found%s."
2049 2051 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2050 2052 'did you mean that instead?)' % magic_name )
2051 2053 error(etpl % (magic_name, extra))
2052 2054 else:
2053 2055 # Note: this is the distance in the stack to the user's frame.
2054 2056 # This will need to be updated if the internal calling logic gets
2055 2057 # refactored, or else we'll be expanding the wrong variables.
2056 2058 stack_depth = 2
2057 2059 magic_arg_s = self.var_expand(line, stack_depth)
2058 2060 # Put magic args in a list so we can call with f(*a) syntax
2059 2061 args = [magic_arg_s]
2060 2062 kwargs = {}
2061 2063 # Grab local namespace if we need it:
2062 2064 if getattr(fn, "needs_local_scope", False):
2063 2065 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2064 2066 with self.builtin_trap:
2065 2067 result = fn(*args,**kwargs)
2066 2068 return result
2067 2069
2068 2070 def run_cell_magic(self, magic_name, line, cell):
2069 2071 """Execute the given cell magic.
2070 2072
2071 2073 Parameters
2072 2074 ----------
2073 2075 magic_name : str
2074 2076 Name of the desired magic function, without '%' prefix.
2075 2077
2076 2078 line : str
2077 2079 The rest of the first input line as a single string.
2078 2080
2079 2081 cell : str
2080 2082 The body of the cell as a (possibly multiline) string.
2081 2083 """
2082 2084 fn = self.find_cell_magic(magic_name)
2083 2085 if fn is None:
2084 2086 lm = self.find_line_magic(magic_name)
2085 2087 etpl = "Cell magic `%%{0}` not found{1}."
2086 2088 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2087 2089 'did you mean that instead?)'.format(magic_name))
2088 2090 error(etpl.format(magic_name, extra))
2089 2091 elif cell == '':
2090 2092 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2091 2093 if self.find_line_magic(magic_name) is not None:
2092 2094 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2093 2095 raise UsageError(message)
2094 2096 else:
2095 2097 # Note: this is the distance in the stack to the user's frame.
2096 2098 # This will need to be updated if the internal calling logic gets
2097 2099 # refactored, or else we'll be expanding the wrong variables.
2098 2100 stack_depth = 2
2099 2101 magic_arg_s = self.var_expand(line, stack_depth)
2100 2102 with self.builtin_trap:
2101 2103 result = fn(magic_arg_s, cell)
2102 2104 return result
2103 2105
2104 2106 def find_line_magic(self, magic_name):
2105 2107 """Find and return a line magic by name.
2106 2108
2107 2109 Returns None if the magic isn't found."""
2108 2110 return self.magics_manager.magics['line'].get(magic_name)
2109 2111
2110 2112 def find_cell_magic(self, magic_name):
2111 2113 """Find and return a cell magic by name.
2112 2114
2113 2115 Returns None if the magic isn't found."""
2114 2116 return self.magics_manager.magics['cell'].get(magic_name)
2115 2117
2116 2118 def find_magic(self, magic_name, magic_kind='line'):
2117 2119 """Find and return a magic of the given type by name.
2118 2120
2119 2121 Returns None if the magic isn't found."""
2120 2122 return self.magics_manager.magics[magic_kind].get(magic_name)
2121 2123
2122 2124 def magic(self, arg_s):
2123 2125 """DEPRECATED. Use run_line_magic() instead.
2124 2126
2125 2127 Call a magic function by name.
2126 2128
2127 2129 Input: a string containing the name of the magic function to call and
2128 2130 any additional arguments to be passed to the magic.
2129 2131
2130 2132 magic('name -opt foo bar') is equivalent to typing at the ipython
2131 2133 prompt:
2132 2134
2133 2135 In[1]: %name -opt foo bar
2134 2136
2135 2137 To call a magic without arguments, simply use magic('name').
2136 2138
2137 2139 This provides a proper Python function to call IPython's magics in any
2138 2140 valid Python code you can type at the interpreter, including loops and
2139 2141 compound statements.
2140 2142 """
2141 2143 # TODO: should we issue a loud deprecation warning here?
2142 2144 magic_name, _, magic_arg_s = arg_s.partition(' ')
2143 2145 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2144 2146 return self.run_line_magic(magic_name, magic_arg_s)
2145 2147
2146 2148 #-------------------------------------------------------------------------
2147 2149 # Things related to macros
2148 2150 #-------------------------------------------------------------------------
2149 2151
2150 2152 def define_macro(self, name, themacro):
2151 2153 """Define a new macro
2152 2154
2153 2155 Parameters
2154 2156 ----------
2155 2157 name : str
2156 2158 The name of the macro.
2157 2159 themacro : str or Macro
2158 2160 The action to do upon invoking the macro. If a string, a new
2159 2161 Macro object is created by passing the string to it.
2160 2162 """
2161 2163
2162 2164 from IPython.core import macro
2163 2165
2164 2166 if isinstance(themacro, str):
2165 2167 themacro = macro.Macro(themacro)
2166 2168 if not isinstance(themacro, macro.Macro):
2167 2169 raise ValueError('A macro must be a string or a Macro instance.')
2168 2170 self.user_ns[name] = themacro
2169 2171
2170 2172 #-------------------------------------------------------------------------
2171 2173 # Things related to the running of system commands
2172 2174 #-------------------------------------------------------------------------
2173 2175
2174 2176 def system_piped(self, cmd):
2175 2177 """Call the given cmd in a subprocess, piping stdout/err
2176 2178
2177 2179 Parameters
2178 2180 ----------
2179 2181 cmd : str
2180 2182 Command to execute (can not end in '&', as background processes are
2181 2183 not supported. Should not be a command that expects input
2182 2184 other than simple text.
2183 2185 """
2184 2186 if cmd.rstrip().endswith('&'):
2185 2187 # this is *far* from a rigorous test
2186 2188 # We do not support backgrounding processes because we either use
2187 2189 # pexpect or pipes to read from. Users can always just call
2188 2190 # os.system() or use ip.system=ip.system_raw
2189 2191 # if they really want a background process.
2190 2192 raise OSError("Background processes not supported.")
2191 2193
2192 2194 # we explicitly do NOT return the subprocess status code, because
2193 2195 # a non-None value would trigger :func:`sys.displayhook` calls.
2194 2196 # Instead, we store the exit_code in user_ns.
2195 2197 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2196 2198
2197 2199 def system_raw(self, cmd):
2198 2200 """Call the given cmd in a subprocess using os.system on Windows or
2199 2201 subprocess.call using the system shell on other platforms.
2200 2202
2201 2203 Parameters
2202 2204 ----------
2203 2205 cmd : str
2204 2206 Command to execute.
2205 2207 """
2206 2208 cmd = self.var_expand(cmd, depth=1)
2207 2209 # protect os.system from UNC paths on Windows, which it can't handle:
2208 2210 if sys.platform == 'win32':
2209 2211 from IPython.utils._process_win32 import AvoidUNCPath
2210 2212 with AvoidUNCPath() as path:
2211 2213 if path is not None:
2212 2214 cmd = '"pushd %s &&"%s' % (path, cmd)
2213 2215 try:
2214 2216 ec = os.system(cmd)
2215 2217 except KeyboardInterrupt:
2216 2218 print('\n' + self.get_exception_only(), file=sys.stderr)
2217 2219 ec = -2
2218 2220 else:
2219 2221 # For posix the result of the subprocess.call() below is an exit
2220 2222 # code, which by convention is zero for success, positive for
2221 2223 # program failure. Exit codes above 128 are reserved for signals,
2222 2224 # and the formula for converting a signal to an exit code is usually
2223 2225 # signal_number+128. To more easily differentiate between exit
2224 2226 # codes and signals, ipython uses negative numbers. For instance
2225 2227 # since control-c is signal 2 but exit code 130, ipython's
2226 2228 # _exit_code variable will read -2. Note that some shells like
2227 2229 # csh and fish don't follow sh/bash conventions for exit codes.
2228 2230 executable = os.environ.get('SHELL', None)
2229 2231 try:
2230 2232 # Use env shell instead of default /bin/sh
2231 2233 ec = subprocess.call(cmd, shell=True, executable=executable)
2232 2234 except KeyboardInterrupt:
2233 2235 # intercept control-C; a long traceback is not useful here
2234 2236 print('\n' + self.get_exception_only(), file=sys.stderr)
2235 2237 ec = 130
2236 2238 if ec > 128:
2237 2239 ec = -(ec - 128)
2238 2240
2239 2241 # We explicitly do NOT return the subprocess status code, because
2240 2242 # a non-None value would trigger :func:`sys.displayhook` calls.
2241 2243 # Instead, we store the exit_code in user_ns. Note the semantics
2242 2244 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2243 2245 # but raising SystemExit(_exit_code) will give status 254!
2244 2246 self.user_ns['_exit_code'] = ec
2245 2247
2246 2248 # use piped system by default, because it is better behaved
2247 2249 system = system_piped
2248 2250
2249 2251 def getoutput(self, cmd, split=True, depth=0):
2250 2252 """Get output (possibly including stderr) from a subprocess.
2251 2253
2252 2254 Parameters
2253 2255 ----------
2254 2256 cmd : str
2255 2257 Command to execute (can not end in '&', as background processes are
2256 2258 not supported.
2257 2259 split : bool, optional
2258 2260 If True, split the output into an IPython SList. Otherwise, an
2259 2261 IPython LSString is returned. These are objects similar to normal
2260 2262 lists and strings, with a few convenience attributes for easier
2261 2263 manipulation of line-based output. You can use '?' on them for
2262 2264 details.
2263 2265 depth : int, optional
2264 2266 How many frames above the caller are the local variables which should
2265 2267 be expanded in the command string? The default (0) assumes that the
2266 2268 expansion variables are in the stack frame calling this function.
2267 2269 """
2268 2270 if cmd.rstrip().endswith('&'):
2269 2271 # this is *far* from a rigorous test
2270 2272 raise OSError("Background processes not supported.")
2271 2273 out = getoutput(self.var_expand(cmd, depth=depth+1))
2272 2274 if split:
2273 2275 out = SList(out.splitlines())
2274 2276 else:
2275 2277 out = LSString(out)
2276 2278 return out
2277 2279
2278 2280 #-------------------------------------------------------------------------
2279 2281 # Things related to aliases
2280 2282 #-------------------------------------------------------------------------
2281 2283
2282 2284 def init_alias(self):
2283 2285 self.alias_manager = AliasManager(shell=self, parent=self)
2284 2286 self.configurables.append(self.alias_manager)
2285 2287
2286 2288 #-------------------------------------------------------------------------
2287 2289 # Things related to extensions
2288 2290 #-------------------------------------------------------------------------
2289 2291
2290 2292 def init_extension_manager(self):
2291 2293 self.extension_manager = ExtensionManager(shell=self, parent=self)
2292 2294 self.configurables.append(self.extension_manager)
2293 2295
2294 2296 #-------------------------------------------------------------------------
2295 2297 # Things related to payloads
2296 2298 #-------------------------------------------------------------------------
2297 2299
2298 2300 def init_payload(self):
2299 2301 self.payload_manager = PayloadManager(parent=self)
2300 2302 self.configurables.append(self.payload_manager)
2301 2303
2302 2304 #-------------------------------------------------------------------------
2303 2305 # Things related to the prefilter
2304 2306 #-------------------------------------------------------------------------
2305 2307
2306 2308 def init_prefilter(self):
2307 2309 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2308 2310 self.configurables.append(self.prefilter_manager)
2309 2311 # Ultimately this will be refactored in the new interpreter code, but
2310 2312 # for now, we should expose the main prefilter method (there's legacy
2311 2313 # code out there that may rely on this).
2312 2314 self.prefilter = self.prefilter_manager.prefilter_lines
2313 2315
2314 2316 def auto_rewrite_input(self, cmd):
2315 2317 """Print to the screen the rewritten form of the user's command.
2316 2318
2317 2319 This shows visual feedback by rewriting input lines that cause
2318 2320 automatic calling to kick in, like::
2319 2321
2320 2322 /f x
2321 2323
2322 2324 into::
2323 2325
2324 2326 ------> f(x)
2325 2327
2326 2328 after the user's input prompt. This helps the user understand that the
2327 2329 input line was transformed automatically by IPython.
2328 2330 """
2329 2331 if not self.show_rewritten_input:
2330 2332 return
2331 2333
2332 2334 # This is overridden in TerminalInteractiveShell to use fancy prompts
2333 2335 print("------> " + cmd)
2334 2336
2335 2337 #-------------------------------------------------------------------------
2336 2338 # Things related to extracting values/expressions from kernel and user_ns
2337 2339 #-------------------------------------------------------------------------
2338 2340
2339 2341 def _user_obj_error(self):
2340 2342 """return simple exception dict
2341 2343
2342 2344 for use in user_expressions
2343 2345 """
2344 2346
2345 2347 etype, evalue, tb = self._get_exc_info()
2346 2348 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2347 2349
2348 2350 exc_info = {
2349 2351 u'status' : 'error',
2350 2352 u'traceback' : stb,
2351 2353 u'ename' : etype.__name__,
2352 2354 u'evalue' : py3compat.safe_unicode(evalue),
2353 2355 }
2354 2356
2355 2357 return exc_info
2356 2358
2357 2359 def _format_user_obj(self, obj):
2358 2360 """format a user object to display dict
2359 2361
2360 2362 for use in user_expressions
2361 2363 """
2362 2364
2363 2365 data, md = self.display_formatter.format(obj)
2364 2366 value = {
2365 2367 'status' : 'ok',
2366 2368 'data' : data,
2367 2369 'metadata' : md,
2368 2370 }
2369 2371 return value
2370 2372
2371 2373 def user_expressions(self, expressions):
2372 2374 """Evaluate a dict of expressions in the user's namespace.
2373 2375
2374 2376 Parameters
2375 2377 ----------
2376 2378 expressions : dict
2377 2379 A dict with string keys and string values. The expression values
2378 2380 should be valid Python expressions, each of which will be evaluated
2379 2381 in the user namespace.
2380 2382
2381 2383 Returns
2382 2384 -------
2383 2385 A dict, keyed like the input expressions dict, with the rich mime-typed
2384 2386 display_data of each value.
2385 2387 """
2386 2388 out = {}
2387 2389 user_ns = self.user_ns
2388 2390 global_ns = self.user_global_ns
2389 2391
2390 2392 for key, expr in expressions.items():
2391 2393 try:
2392 2394 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2393 2395 except:
2394 2396 value = self._user_obj_error()
2395 2397 out[key] = value
2396 2398 return out
2397 2399
2398 2400 #-------------------------------------------------------------------------
2399 2401 # Things related to the running of code
2400 2402 #-------------------------------------------------------------------------
2401 2403
2402 2404 def ex(self, cmd):
2403 2405 """Execute a normal python statement in user namespace."""
2404 2406 with self.builtin_trap:
2405 2407 exec(cmd, self.user_global_ns, self.user_ns)
2406 2408
2407 2409 def ev(self, expr):
2408 2410 """Evaluate python expression expr in user namespace.
2409 2411
2410 2412 Returns the result of evaluation
2411 2413 """
2412 2414 with self.builtin_trap:
2413 2415 return eval(expr, self.user_global_ns, self.user_ns)
2414 2416
2415 2417 def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
2416 2418 """A safe version of the builtin execfile().
2417 2419
2418 2420 This version will never throw an exception, but instead print
2419 2421 helpful error messages to the screen. This only works on pure
2420 2422 Python files with the .py extension.
2421 2423
2422 2424 Parameters
2423 2425 ----------
2424 2426 fname : string
2425 2427 The name of the file to be executed.
2426 2428 where : tuple
2427 2429 One or two namespaces, passed to execfile() as (globals,locals).
2428 2430 If only one is given, it is passed as both.
2429 2431 exit_ignore : bool (False)
2430 2432 If True, then silence SystemExit for non-zero status (it is always
2431 2433 silenced for zero status, as it is so common).
2432 2434 raise_exceptions : bool (False)
2433 2435 If True raise exceptions everywhere. Meant for testing.
2434 2436 shell_futures : bool (False)
2435 2437 If True, the code will share future statements with the interactive
2436 2438 shell. It will both be affected by previous __future__ imports, and
2437 2439 any __future__ imports in the code will affect the shell. If False,
2438 2440 __future__ imports are not shared in either direction.
2439 2441
2440 2442 """
2441 2443 fname = os.path.abspath(os.path.expanduser(fname))
2442 2444
2443 2445 # Make sure we can open the file
2444 2446 try:
2445 2447 with open(fname):
2446 2448 pass
2447 2449 except:
2448 2450 warn('Could not open file <%s> for safe execution.' % fname)
2449 2451 return
2450 2452
2451 2453 # Find things also in current directory. This is needed to mimic the
2452 2454 # behavior of running a script from the system command line, where
2453 2455 # Python inserts the script's directory into sys.path
2454 2456 dname = os.path.dirname(fname)
2455 2457
2456 2458 with prepended_to_syspath(dname), self.builtin_trap:
2457 2459 try:
2458 2460 glob, loc = (where + (None, ))[:2]
2459 2461 py3compat.execfile(
2460 2462 fname, glob, loc,
2461 2463 self.compile if shell_futures else None)
2462 2464 except SystemExit as status:
2463 2465 # If the call was made with 0 or None exit status (sys.exit(0)
2464 2466 # or sys.exit() ), don't bother showing a traceback, as both of
2465 2467 # these are considered normal by the OS:
2466 2468 # > python -c'import sys;sys.exit(0)'; echo $?
2467 2469 # 0
2468 2470 # > python -c'import sys;sys.exit()'; echo $?
2469 2471 # 0
2470 2472 # For other exit status, we show the exception unless
2471 2473 # explicitly silenced, but only in short form.
2472 2474 if status.code:
2473 2475 if raise_exceptions:
2474 2476 raise
2475 2477 if not exit_ignore:
2476 2478 self.showtraceback(exception_only=True)
2477 2479 except:
2478 2480 if raise_exceptions:
2479 2481 raise
2480 2482 # tb offset is 2 because we wrap execfile
2481 2483 self.showtraceback(tb_offset=2)
2482 2484
2483 2485 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2484 2486 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2485 2487
2486 2488 Parameters
2487 2489 ----------
2488 2490 fname : str
2489 2491 The name of the file to execute. The filename must have a
2490 2492 .ipy or .ipynb extension.
2491 2493 shell_futures : bool (False)
2492 2494 If True, the code will share future statements with the interactive
2493 2495 shell. It will both be affected by previous __future__ imports, and
2494 2496 any __future__ imports in the code will affect the shell. If False,
2495 2497 __future__ imports are not shared in either direction.
2496 2498 raise_exceptions : bool (False)
2497 2499 If True raise exceptions everywhere. Meant for testing.
2498 2500 """
2499 2501 fname = os.path.abspath(os.path.expanduser(fname))
2500 2502
2501 2503 # Make sure we can open the file
2502 2504 try:
2503 2505 with open(fname):
2504 2506 pass
2505 2507 except:
2506 2508 warn('Could not open file <%s> for safe execution.' % fname)
2507 2509 return
2508 2510
2509 2511 # Find things also in current directory. This is needed to mimic the
2510 2512 # behavior of running a script from the system command line, where
2511 2513 # Python inserts the script's directory into sys.path
2512 2514 dname = os.path.dirname(fname)
2513 2515
2514 2516 def get_cells():
2515 2517 """generator for sequence of code blocks to run"""
2516 2518 if fname.endswith('.ipynb'):
2517 2519 from nbformat import read
2518 2520 nb = read(fname, as_version=4)
2519 2521 if not nb.cells:
2520 2522 return
2521 2523 for cell in nb.cells:
2522 2524 if cell.cell_type == 'code':
2523 2525 yield cell.source
2524 2526 else:
2525 2527 with open(fname) as f:
2526 2528 yield f.read()
2527 2529
2528 2530 with prepended_to_syspath(dname):
2529 2531 try:
2530 2532 for cell in get_cells():
2531 2533 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2532 2534 if raise_exceptions:
2533 2535 result.raise_error()
2534 2536 elif not result.success:
2535 2537 break
2536 2538 except:
2537 2539 if raise_exceptions:
2538 2540 raise
2539 2541 self.showtraceback()
2540 2542 warn('Unknown failure executing file: <%s>' % fname)
2541 2543
2542 2544 def safe_run_module(self, mod_name, where):
2543 2545 """A safe version of runpy.run_module().
2544 2546
2545 2547 This version will never throw an exception, but instead print
2546 2548 helpful error messages to the screen.
2547 2549
2548 2550 `SystemExit` exceptions with status code 0 or None are ignored.
2549 2551
2550 2552 Parameters
2551 2553 ----------
2552 2554 mod_name : string
2553 2555 The name of the module to be executed.
2554 2556 where : dict
2555 2557 The globals namespace.
2556 2558 """
2557 2559 try:
2558 2560 try:
2559 2561 where.update(
2560 2562 runpy.run_module(str(mod_name), run_name="__main__",
2561 2563 alter_sys=True)
2562 2564 )
2563 2565 except SystemExit as status:
2564 2566 if status.code:
2565 2567 raise
2566 2568 except:
2567 2569 self.showtraceback()
2568 2570 warn('Unknown failure executing module: <%s>' % mod_name)
2569 2571
2570 2572 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2571 2573 """Run a complete IPython cell.
2572 2574
2573 2575 Parameters
2574 2576 ----------
2575 2577 raw_cell : str
2576 2578 The code (including IPython code such as %magic functions) to run.
2577 2579 store_history : bool
2578 2580 If True, the raw and translated cell will be stored in IPython's
2579 2581 history. For user code calling back into IPython's machinery, this
2580 2582 should be set to False.
2581 2583 silent : bool
2582 2584 If True, avoid side-effects, such as implicit displayhooks and
2583 2585 and logging. silent=True forces store_history=False.
2584 2586 shell_futures : bool
2585 2587 If True, the code will share future statements with the interactive
2586 2588 shell. It will both be affected by previous __future__ imports, and
2587 2589 any __future__ imports in the code will affect the shell. If False,
2588 2590 __future__ imports are not shared in either direction.
2589 2591
2590 2592 Returns
2591 2593 -------
2592 2594 result : :class:`ExecutionResult`
2593 2595 """
2594 2596 result = ExecutionResult()
2595 2597
2596 2598 if (not raw_cell) or raw_cell.isspace():
2597 2599 self.last_execution_succeeded = True
2598 2600 return result
2599 2601
2600 2602 if silent:
2601 2603 store_history = False
2602 2604
2603 2605 if store_history:
2604 2606 result.execution_count = self.execution_count
2605 2607
2606 2608 def error_before_exec(value):
2607 2609 result.error_before_exec = value
2608 2610 self.last_execution_succeeded = False
2609 2611 return result
2610 2612
2611 2613 self.events.trigger('pre_execute')
2612 2614 if not silent:
2613 2615 self.events.trigger('pre_run_cell')
2614 2616
2615 2617 # If any of our input transformation (input_transformer_manager or
2616 2618 # prefilter_manager) raises an exception, we store it in this variable
2617 2619 # so that we can display the error after logging the input and storing
2618 2620 # it in the history.
2619 2621 preprocessing_exc_tuple = None
2620 2622 try:
2621 2623 # Static input transformations
2622 2624 cell = self.input_transformer_manager.transform_cell(raw_cell)
2623 2625 except SyntaxError:
2624 2626 preprocessing_exc_tuple = sys.exc_info()
2625 2627 cell = raw_cell # cell has to exist so it can be stored/logged
2626 2628 else:
2627 2629 if len(cell.splitlines()) == 1:
2628 2630 # Dynamic transformations - only applied for single line commands
2629 2631 with self.builtin_trap:
2630 2632 try:
2631 2633 # use prefilter_lines to handle trailing newlines
2632 2634 # restore trailing newline for ast.parse
2633 2635 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2634 2636 except Exception:
2635 2637 # don't allow prefilter errors to crash IPython
2636 2638 preprocessing_exc_tuple = sys.exc_info()
2637 2639
2638 2640 # Store raw and processed history
2639 2641 if store_history:
2640 2642 self.history_manager.store_inputs(self.execution_count,
2641 2643 cell, raw_cell)
2642 2644 if not silent:
2643 2645 self.logger.log(cell, raw_cell)
2644 2646
2645 2647 # Display the exception if input processing failed.
2646 2648 if preprocessing_exc_tuple is not None:
2647 2649 self.showtraceback(preprocessing_exc_tuple)
2648 2650 if store_history:
2649 2651 self.execution_count += 1
2650 2652 return error_before_exec(preprocessing_exc_tuple[2])
2651 2653
2652 2654 # Our own compiler remembers the __future__ environment. If we want to
2653 2655 # run code with a separate __future__ environment, use the default
2654 2656 # compiler
2655 2657 compiler = self.compile if shell_futures else CachingCompiler()
2656 2658
2657 2659 with self.builtin_trap:
2658 2660 cell_name = self.compile.cache(cell, self.execution_count)
2659 2661
2660 2662 with self.display_trap:
2661 2663 # Compile to bytecode
2662 2664 try:
2663 2665 code_ast = compiler.ast_parse(cell, filename=cell_name)
2664 2666 except self.custom_exceptions as e:
2665 2667 etype, value, tb = sys.exc_info()
2666 2668 self.CustomTB(etype, value, tb)
2667 2669 return error_before_exec(e)
2668 2670 except IndentationError as e:
2669 2671 self.showindentationerror()
2670 2672 if store_history:
2671 2673 self.execution_count += 1
2672 2674 return error_before_exec(e)
2673 2675 except (OverflowError, SyntaxError, ValueError, TypeError,
2674 2676 MemoryError) as e:
2675 2677 self.showsyntaxerror()
2676 2678 if store_history:
2677 2679 self.execution_count += 1
2678 2680 return error_before_exec(e)
2679 2681
2680 2682 # Apply AST transformations
2681 2683 try:
2682 2684 code_ast = self.transform_ast(code_ast)
2683 2685 except InputRejected as e:
2684 2686 self.showtraceback()
2685 2687 if store_history:
2686 2688 self.execution_count += 1
2687 2689 return error_before_exec(e)
2688 2690
2689 2691 # Give the displayhook a reference to our ExecutionResult so it
2690 2692 # can fill in the output value.
2691 2693 self.displayhook.exec_result = result
2692 2694
2693 2695 # Execute the user code
2694 2696 interactivity = "none" if silent else self.ast_node_interactivity
2695 2697 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2696 2698 interactivity=interactivity, compiler=compiler, result=result)
2697 2699
2698 2700 self.last_execution_succeeded = not has_raised
2699 2701
2700 2702 # Reset this so later displayed values do not modify the
2701 2703 # ExecutionResult
2702 2704 self.displayhook.exec_result = None
2703 2705
2704 2706 self.events.trigger('post_execute')
2705 2707 if not silent:
2706 2708 self.events.trigger('post_run_cell')
2707 2709
2708 2710 if store_history:
2709 2711 # Write output to the database. Does nothing unless
2710 2712 # history output logging is enabled.
2711 2713 self.history_manager.store_output(self.execution_count)
2712 2714 # Each cell is a *single* input, regardless of how many lines it has
2713 2715 self.execution_count += 1
2714 2716
2715 2717 return result
2716 2718
2717 2719 def transform_ast(self, node):
2718 2720 """Apply the AST transformations from self.ast_transformers
2719 2721
2720 2722 Parameters
2721 2723 ----------
2722 2724 node : ast.Node
2723 2725 The root node to be transformed. Typically called with the ast.Module
2724 2726 produced by parsing user input.
2725 2727
2726 2728 Returns
2727 2729 -------
2728 2730 An ast.Node corresponding to the node it was called with. Note that it
2729 2731 may also modify the passed object, so don't rely on references to the
2730 2732 original AST.
2731 2733 """
2732 2734 for transformer in self.ast_transformers:
2733 2735 try:
2734 2736 node = transformer.visit(node)
2735 2737 except InputRejected:
2736 2738 # User-supplied AST transformers can reject an input by raising
2737 2739 # an InputRejected. Short-circuit in this case so that we
2738 2740 # don't unregister the transform.
2739 2741 raise
2740 2742 except Exception:
2741 2743 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2742 2744 self.ast_transformers.remove(transformer)
2743 2745
2744 2746 if self.ast_transformers:
2745 2747 ast.fix_missing_locations(node)
2746 2748 return node
2747 2749
2748 2750
2749 2751 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2750 2752 compiler=compile, result=None):
2751 2753 """Run a sequence of AST nodes. The execution mode depends on the
2752 2754 interactivity parameter.
2753 2755
2754 2756 Parameters
2755 2757 ----------
2756 2758 nodelist : list
2757 2759 A sequence of AST nodes to run.
2758 2760 cell_name : str
2759 2761 Will be passed to the compiler as the filename of the cell. Typically
2760 2762 the value returned by ip.compile.cache(cell).
2761 2763 interactivity : str
2762 2764 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2763 2765 run interactively (displaying output from expressions). 'last_expr'
2764 2766 will run the last node interactively only if it is an expression (i.e.
2765 2767 expressions in loops or other blocks are not displayed. Other values
2766 2768 for this parameter will raise a ValueError.
2767 2769 compiler : callable
2768 2770 A function with the same interface as the built-in compile(), to turn
2769 2771 the AST nodes into code objects. Default is the built-in compile().
2770 2772 result : ExecutionResult, optional
2771 2773 An object to store exceptions that occur during execution.
2772 2774
2773 2775 Returns
2774 2776 -------
2775 2777 True if an exception occurred while running code, False if it finished
2776 2778 running.
2777 2779 """
2778 2780 if not nodelist:
2779 2781 return
2780 2782
2781 2783 if interactivity == 'last_expr':
2782 2784 if isinstance(nodelist[-1], ast.Expr):
2783 2785 interactivity = "last"
2784 2786 else:
2785 2787 interactivity = "none"
2786 2788
2787 2789 if interactivity == 'none':
2788 2790 to_run_exec, to_run_interactive = nodelist, []
2789 2791 elif interactivity == 'last':
2790 2792 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2791 2793 elif interactivity == 'all':
2792 2794 to_run_exec, to_run_interactive = [], nodelist
2793 2795 else:
2794 2796 raise ValueError("Interactivity was %r" % interactivity)
2795 2797
2796 2798 try:
2797 2799 for i, node in enumerate(to_run_exec):
2798 2800 mod = ast.Module([node])
2799 2801 code = compiler(mod, cell_name, "exec")
2800 2802 if self.run_code(code, result):
2801 2803 return True
2802 2804
2803 2805 for i, node in enumerate(to_run_interactive):
2804 2806 mod = ast.Interactive([node])
2805 2807 code = compiler(mod, cell_name, "single")
2806 2808 if self.run_code(code, result):
2807 2809 return True
2808 2810
2809 2811 # Flush softspace
2810 2812 if softspace(sys.stdout, 0):
2811 2813 print()
2812 2814
2813 2815 except:
2814 2816 # It's possible to have exceptions raised here, typically by
2815 2817 # compilation of odd code (such as a naked 'return' outside a
2816 2818 # function) that did parse but isn't valid. Typically the exception
2817 2819 # is a SyntaxError, but it's safest just to catch anything and show
2818 2820 # the user a traceback.
2819 2821
2820 2822 # We do only one try/except outside the loop to minimize the impact
2821 2823 # on runtime, and also because if any node in the node list is
2822 2824 # broken, we should stop execution completely.
2823 2825 if result:
2824 2826 result.error_before_exec = sys.exc_info()[1]
2825 2827 self.showtraceback()
2826 2828 return True
2827 2829
2828 2830 return False
2829 2831
2830 2832 def run_code(self, code_obj, result=None):
2831 2833 """Execute a code object.
2832 2834
2833 2835 When an exception occurs, self.showtraceback() is called to display a
2834 2836 traceback.
2835 2837
2836 2838 Parameters
2837 2839 ----------
2838 2840 code_obj : code object
2839 2841 A compiled code object, to be executed
2840 2842 result : ExecutionResult, optional
2841 2843 An object to store exceptions that occur during execution.
2842 2844
2843 2845 Returns
2844 2846 -------
2845 2847 False : successful execution.
2846 2848 True : an error occurred.
2847 2849 """
2848 2850 # Set our own excepthook in case the user code tries to call it
2849 2851 # directly, so that the IPython crash handler doesn't get triggered
2850 2852 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2851 2853
2852 2854 # we save the original sys.excepthook in the instance, in case config
2853 2855 # code (such as magics) needs access to it.
2854 2856 self.sys_excepthook = old_excepthook
2855 2857 outflag = True # happens in more places, so it's easier as default
2856 2858 try:
2857 2859 try:
2858 2860 self.hooks.pre_run_code_hook()
2859 2861 #rprint('Running code', repr(code_obj)) # dbg
2860 2862 exec(code_obj, self.user_global_ns, self.user_ns)
2861 2863 finally:
2862 2864 # Reset our crash handler in place
2863 2865 sys.excepthook = old_excepthook
2864 2866 except SystemExit as e:
2865 2867 if result is not None:
2866 2868 result.error_in_exec = e
2867 2869 self.showtraceback(exception_only=True)
2868 2870 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2869 2871 except self.custom_exceptions:
2870 2872 etype, value, tb = sys.exc_info()
2871 2873 if result is not None:
2872 2874 result.error_in_exec = value
2873 2875 self.CustomTB(etype, value, tb)
2874 2876 except:
2875 2877 if result is not None:
2876 2878 result.error_in_exec = sys.exc_info()[1]
2877 2879 self.showtraceback(running_compiled_code=True)
2878 2880 else:
2879 2881 outflag = False
2880 2882 return outflag
2881 2883
2882 2884 # For backwards compatibility
2883 2885 runcode = run_code
2884 2886
2885 2887 #-------------------------------------------------------------------------
2886 2888 # Things related to GUI support and pylab
2887 2889 #-------------------------------------------------------------------------
2888 2890
2889 2891 active_eventloop = None
2890 2892
2891 2893 def enable_gui(self, gui=None):
2892 2894 raise NotImplementedError('Implement enable_gui in a subclass')
2893 2895
2894 2896 def enable_matplotlib(self, gui=None):
2895 2897 """Enable interactive matplotlib and inline figure support.
2896 2898
2897 2899 This takes the following steps:
2898 2900
2899 2901 1. select the appropriate eventloop and matplotlib backend
2900 2902 2. set up matplotlib for interactive use with that backend
2901 2903 3. configure formatters for inline figure display
2902 2904 4. enable the selected gui eventloop
2903 2905
2904 2906 Parameters
2905 2907 ----------
2906 2908 gui : optional, string
2907 2909 If given, dictates the choice of matplotlib GUI backend to use
2908 2910 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2909 2911 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2910 2912 matplotlib (as dictated by the matplotlib build-time options plus the
2911 2913 user's matplotlibrc configuration file). Note that not all backends
2912 2914 make sense in all contexts, for example a terminal ipython can't
2913 2915 display figures inline.
2914 2916 """
2915 2917 from IPython.core import pylabtools as pt
2916 2918 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2917 2919
2918 2920 if gui != 'inline':
2919 2921 # If we have our first gui selection, store it
2920 2922 if self.pylab_gui_select is None:
2921 2923 self.pylab_gui_select = gui
2922 2924 # Otherwise if they are different
2923 2925 elif gui != self.pylab_gui_select:
2924 2926 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2925 2927 ' Using %s instead.' % (gui, self.pylab_gui_select))
2926 2928 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2927 2929
2928 2930 pt.activate_matplotlib(backend)
2929 2931 pt.configure_inline_support(self, backend)
2930 2932
2931 2933 # Now we must activate the gui pylab wants to use, and fix %run to take
2932 2934 # plot updates into account
2933 2935 self.enable_gui(gui)
2934 2936 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2935 2937 pt.mpl_runner(self.safe_execfile)
2936 2938
2937 2939 return gui, backend
2938 2940
2939 2941 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2940 2942 """Activate pylab support at runtime.
2941 2943
2942 2944 This turns on support for matplotlib, preloads into the interactive
2943 2945 namespace all of numpy and pylab, and configures IPython to correctly
2944 2946 interact with the GUI event loop. The GUI backend to be used can be
2945 2947 optionally selected with the optional ``gui`` argument.
2946 2948
2947 2949 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2948 2950
2949 2951 Parameters
2950 2952 ----------
2951 2953 gui : optional, string
2952 2954 If given, dictates the choice of matplotlib GUI backend to use
2953 2955 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2954 2956 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2955 2957 matplotlib (as dictated by the matplotlib build-time options plus the
2956 2958 user's matplotlibrc configuration file). Note that not all backends
2957 2959 make sense in all contexts, for example a terminal ipython can't
2958 2960 display figures inline.
2959 2961 import_all : optional, bool, default: True
2960 2962 Whether to do `from numpy import *` and `from pylab import *`
2961 2963 in addition to module imports.
2962 2964 welcome_message : deprecated
2963 2965 This argument is ignored, no welcome message will be displayed.
2964 2966 """
2965 2967 from IPython.core.pylabtools import import_pylab
2966 2968
2967 2969 gui, backend = self.enable_matplotlib(gui)
2968 2970
2969 2971 # We want to prevent the loading of pylab to pollute the user's
2970 2972 # namespace as shown by the %who* magics, so we execute the activation
2971 2973 # code in an empty namespace, and we update *both* user_ns and
2972 2974 # user_ns_hidden with this information.
2973 2975 ns = {}
2974 2976 import_pylab(ns, import_all)
2975 2977 # warn about clobbered names
2976 2978 ignored = {"__builtins__"}
2977 2979 both = set(ns).intersection(self.user_ns).difference(ignored)
2978 2980 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2979 2981 self.user_ns.update(ns)
2980 2982 self.user_ns_hidden.update(ns)
2981 2983 return gui, backend, clobbered
2982 2984
2983 2985 #-------------------------------------------------------------------------
2984 2986 # Utilities
2985 2987 #-------------------------------------------------------------------------
2986 2988
2987 2989 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2988 2990 """Expand python variables in a string.
2989 2991
2990 2992 The depth argument indicates how many frames above the caller should
2991 2993 be walked to look for the local namespace where to expand variables.
2992 2994
2993 2995 The global namespace for expansion is always the user's interactive
2994 2996 namespace.
2995 2997 """
2996 2998 ns = self.user_ns.copy()
2997 2999 try:
2998 3000 frame = sys._getframe(depth+1)
2999 3001 except ValueError:
3000 3002 # This is thrown if there aren't that many frames on the stack,
3001 3003 # e.g. if a script called run_line_magic() directly.
3002 3004 pass
3003 3005 else:
3004 3006 ns.update(frame.f_locals)
3005 3007
3006 3008 try:
3007 3009 # We have to use .vformat() here, because 'self' is a valid and common
3008 3010 # name, and expanding **ns for .format() would make it collide with
3009 3011 # the 'self' argument of the method.
3010 3012 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3011 3013 except Exception:
3012 3014 # if formatter couldn't format, just let it go untransformed
3013 3015 pass
3014 3016 return cmd
3015 3017
3016 3018 def mktempfile(self, data=None, prefix='ipython_edit_'):
3017 3019 """Make a new tempfile and return its filename.
3018 3020
3019 3021 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3020 3022 but it registers the created filename internally so ipython cleans it up
3021 3023 at exit time.
3022 3024
3023 3025 Optional inputs:
3024 3026
3025 3027 - data(None): if data is given, it gets written out to the temp file
3026 3028 immediately, and the file is closed again."""
3027 3029
3028 3030 dirname = tempfile.mkdtemp(prefix=prefix)
3029 3031 self.tempdirs.append(dirname)
3030 3032
3031 3033 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3032 3034 os.close(handle) # On Windows, there can only be one open handle on a file
3033 3035 self.tempfiles.append(filename)
3034 3036
3035 3037 if data:
3036 3038 tmp_file = open(filename,'w')
3037 3039 tmp_file.write(data)
3038 3040 tmp_file.close()
3039 3041 return filename
3040 3042
3041 3043 @undoc
3042 3044 def write(self,data):
3043 3045 """DEPRECATED: Write a string to the default output"""
3044 3046 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3045 3047 DeprecationWarning, stacklevel=2)
3046 3048 sys.stdout.write(data)
3047 3049
3048 3050 @undoc
3049 3051 def write_err(self,data):
3050 3052 """DEPRECATED: Write a string to the default error output"""
3051 3053 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3052 3054 DeprecationWarning, stacklevel=2)
3053 3055 sys.stderr.write(data)
3054 3056
3055 3057 def ask_yes_no(self, prompt, default=None, interrupt=None):
3056 3058 if self.quiet:
3057 3059 return True
3058 3060 return ask_yes_no(prompt,default,interrupt)
3059 3061
3060 3062 def show_usage(self):
3061 3063 """Show a usage message"""
3062 3064 page.page(IPython.core.usage.interactive_usage)
3063 3065
3064 3066 def extract_input_lines(self, range_str, raw=False):
3065 3067 """Return as a string a set of input history slices.
3066 3068
3067 3069 Parameters
3068 3070 ----------
3069 3071 range_str : string
3070 3072 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3071 3073 since this function is for use by magic functions which get their
3072 3074 arguments as strings. The number before the / is the session
3073 3075 number: ~n goes n back from the current session.
3074 3076
3075 3077 raw : bool, optional
3076 3078 By default, the processed input is used. If this is true, the raw
3077 3079 input history is used instead.
3078 3080
3079 3081 Notes
3080 3082 -----
3081 3083
3082 3084 Slices can be described with two notations:
3083 3085
3084 3086 * ``N:M`` -> standard python form, means including items N...(M-1).
3085 3087 * ``N-M`` -> include items N..M (closed endpoint).
3086 3088 """
3087 3089 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3088 3090 return "\n".join(x for _, _, x in lines)
3089 3091
3090 3092 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3091 3093 """Get a code string from history, file, url, or a string or macro.
3092 3094
3093 3095 This is mainly used by magic functions.
3094 3096
3095 3097 Parameters
3096 3098 ----------
3097 3099
3098 3100 target : str
3099 3101
3100 3102 A string specifying code to retrieve. This will be tried respectively
3101 3103 as: ranges of input history (see %history for syntax), url,
3102 3104 corresponding .py file, filename, or an expression evaluating to a
3103 3105 string or Macro in the user namespace.
3104 3106
3105 3107 raw : bool
3106 3108 If true (default), retrieve raw history. Has no effect on the other
3107 3109 retrieval mechanisms.
3108 3110
3109 3111 py_only : bool (default False)
3110 3112 Only try to fetch python code, do not try alternative methods to decode file
3111 3113 if unicode fails.
3112 3114
3113 3115 Returns
3114 3116 -------
3115 3117 A string of code.
3116 3118
3117 3119 ValueError is raised if nothing is found, and TypeError if it evaluates
3118 3120 to an object of another type. In each case, .args[0] is a printable
3119 3121 message.
3120 3122 """
3121 3123 code = self.extract_input_lines(target, raw=raw) # Grab history
3122 3124 if code:
3123 3125 return code
3124 3126 try:
3125 3127 if target.startswith(('http://', 'https://')):
3126 3128 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3127 3129 except UnicodeDecodeError:
3128 3130 if not py_only :
3129 3131 # Deferred import
3130 3132 from urllib.request import urlopen
3131 3133 response = urlopen(target)
3132 3134 return response.read().decode('latin1')
3133 3135 raise ValueError(("'%s' seem to be unreadable.") % target)
3134 3136
3135 3137 potential_target = [target]
3136 3138 try :
3137 3139 potential_target.insert(0,get_py_filename(target))
3138 3140 except IOError:
3139 3141 pass
3140 3142
3141 3143 for tgt in potential_target :
3142 3144 if os.path.isfile(tgt): # Read file
3143 3145 try :
3144 3146 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3145 3147 except UnicodeDecodeError :
3146 3148 if not py_only :
3147 3149 with io_open(tgt,'r', encoding='latin1') as f :
3148 3150 return f.read()
3149 3151 raise ValueError(("'%s' seem to be unreadable.") % target)
3150 3152 elif os.path.isdir(os.path.expanduser(tgt)):
3151 3153 raise ValueError("'%s' is a directory, not a regular file." % target)
3152 3154
3153 3155 if search_ns:
3154 3156 # Inspect namespace to load object source
3155 3157 object_info = self.object_inspect(target, detail_level=1)
3156 3158 if object_info['found'] and object_info['source']:
3157 3159 return object_info['source']
3158 3160
3159 3161 try: # User namespace
3160 3162 codeobj = eval(target, self.user_ns)
3161 3163 except Exception:
3162 3164 raise ValueError(("'%s' was not found in history, as a file, url, "
3163 3165 "nor in the user namespace.") % target)
3164 3166
3165 3167 if isinstance(codeobj, str):
3166 3168 return codeobj
3167 3169 elif isinstance(codeobj, Macro):
3168 3170 return codeobj.value
3169 3171
3170 3172 raise TypeError("%s is neither a string nor a macro." % target,
3171 3173 codeobj)
3172 3174
3173 3175 #-------------------------------------------------------------------------
3174 3176 # Things related to IPython exiting
3175 3177 #-------------------------------------------------------------------------
3176 3178 def atexit_operations(self):
3177 3179 """This will be executed at the time of exit.
3178 3180
3179 3181 Cleanup operations and saving of persistent data that is done
3180 3182 unconditionally by IPython should be performed here.
3181 3183
3182 3184 For things that may depend on startup flags or platform specifics (such
3183 3185 as having readline or not), register a separate atexit function in the
3184 3186 code that has the appropriate information, rather than trying to
3185 3187 clutter
3186 3188 """
3187 3189 # Close the history session (this stores the end time and line count)
3188 3190 # this must be *before* the tempfile cleanup, in case of temporary
3189 3191 # history db
3190 3192 self.history_manager.end_session()
3191 3193
3192 3194 # Cleanup all tempfiles and folders left around
3193 3195 for tfile in self.tempfiles:
3194 3196 try:
3195 3197 os.unlink(tfile)
3196 3198 except OSError:
3197 3199 pass
3198 3200
3199 3201 for tdir in self.tempdirs:
3200 3202 try:
3201 3203 os.rmdir(tdir)
3202 3204 except OSError:
3203 3205 pass
3204 3206
3205 3207 # Clear all user namespaces to release all references cleanly.
3206 3208 self.reset(new_session=False)
3207 3209
3208 3210 # Run user hooks
3209 3211 self.hooks.shutdown_hook()
3210 3212
3211 3213 def cleanup(self):
3212 3214 self.restore_sys_module_state()
3213 3215
3214 3216
3215 3217 # Overridden in terminal subclass to change prompts
3216 3218 def switch_doctest_mode(self, mode):
3217 3219 pass
3218 3220
3219 3221
3220 3222 class InteractiveShellABC(metaclass=abc.ABCMeta):
3221 3223 """An abstract base class for InteractiveShell."""
3222 3224
3223 3225 InteractiveShellABC.register(InteractiveShell)
@@ -1,334 +1,354 b''
1 1 # Copyright (c) IPython Development Team.
2 2 # Distributed under the terms of the Modified BSD License.
3 3
4 4 import json
5 5 import os
6 6 import warnings
7 7
8 8 from unittest import mock
9 9
10 10 import nose.tools as nt
11 11
12 12 from IPython.core import display
13 13 from IPython.core.getipython import get_ipython
14 14 from IPython.utils.tempdir import NamedFileInTemporaryDirectory
15 15 from IPython import paths as ipath
16 from IPython.testing.tools import AssertPrints, AssertNotPrints
16 17
17 18 import IPython.testing.decorators as dec
18 19
19 20 def test_image_size():
20 21 """Simple test for display.Image(args, width=x,height=y)"""
21 22 thisurl = 'http://www.google.fr/images/srpr/logo3w.png'
22 23 img = display.Image(url=thisurl, width=200, height=200)
23 24 nt.assert_equal(u'<img src="%s" width="200" height="200"/>' % (thisurl), img._repr_html_())
24 25 img = display.Image(url=thisurl, width=200)
25 26 nt.assert_equal(u'<img src="%s" width="200"/>' % (thisurl), img._repr_html_())
26 27 img = display.Image(url=thisurl)
27 28 nt.assert_equal(u'<img src="%s"/>' % (thisurl), img._repr_html_())
28 29 img = display.Image(url=thisurl, unconfined=True)
29 30 nt.assert_equal(u'<img src="%s" class="unconfined"/>' % (thisurl), img._repr_html_())
30 31
31 32
32 33 def test_geojson():
33 34
34 35 gj = display.GeoJSON(data={
35 36 "type": "Feature",
36 37 "geometry": {
37 38 "type": "Point",
38 39 "coordinates": [-81.327, 296.038]
39 40 },
40 41 "properties": {
41 42 "name": "Inca City"
42 43 }
43 44 },
44 45 url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png",
45 46 layer_options={
46 47 "basemap_id": "celestia_mars-shaded-16k_global",
47 48 "attribution": "Celestia/praesepe",
48 49 "minZoom": 0,
49 50 "maxZoom": 18,
50 51 })
51 52 nt.assert_equal(u'<IPython.core.display.GeoJSON object>', str(gj))
52 53
53 54 def test_retina_png():
54 55 here = os.path.dirname(__file__)
55 56 img = display.Image(os.path.join(here, "2x2.png"), retina=True)
56 57 nt.assert_equal(img.height, 1)
57 58 nt.assert_equal(img.width, 1)
58 59 data, md = img._repr_png_()
59 60 nt.assert_equal(md['width'], 1)
60 61 nt.assert_equal(md['height'], 1)
61 62
62 63 def test_retina_jpeg():
63 64 here = os.path.dirname(__file__)
64 65 img = display.Image(os.path.join(here, "2x2.jpg"), retina=True)
65 66 nt.assert_equal(img.height, 1)
66 67 nt.assert_equal(img.width, 1)
67 68 data, md = img._repr_jpeg_()
68 69 nt.assert_equal(md['width'], 1)
69 70 nt.assert_equal(md['height'], 1)
70 71
71 72 def test_base64image():
72 73 display.Image("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB94BCRQnOqNu0b4AAAAKSURBVAjXY2AAAAACAAHiIbwzAAAAAElFTkSuQmCC")
73 74
74 75 def test_image_filename_defaults():
75 76 '''test format constraint, and validity of jpeg and png'''
76 77 tpath = ipath.get_ipython_package_dir()
77 78 nt.assert_raises(ValueError, display.Image, filename=os.path.join(tpath, 'testing/tests/badformat.gif'),
78 79 embed=True)
79 80 nt.assert_raises(ValueError, display.Image)
80 81 nt.assert_raises(ValueError, display.Image, data='this is not an image', format='badformat', embed=True)
81 82 # check boths paths to allow packages to test at build and install time
82 83 imgfile = os.path.join(tpath, 'core/tests/2x2.png')
83 84 img = display.Image(filename=imgfile)
84 85 nt.assert_equal('png', img.format)
85 86 nt.assert_is_not_none(img._repr_png_())
86 87 img = display.Image(filename=os.path.join(tpath, 'testing/tests/logo.jpg'), embed=False)
87 88 nt.assert_equal('jpeg', img.format)
88 89 nt.assert_is_none(img._repr_jpeg_())
89 90
90 91 def _get_inline_config():
91 92 from ipykernel.pylab.config import InlineBackend
92 93 return InlineBackend.instance()
93 94
94 95 @dec.skip_without('matplotlib')
95 96 def test_set_matplotlib_close():
96 97 cfg = _get_inline_config()
97 98 cfg.close_figures = False
98 99 display.set_matplotlib_close()
99 100 assert cfg.close_figures
100 101 display.set_matplotlib_close(False)
101 102 assert not cfg.close_figures
102 103
103 104 _fmt_mime_map = {
104 105 'png': 'image/png',
105 106 'jpeg': 'image/jpeg',
106 107 'pdf': 'application/pdf',
107 108 'retina': 'image/png',
108 109 'svg': 'image/svg+xml',
109 110 }
110 111
111 112 @dec.skip_without('matplotlib')
112 113 def test_set_matplotlib_formats():
113 114 from matplotlib.figure import Figure
114 115 formatters = get_ipython().display_formatter.formatters
115 116 for formats in [
116 117 ('png',),
117 118 ('pdf', 'svg'),
118 119 ('jpeg', 'retina', 'png'),
119 120 (),
120 121 ]:
121 122 active_mimes = {_fmt_mime_map[fmt] for fmt in formats}
122 123 display.set_matplotlib_formats(*formats)
123 124 for mime, f in formatters.items():
124 125 if mime in active_mimes:
125 126 nt.assert_in(Figure, f)
126 127 else:
127 128 nt.assert_not_in(Figure, f)
128 129
129 130 @dec.skip_without('matplotlib')
130 131 def test_set_matplotlib_formats_kwargs():
131 132 from matplotlib.figure import Figure
132 133 ip = get_ipython()
133 134 cfg = _get_inline_config()
134 135 cfg.print_figure_kwargs.update(dict(foo='bar'))
135 136 kwargs = dict(quality=10)
136 137 display.set_matplotlib_formats('png', **kwargs)
137 138 formatter = ip.display_formatter.formatters['image/png']
138 139 f = formatter.lookup_by_type(Figure)
139 140 cell = f.__closure__[0].cell_contents
140 141 expected = kwargs
141 142 expected.update(cfg.print_figure_kwargs)
142 143 nt.assert_equal(cell, expected)
143 144
145 def test_display_available():
146 """
147 Test that display is available without import
148
149 We don't really care if it's in builtin or anything else, but it should
150 always be available.
151 """
152 ip = get_ipython()
153 with AssertNotPrints('NameError'):
154 ip.run_cell('display')
155 try:
156 ip.run_cell('del display')
157 except NameError:
158 pass # it's ok, it might be in builtins
159 # even if deleted it should be back
160 with AssertNotPrints('NameError'):
161 ip.run_cell('display')
162
163
144 164 def test_displayobject_repr():
145 165 h = display.HTML('<br />')
146 166 nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')
147 167 h._show_mem_addr = True
148 168 nt.assert_equal(repr(h), object.__repr__(h))
149 169 h._show_mem_addr = False
150 170 nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')
151 171
152 172 j = display.Javascript('')
153 173 nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>')
154 174 j._show_mem_addr = True
155 175 nt.assert_equal(repr(j), object.__repr__(j))
156 176 j._show_mem_addr = False
157 177 nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>')
158 178
159 179 def test_json():
160 180 d = {'a': 5}
161 181 lis = [d]
162 182 md = {'expanded': False}
163 183 md2 = {'expanded': True}
164 184 j = display.JSON(d)
165 185 j2 = display.JSON(d, expanded=True)
166 186 nt.assert_equal(j._repr_json_(), (d, md))
167 187 nt.assert_equal(j2._repr_json_(), (d, md2))
168 188
169 189 with warnings.catch_warnings(record=True) as w:
170 190 warnings.simplefilter("always")
171 191 j = display.JSON(json.dumps(d))
172 192 nt.assert_equal(len(w), 1)
173 193 nt.assert_equal(j._repr_json_(), (d, md))
174 194 nt.assert_equal(j2._repr_json_(), (d, md2))
175 195
176 196 j = display.JSON(lis)
177 197 j2 = display.JSON(lis, expanded=True)
178 198 nt.assert_equal(j._repr_json_(), (lis, md))
179 199 nt.assert_equal(j2._repr_json_(), (lis, md2))
180 200
181 201 with warnings.catch_warnings(record=True) as w:
182 202 warnings.simplefilter("always")
183 203 j = display.JSON(json.dumps(lis))
184 204 nt.assert_equal(len(w), 1)
185 205 nt.assert_equal(j._repr_json_(), (lis, md))
186 206 nt.assert_equal(j2._repr_json_(), (lis, md2))
187 207
188 208 def test_video_embedding():
189 209 """use a tempfile, with dummy-data, to ensure that video embedding doesn't crash"""
190 210 v = display.Video("http://ignored")
191 211 assert not v.embed
192 212 html = v._repr_html_()
193 213 nt.assert_not_in('src="data:', html)
194 214 nt.assert_in('src="http://ignored"', html)
195 215
196 216 with nt.assert_raises(ValueError):
197 217 v = display.Video(b'abc')
198 218
199 219 with NamedFileInTemporaryDirectory('test.mp4') as f:
200 220 f.write(b'abc')
201 221 f.close()
202 222
203 223 v = display.Video(f.name)
204 224 assert not v.embed
205 225 html = v._repr_html_()
206 226 nt.assert_not_in('src="data:', html)
207 227
208 228 v = display.Video(f.name, embed=True)
209 229 html = v._repr_html_()
210 230 nt.assert_in('src="data:video/mp4;base64,YWJj"',html)
211 231
212 232 v = display.Video(f.name, embed=True, mimetype='video/other')
213 233 html = v._repr_html_()
214 234 nt.assert_in('src="data:video/other;base64,YWJj"',html)
215 235
216 236 v = display.Video(b'abc', embed=True, mimetype='video/mp4')
217 237 html = v._repr_html_()
218 238 nt.assert_in('src="data:video/mp4;base64,YWJj"',html)
219 239
220 240 v = display.Video(u'YWJj', embed=True, mimetype='video/xyz')
221 241 html = v._repr_html_()
222 242 nt.assert_in('src="data:video/xyz;base64,YWJj"',html)
223 243
224 244
225 245 def test_display_id():
226 246 ip = get_ipython()
227 247 with mock.patch.object(ip.display_pub, 'publish') as pub:
228 248 handle = display.display('x')
229 249 nt.assert_is(handle, None)
230 250 handle = display.display('y', display_id='secret')
231 251 nt.assert_is_instance(handle, display.DisplayHandle)
232 252 handle2 = display.display('z', display_id=True)
233 253 nt.assert_is_instance(handle2, display.DisplayHandle)
234 254 nt.assert_not_equal(handle.display_id, handle2.display_id)
235 255
236 256 nt.assert_equal(pub.call_count, 3)
237 257 args, kwargs = pub.call_args_list[0]
238 258 nt.assert_equal(args, ())
239 259 nt.assert_equal(kwargs, {
240 260 'data': {
241 261 'text/plain': repr('x')
242 262 },
243 263 'metadata': {},
244 264 })
245 265 args, kwargs = pub.call_args_list[1]
246 266 nt.assert_equal(args, ())
247 267 nt.assert_equal(kwargs, {
248 268 'data': {
249 269 'text/plain': repr('y')
250 270 },
251 271 'metadata': {},
252 272 'transient': {
253 273 'display_id': handle.display_id,
254 274 },
255 275 })
256 276 args, kwargs = pub.call_args_list[2]
257 277 nt.assert_equal(args, ())
258 278 nt.assert_equal(kwargs, {
259 279 'data': {
260 280 'text/plain': repr('z')
261 281 },
262 282 'metadata': {},
263 283 'transient': {
264 284 'display_id': handle2.display_id,
265 285 },
266 286 })
267 287
268 288
269 289 def test_update_display():
270 290 ip = get_ipython()
271 291 with mock.patch.object(ip.display_pub, 'publish') as pub:
272 292 with nt.assert_raises(TypeError):
273 293 display.update_display('x')
274 294 display.update_display('x', display_id='1')
275 295 display.update_display('y', display_id='2')
276 296 args, kwargs = pub.call_args_list[0]
277 297 nt.assert_equal(args, ())
278 298 nt.assert_equal(kwargs, {
279 299 'data': {
280 300 'text/plain': repr('x')
281 301 },
282 302 'metadata': {},
283 303 'transient': {
284 304 'display_id': '1',
285 305 },
286 306 'update': True,
287 307 })
288 308 args, kwargs = pub.call_args_list[1]
289 309 nt.assert_equal(args, ())
290 310 nt.assert_equal(kwargs, {
291 311 'data': {
292 312 'text/plain': repr('y')
293 313 },
294 314 'metadata': {},
295 315 'transient': {
296 316 'display_id': '2',
297 317 },
298 318 'update': True,
299 319 })
300 320
301 321
302 322 def test_display_handle():
303 323 ip = get_ipython()
304 324 handle = display.DisplayHandle()
305 325 nt.assert_is_instance(handle.display_id, str)
306 326 handle = display.DisplayHandle('my-id')
307 327 nt.assert_equal(handle.display_id, 'my-id')
308 328 with mock.patch.object(ip.display_pub, 'publish') as pub:
309 329 handle.display('x')
310 330 handle.update('y')
311 331
312 332 args, kwargs = pub.call_args_list[0]
313 333 nt.assert_equal(args, ())
314 334 nt.assert_equal(kwargs, {
315 335 'data': {
316 336 'text/plain': repr('x')
317 337 },
318 338 'metadata': {},
319 339 'transient': {
320 340 'display_id': handle.display_id,
321 341 }
322 342 })
323 343 args, kwargs = pub.call_args_list[1]
324 344 nt.assert_equal(args, ())
325 345 nt.assert_equal(kwargs, {
326 346 'data': {
327 347 'text/plain': repr('y')
328 348 },
329 349 'metadata': {},
330 350 'transient': {
331 351 'display_id': handle.display_id,
332 352 },
333 353 'update': True,
334 354 })
@@ -1,42 +1,67 b''
1 1 .. _plotting:
2 2
3 Rich Outputs
4 ------------
5
6 One of the main feature of IPython when used as a kernel is its ability to
7 show rich output. This means that object that can be representing as image,
8 sounds, animation, (etc...) can be shown this way if the frontend support it.
9
10 In order for this to be possible, you need to use the ``display()`` function,
11 that should be available by default on IPython 5.4+ and 6.1+, or that you can
12 import with ``from IPython.display import display``. Then use ``display(<your
13 object>)`` instead of ``print()``, and if possible your object will be displayed
14 with a richer representation. In the terminal of course, there wont be much
15 difference as object are most of the time represented by text, but in notebook
16 and similar interface you will get richer outputs.
17
18
3 19 Plotting
4 20 --------
21
22 .. note::
23
24 Starting with IPython 5.0 and matplotlib 2.0 you can avoid the use of
25 IPython's specific magic and use
26 ``matplotlib.pyplot.ion()``/``matplotlib.pyplot.ioff()`` which have the
27 advantages of working outside of IPython as well.
28
29
5 30 One major feature of the IPython kernel is the ability to display plots that
6 31 are the output of running code cells. The IPython kernel is designed to work
7 32 seamlessly with the matplotlib_ plotting library to provide this functionality.
8 33
9 34 To set this up, before any plotting or import of matplotlib is performed you
10 35 must execute the ``%matplotlib`` :ref:`magic command <magics_explained>`. This
11 36 performs the necessary behind-the-scenes setup for IPython to work correctly
12 37 hand in hand with ``matplotlib``; it does *not*, however, actually execute any
13 38 Python ``import`` commands, that is, no names are added to the namespace.
14 39
15 40 If the ``%matplotlib`` magic is called without an argument, the
16 41 output of a plotting command is displayed using the default ``matplotlib``
17 42 backend in a separate window. Alternatively, the backend can be explicitly
18 43 requested using, for example::
19 44
20 45 %matplotlib gtk
21 46
22 47 A particularly interesting backend, provided by IPython, is the ``inline``
23 48 backend. This is available only for the Jupyter Notebook and the
24 49 Jupyter QtConsole. It can be invoked as follows::
25 50
26 51 %matplotlib inline
27 52
28 53 With this backend, the output of plotting commands is displayed *inline* within
29 54 frontends like the Jupyter notebook, directly below the code cell that produced
30 55 it. The resulting plots will then also be stored in the notebook document.
31 56
32 57 .. seealso::
33 58
34 59 `Plotting with Matplotlib`_ example notebook
35 60
36 61
37 62 The matplotlib_ library also ships with ``%matplotlib notebook`` command that
38 63 allows interactive figures if your environment allows it.
39 64
40 65 See the matplotlib_ documentation for more information.
41 66
42 67 .. include:: ../links.txt
@@ -1,346 +1,359 b''
1 1 ============
2 2 5.x Series
3 3 ============
4 4
5 5 .. _whatsnew540:
6 6
7 7 IPython 5.4
8 8 ===========
9 9
10 10 IPython 5.4-LTS is the first release of IPython after the release of the 6.x
11 11 series which is Python 3 only. It backports most of the new exposed API
12 12 additions made in IPython 6.0 and 6.1 and avoid having to write conditional
13 13 logics depending of the version of IPython.
14 14
15 15 Please upgrade to pip 9 or greater before upgrading IPython.
16 16 Failing to do so on Python 2 may lead to a broken IPython install.
17 17
18 18 Configurable TerminalInteractiveShell
19 19 -------------------------------------
20 20
21 21 Backported from the 6.x branch as an exceptional new feature. See
22 22 :ghpull:`10373` and :ghissue:`10364`
23 23
24 24 IPython gained a new ``c.TerminalIPythonApp.interactive_shell_class`` option
25 25 that allow to customize the class used to start the terminal frontend. This
26 26 should allow user to use custom interfaces, like reviving the former readline
27 27 interface which is now a separate package not maintained by the core team.
28 28
29 29
30 30 Define ``_repr_mimebundle_``
31 31 ----------------------------
32 32
33 33 Object can now define `_repr_mimebundle_` in place of multiple `_repr_*_`
34 34 methods and return a full mimebundle. This greatly simplify many implementation
35 35 and allow to publish custom mimetypes (like geojson, plotly, dataframes....).
36 36 See the ``Cutom Display Logic`` example notebook for more informations.
37 37
38 38 Execution Heuristics
39 39 --------------------
40 40
41 41 The heuristic for execution in the command line interface is now more biased
42 42 toward executing for single statement. While in IPython 4.x and before a single
43 43 line would be executed when enter is pressed, IPython 5.x would insert a new
44 44 line. For single line statement this is not true anymore and if a single line is
45 45 valid Python, IPython will execute it regardless of the cursor position. Use
46 46 :kbd:`Ctrl-O` to insert a new line. :ghpull:`10489`
47 47
48 48
49 49 Implement Display IDs
50 50 ---------------------
51 51
52 52 Implement display id and ability to update a given display. This should greatly
53 53 simplify a lot of code by removing the need for widgets and allow other frontend
54 54 to implement things like progress-bars. See :ghpull:`10048`
55 55
56 Display function
57 ----------------
58
59 The :func:`display() <IPython.display.display>` function is now available by
60 default in an IPython session, meaning users can call it on any object to see
61 their rich representation. This should allow for better interactivity both at
62 the REPL and in notebook environment.
63
64 Scripts and library that rely on display and may be run outside of IPython still
65 need to import the display function using ``from IPython.display import
66 display``. See :ghpull:`10596`
67
68
56 69 Miscs
57 70 -----
58 71
59 72 * ``_mp_main_`` is not reloaded which fixes issues with multiprocessing.
60 73 :ghpull:`10523`
61 74 * Use user colorscheme in Pdb as well :ghpull:`10479`
62 75 * Faster shutdown. :ghpull:`10408`
63 76 * Fix a crash in reverse search. :ghpull:`10371`
64 77 * added ``Completer.backslash_combining_completions`` boolean option to
65 78 deactivate backslash-tab completion that may conflict with windows path.
66 79
67 80 IPython 5.3
68 81 ===========
69 82
70 83 Released on February 24th, 2017. Remarkable changes and fixes:
71 84
72 85 * Fix a bug in ``set_next_input`` leading to a crash of terminal IPython.
73 86 :ghpull:`10231`, :ghissue:`10296`, :ghissue:`10229`
74 87 * Always wait for editor inputhook for terminal IPython :ghpull:`10239`,
75 88 :ghpull:`10240`
76 89 * Disable ``_ipython_display_`` in terminal :ghpull:`10249`, :ghpull:`10274`
77 90 * Update terminal colors to be more visible by default on windows
78 91 :ghpull:`10260`, :ghpull:`10238`, :ghissue:`10281`
79 92 * Add Ctrl-Z shortcut (suspend) in terminal debugger :ghpull:`10254`,
80 93 :ghissue:`10273`
81 94 * Indent on new line by looking at the text before the cursor :ghpull:`10264`,
82 95 :ghpull:`10275`, :ghissue:`9283`
83 96 * Update QtEventloop integration to fix some matplotlib integration issues
84 97 :ghpull:`10201`, :ghpull:`10311`, :ghissue:`10201`
85 98 * Respect completions display style in terminal debugger :ghpull:`10305`,
86 99 :ghpull:`10313`
87 100 * Add a config option ``TerminalInteractiveShell.extra_open_editor_shortcuts``
88 101 to enable extra shortcuts to open the input in an editor. These are :kbd:`v`
89 102 in vi mode, and :kbd:`C-X C-E` in emacs mode (:ghpull:`10330`).
90 103 The :kbd:`F2` shortcut is always enabled.
91 104
92 105 IPython 5.2.2
93 106 =============
94 107
95 108 * Fix error when starting with ``IPCompleter.limit_to__all__`` configured.
96 109
97 110 IPython 5.2.1
98 111 =============
99 112
100 113 * Fix tab completion in the debugger. :ghpull:`10223`
101 114
102 115 IPython 5.2
103 116 ===========
104 117
105 118 Released on January 29th, 2017. Remarkable changes and fixes:
106 119
107 120 * restore IPython's debugger to raise on quit. :ghpull:`10009`
108 121 * The configuration value ``c.TerminalInteractiveShell.highlighting_style`` can
109 122 now directly take a class argument for custom color style. :ghpull:`9848`
110 123 * Correctly handle matplotlib figures dpi :ghpull:`9868`
111 124 * Deprecate ``-e`` flag for the ``%notebook`` magic that had no effects.
112 125 :ghpull:`9872`
113 126 * You can now press F2 while typing at a terminal prompt to edit the contents
114 127 in your favourite terminal editor. Set the :envvar:`EDITOR` environment
115 128 variable to pick which editor is used. :ghpull:`9929`
116 129 * sdists will now only be ``.tar.gz`` as per upstream PyPI requirements.
117 130 :ghpull:`9925`
118 131 * :any:`IPython.core.debugger` have gained a ``set_trace()`` method for
119 132 convenience. :ghpull:`9947`
120 133 * The 'smart command mode' added to the debugger in 5.0 was removed, as more
121 134 people preferred the previous behaviour. Therefore, debugger commands such as
122 135 ``c`` will act as debugger commands even when ``c`` is defined as a variable.
123 136 :ghpull:`10050`
124 137 * Fixes OS X event loop issues at startup, :ghpull:`10150`
125 138 * Deprecate the ``%autoindent`` magic. :ghpull:`10176`
126 139 * Emit a :any:`DeprecationWarning` when setting the deprecated
127 140 ``limit_to_all`` option of the completer. :ghpull:`10198`
128 141 * The :cellmagic:`capture` magic can now capture the result of a cell (from an
129 142 expression on the last line), as well as printed and displayed output.
130 143 :ghpull:`9851`.
131 144
132 145
133 146 Changes of behavior to :any:`InteractiveShellEmbed`.
134 147
135 148 :any:`InteractiveShellEmbed` interactive behavior have changed a bit in between
136 149 5.1 and 5.2. By default ``%kill_embedded`` magic will prevent further invocation
137 150 of the current ``call location`` instead of preventing further invocation of
138 151 the current instance creation location. For most use case this will not change
139 152 much for you, though previous behavior was confusing and less consistent with
140 153 previous IPython versions.
141 154
142 155 You can now deactivate instances by using ``%kill_embedded --instance`` flag,
143 156 (or ``-i`` in short). The ``%kill_embedded`` magic also gained a
144 157 ``--yes``/``-y`` option which skip confirmation step, and ``-x``/``--exit``
145 158 which also exit the current embedded call without asking for confirmation.
146 159
147 160 See :ghpull:`10207`.
148 161
149 162
150 163
151 164 IPython 5.1
152 165 ===========
153 166
154 167 * Broken ``%timeit`` on Python2 due to the use of ``__qualname__``. :ghpull:`9804`
155 168 * Restore ``%gui qt`` to create and return a ``QApplication`` if necessary. :ghpull:`9789`
156 169 * Don't set terminal title by default. :ghpull:`9801`
157 170 * Preserve indentation when inserting newlines with ``Ctrl-O``. :ghpull:`9770`
158 171 * Restore completion in debugger. :ghpull:`9785`
159 172 * Deprecate ``IPython.core.debugger.Tracer()`` in favor of simpler, newer, APIs. :ghpull:`9731`
160 173 * Restore ``NoOpContext`` context manager removed by mistake, and add `DeprecationWarning`. :ghpull:`9765`
161 174 * Add option allowing ``Prompt_toolkit`` to use 24bits colors. :ghpull:`9736`
162 175 * Fix for closing interactive matplotlib windows on OS X. :ghpull:`9854`
163 176 * An embedded interactive shell instance can be used more than once. :ghpull:`9843`
164 177 * More robust check for whether IPython is in a terminal. :ghpull:`9833`
165 178 * Better pretty-printing of dicts on PyPy. :ghpull:`9827`
166 179 * Some coloured output now looks better on dark background command prompts in Windows.
167 180 :ghpull:`9838`
168 181 * Improved tab completion of paths on Windows . :ghpull:`9826`
169 182 * Fix tkinter event loop integration on Python 2 with ``future`` installed. :ghpull:`9824`
170 183 * Restore ``Ctrl-\`` as a shortcut to quit IPython.
171 184 * Make ``get_ipython()`` accessible when modules are imported by startup files. :ghpull:`9818`
172 185 * Add support for running directories containing a ``__main__.py`` file with the
173 186 ``ipython`` command. :ghpull:`9813`
174 187
175 188
176 189 True Color feature
177 190 ------------------
178 191
179 192 ``prompt_toolkit`` uses pygments styles for syntax highlighting. By default, the
180 193 colors specified in the style are approximated using a standard 256-color
181 194 palette. ``prompt_toolkit`` also supports 24bit, a.k.a. "true", a.k.a. 16-million
182 195 color escape sequences which enable compatible terminals to display the exact
183 196 colors specified instead of an approximation. This true_color option exposes
184 197 that capability in prompt_toolkit to the IPython shell.
185 198
186 199 Here is a good source for the current state of true color support in various
187 200 terminal emulators and software projects: https://gist.github.com/XVilka/8346728
188 201
189 202
190 203
191 204 IPython 5.0
192 205 ===========
193 206
194 207 Released July 7, 2016
195 208
196 209 New terminal interface
197 210 ----------------------
198 211
199 212 IPython 5 features a major upgrade to the terminal interface, bringing live
200 213 syntax highlighting as you type, proper multiline editing and multiline paste,
201 214 and tab completions that don't clutter up your history.
202 215
203 216 .. image:: ../_images/ptshell_features.png
204 217 :alt: New terminal interface features
205 218 :align: center
206 219 :target: ../_images/ptshell_features.png
207 220
208 221 These features are provided by the Python library `prompt_toolkit
209 222 <http://python-prompt-toolkit.readthedocs.io/en/stable/>`__, which replaces
210 223 ``readline`` throughout our terminal interface.
211 224
212 225 Relying on this pure-Python, cross platform module also makes it simpler to
213 226 install IPython. We have removed dependencies on ``pyreadline`` for Windows and
214 227 ``gnureadline`` for Mac.
215 228
216 229 Backwards incompatible changes
217 230 ------------------------------
218 231
219 232 - The ``%install_ext`` magic function, deprecated since 4.0, has now been deleted.
220 233 You can distribute and install extensions as packages on PyPI.
221 234 - Callbacks registered while an event is being handled will now only be called
222 235 for subsequent events; previously they could be called for the current event.
223 236 Similarly, callbacks removed while handling an event *will* always get that
224 237 event. See :ghissue:`9447` and :ghpull:`9453`.
225 238 - Integration with pydb has been removed since pydb development has been stopped
226 239 since 2012, and pydb is not installable from PyPI.
227 240 - The ``autoedit_syntax`` option has apparently been broken for many years.
228 241 It has been removed.
229 242
230 243 New terminal interface
231 244 ~~~~~~~~~~~~~~~~~~~~~~
232 245
233 246 The overhaul of the terminal interface will probably cause a range of minor
234 247 issues for existing users.
235 248 This is inevitable for such a significant change, and we've done our best to
236 249 minimise these issues.
237 250 Some changes that we're aware of, with suggestions on how to handle them:
238 251
239 252 IPython no longer uses readline configuration (``~/.inputrc``). We hope that
240 253 the functionality you want (e.g. vi input mode) will be available by configuring
241 254 IPython directly (see :doc:`/config/options/terminal`).
242 255 If something's missing, please file an issue.
243 256
244 257 The ``PromptManager`` class has been removed, and the prompt machinery simplified.
245 258 See :ref:`custom_prompts` to customise prompts with the new machinery.
246 259
247 260 :mod:`IPython.core.debugger` now provides a plainer interface.
248 261 :mod:`IPython.terminal.debugger` contains the terminal debugger using
249 262 prompt_toolkit.
250 263
251 264 There are new options to configure the colours used in syntax highlighting.
252 265 We have tried to integrate them with our classic ``--colors`` option and
253 266 ``%colors`` magic, but there's a mismatch in possibilities, so some configurations
254 267 may produce unexpected results. See :ref:`termcolour` for more information.
255 268
256 269 The new interface is not compatible with Emacs 'inferior-shell' feature. To
257 270 continue using this, add the ``--simple-prompt`` flag to the command Emacs
258 271 runs. This flag disables most IPython features, relying on Emacs to provide
259 272 things like tab completion.
260 273
261 274 Provisional Changes
262 275 -------------------
263 276
264 277 Provisional changes are experimental functionality that may, or may not, make
265 278 it into a future version of IPython, and which API may change without warnings.
266 279 Activating these features and using these API are at your own risk, and may have
267 280 security implication for your system, especially if used with the Jupyter notebook,
268 281
269 282 When running via the Jupyter notebook interfaces, or other compatible client,
270 283 you can enable rich documentation experimental functionality:
271 284
272 285 When the ``docrepr`` package is installed setting the boolean flag
273 286 ``InteractiveShell.sphinxify_docstring`` to ``True``, will process the various
274 287 object through sphinx before displaying them (see the ``docrepr`` package
275 288 documentation for more information.
276 289
277 290 You need to also enable the IPython pager display rich HTML representation
278 291 using the ``InteractiveShell.enable_html_pager`` boolean configuration option.
279 292 As usual you can set these configuration options globally in your configuration
280 293 files, alternatively you can turn them on dynamically using the following
281 294 snippet:
282 295
283 296 .. code-block:: python
284 297
285 298 ip = get_ipython()
286 299 ip.sphinxify_docstring = True
287 300 ip.enable_html_pager = True
288 301
289 302
290 303 You can test the effect of various combinations of the above configuration in
291 304 the Jupyter notebook, with things example like :
292 305
293 306 .. code-block:: ipython
294 307
295 308 import numpy as np
296 309 np.histogram?
297 310
298 311
299 312 This is part of an effort to make Documentation in Python richer and provide in
300 313 the long term if possible dynamic examples that can contain math, images,
301 314 widgets... As stated above this is nightly experimental feature with a lot of
302 315 (fun) problem to solve. We would be happy to get your feedback and expertise on
303 316 it.
304 317
305 318
306 319
307 320 Deprecated Features
308 321 -------------------
309 322
310 323 Some deprecated features are listed in this section. Don't forget to enable
311 324 ``DeprecationWarning`` as an error if you are using IPython in a Continuous
312 325 Integration setup or in your testing in general:
313 326
314 327 .. code-block:: python
315 328
316 329 import warnings
317 330 warnings.filterwarnings('error', '.*', DeprecationWarning, module='yourmodule.*')
318 331
319 332
320 333 - ``hooks.fix_error_editor`` seems unused and is pending deprecation.
321 334 - `IPython/core/excolors.py:ExceptionColors` is deprecated.
322 335 - `IPython.core.InteractiveShell:write()` is deprecated; use `sys.stdout` instead.
323 336 - `IPython.core.InteractiveShell:write_err()` is deprecated; use `sys.stderr` instead.
324 337 - The `formatter` keyword argument to `Inspector.info` in `IPython.core.oinspec` has no effect.
325 338 - The `global_ns` keyword argument of IPython Embed was deprecated, and has no effect. Use `module` keyword argument instead.
326 339
327 340
328 341 Known Issues:
329 342 -------------
330 343
331 344 - ``<Esc>`` Key does not dismiss the completer and does not clear the current
332 345 buffer. This is an on purpose modification due to current technical
333 346 limitation. Cf :ghpull:`9572`. Escape the control character which is used
334 347 for other shortcut, and there is no practical way to distinguish. Use Ctr-G
335 348 or Ctrl-C as an alternative.
336 349
337 350 - Cannot use ``Shift-Enter`` and ``Ctrl-Enter`` to submit code in terminal. cf
338 351 :ghissue:`9587` and :ghissue:`9401`. In terminal there is no practical way to
339 352 distinguish these key sequences from a normal new line return.
340 353
341 354 - ``PageUp`` and ``pageDown`` do not move through completion menu.
342 355
343 356 - Color styles might not adapt to terminal emulator themes. This will need new
344 357 version of Pygments to be released, and can be mitigated with custom themes.
345 358
346 359
General Comments 0
You need to be logged in to leave comments. Login now