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