##// END OF EJS Templates
Merge pull request #5992 from dawehner/display-video...
Min RK -
r18367:7b1ea1a9 merge
parent child Browse files
Show More
@@ -1,859 +1,944 b''
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 Authors:
4 Authors:
5
5
6 * Brian Granger
6 * Brian Granger
7 """
7 """
8
8
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Copyright (C) 2013 The IPython Development Team
10 # Copyright (C) 2013 The IPython Development Team
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Imports
17 # Imports
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 from __future__ import print_function
20 from __future__ import print_function
21
21
22 import os
22 import os
23 import struct
23 import struct
24 import mimetypes
24
25
25 from IPython.core.formatters import _safe_get_formatter_method
26 from IPython.core.formatters import _safe_get_formatter_method
26 from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode,
27 from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode,
27 unicode_type)
28 unicode_type)
28 from IPython.testing.skipdoctest import skip_doctest
29 from IPython.testing.skipdoctest import skip_doctest
29
30
30 __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown',
31 __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown',
31 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json',
32 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json',
32 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject',
33 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject',
33 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'JSON', 'Javascript',
34 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'JSON', 'Javascript',
34 'Image', 'clear_output', 'set_matplotlib_formats', 'set_matplotlib_close',
35 'Image', 'clear_output', 'set_matplotlib_formats', 'set_matplotlib_close',
35 'publish_display_data']
36 'publish_display_data']
36
37
37 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
38 # utility functions
39 # utility functions
39 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
40
41
41 def _safe_exists(path):
42 def _safe_exists(path):
42 """Check path, but don't let exceptions raise"""
43 """Check path, but don't let exceptions raise"""
43 try:
44 try:
44 return os.path.exists(path)
45 return os.path.exists(path)
45 except Exception:
46 except Exception:
46 return False
47 return False
47
48
48 def _merge(d1, d2):
49 def _merge(d1, d2):
49 """Like update, but merges sub-dicts instead of clobbering at the top level.
50 """Like update, but merges sub-dicts instead of clobbering at the top level.
50
51
51 Updates d1 in-place
52 Updates d1 in-place
52 """
53 """
53
54
54 if not isinstance(d2, dict) or not isinstance(d1, dict):
55 if not isinstance(d2, dict) or not isinstance(d1, dict):
55 return d2
56 return d2
56 for key, value in d2.items():
57 for key, value in d2.items():
57 d1[key] = _merge(d1.get(key), value)
58 d1[key] = _merge(d1.get(key), value)
58 return d1
59 return d1
59
60
60 def _display_mimetype(mimetype, objs, raw=False, metadata=None):
61 def _display_mimetype(mimetype, objs, raw=False, metadata=None):
61 """internal implementation of all display_foo methods
62 """internal implementation of all display_foo methods
62
63
63 Parameters
64 Parameters
64 ----------
65 ----------
65 mimetype : str
66 mimetype : str
66 The mimetype to be published (e.g. 'image/png')
67 The mimetype to be published (e.g. 'image/png')
67 objs : tuple of objects
68 objs : tuple of objects
68 The Python objects to display, or if raw=True raw text data to
69 The Python objects to display, or if raw=True raw text data to
69 display.
70 display.
70 raw : bool
71 raw : bool
71 Are the data objects raw data or Python objects that need to be
72 Are the data objects raw data or Python objects that need to be
72 formatted before display? [default: False]
73 formatted before display? [default: False]
73 metadata : dict (optional)
74 metadata : dict (optional)
74 Metadata to be associated with the specific mimetype output.
75 Metadata to be associated with the specific mimetype output.
75 """
76 """
76 if metadata:
77 if metadata:
77 metadata = {mimetype: metadata}
78 metadata = {mimetype: metadata}
78 if raw:
79 if raw:
79 # turn list of pngdata into list of { 'image/png': pngdata }
80 # turn list of pngdata into list of { 'image/png': pngdata }
80 objs = [ {mimetype: obj} for obj in objs ]
81 objs = [ {mimetype: obj} for obj in objs ]
81 display(*objs, raw=raw, metadata=metadata, include=[mimetype])
82 display(*objs, raw=raw, metadata=metadata, include=[mimetype])
82
83
83 #-----------------------------------------------------------------------------
84 #-----------------------------------------------------------------------------
84 # Main functions
85 # Main functions
85 #-----------------------------------------------------------------------------
86 #-----------------------------------------------------------------------------
86
87
87 def publish_display_data(data, metadata=None, source=None):
88 def publish_display_data(data, metadata=None, source=None):
88 """Publish data and metadata to all frontends.
89 """Publish data and metadata to all frontends.
89
90
90 See the ``display_data`` message in the messaging documentation for
91 See the ``display_data`` message in the messaging documentation for
91 more details about this message type.
92 more details about this message type.
92
93
93 The following MIME types are currently implemented:
94 The following MIME types are currently implemented:
94
95
95 * text/plain
96 * text/plain
96 * text/html
97 * text/html
97 * text/markdown
98 * text/markdown
98 * text/latex
99 * text/latex
99 * application/json
100 * application/json
100 * application/javascript
101 * application/javascript
101 * image/png
102 * image/png
102 * image/jpeg
103 * image/jpeg
103 * image/svg+xml
104 * image/svg+xml
104
105
105 Parameters
106 Parameters
106 ----------
107 ----------
107 data : dict
108 data : dict
108 A dictionary having keys that are valid MIME types (like
109 A dictionary having keys that are valid MIME types (like
109 'text/plain' or 'image/svg+xml') and values that are the data for
110 'text/plain' or 'image/svg+xml') and values that are the data for
110 that MIME type. The data itself must be a JSON'able data
111 that MIME type. The data itself must be a JSON'able data
111 structure. Minimally all data should have the 'text/plain' data,
112 structure. Minimally all data should have the 'text/plain' data,
112 which can be displayed by all frontends. If more than the plain
113 which can be displayed by all frontends. If more than the plain
113 text is given, it is up to the frontend to decide which
114 text is given, it is up to the frontend to decide which
114 representation to use.
115 representation to use.
115 metadata : dict
116 metadata : dict
116 A dictionary for metadata related to the data. This can contain
117 A dictionary for metadata related to the data. This can contain
117 arbitrary key, value pairs that frontends can use to interpret
118 arbitrary key, value pairs that frontends can use to interpret
118 the data. mime-type keys matching those in data can be used
119 the data. mime-type keys matching those in data can be used
119 to specify metadata about particular representations.
120 to specify metadata about particular representations.
120 source : str, deprecated
121 source : str, deprecated
121 Unused.
122 Unused.
122 """
123 """
123 from IPython.core.interactiveshell import InteractiveShell
124 from IPython.core.interactiveshell import InteractiveShell
124 InteractiveShell.instance().display_pub.publish(
125 InteractiveShell.instance().display_pub.publish(
125 data=data,
126 data=data,
126 metadata=metadata,
127 metadata=metadata,
127 )
128 )
128
129
129 def display(*objs, **kwargs):
130 def display(*objs, **kwargs):
130 """Display a Python object in all frontends.
131 """Display a Python object in all frontends.
131
132
132 By default all representations will be computed and sent to the frontends.
133 By default all representations will be computed and sent to the frontends.
133 Frontends can decide which representation is used and how.
134 Frontends can decide which representation is used and how.
134
135
135 Parameters
136 Parameters
136 ----------
137 ----------
137 objs : tuple of objects
138 objs : tuple of objects
138 The Python objects to display.
139 The Python objects to display.
139 raw : bool, optional
140 raw : bool, optional
140 Are the objects to be displayed already mimetype-keyed dicts of raw display data,
141 Are the objects to be displayed already mimetype-keyed dicts of raw display data,
141 or Python objects that need to be formatted before display? [default: False]
142 or Python objects that need to be formatted before display? [default: False]
142 include : list or tuple, optional
143 include : list or tuple, optional
143 A list of format type strings (MIME types) to include in the
144 A list of format type strings (MIME types) to include in the
144 format data dict. If this is set *only* the format types included
145 format data dict. If this is set *only* the format types included
145 in this list will be computed.
146 in this list will be computed.
146 exclude : list or tuple, optional
147 exclude : list or tuple, optional
147 A list of format type strings (MIME types) to exclude in the format
148 A list of format type strings (MIME types) to exclude in the format
148 data dict. If this is set all format types will be computed,
149 data dict. If this is set all format types will be computed,
149 except for those included in this argument.
150 except for those included in this argument.
150 metadata : dict, optional
151 metadata : dict, optional
151 A dictionary of metadata to associate with the output.
152 A dictionary of metadata to associate with the output.
152 mime-type keys in this dictionary will be associated with the individual
153 mime-type keys in this dictionary will be associated with the individual
153 representation formats, if they exist.
154 representation formats, if they exist.
154 """
155 """
155 raw = kwargs.get('raw', False)
156 raw = kwargs.get('raw', False)
156 include = kwargs.get('include')
157 include = kwargs.get('include')
157 exclude = kwargs.get('exclude')
158 exclude = kwargs.get('exclude')
158 metadata = kwargs.get('metadata')
159 metadata = kwargs.get('metadata')
159
160
160 from IPython.core.interactiveshell import InteractiveShell
161 from IPython.core.interactiveshell import InteractiveShell
161
162
162 if not raw:
163 if not raw:
163 format = InteractiveShell.instance().display_formatter.format
164 format = InteractiveShell.instance().display_formatter.format
164
165
165 for obj in objs:
166 for obj in objs:
166
167
167 # If _ipython_display_ is defined, use that to display this object.
168 # If _ipython_display_ is defined, use that to display this object.
168 display_method = _safe_get_formatter_method(obj, '_ipython_display_')
169 display_method = _safe_get_formatter_method(obj, '_ipython_display_')
169 if display_method is not None:
170 if display_method is not None:
170 try:
171 try:
171 display_method(**kwargs)
172 display_method(**kwargs)
172 except NotImplementedError:
173 except NotImplementedError:
173 pass
174 pass
174 else:
175 else:
175 continue
176 continue
176 if raw:
177 if raw:
177 publish_display_data(data=obj, metadata=metadata)
178 publish_display_data(data=obj, metadata=metadata)
178 else:
179 else:
179 format_dict, md_dict = format(obj, include=include, exclude=exclude)
180 format_dict, md_dict = format(obj, include=include, exclude=exclude)
180 if metadata:
181 if metadata:
181 # kwarg-specified metadata gets precedence
182 # kwarg-specified metadata gets precedence
182 _merge(md_dict, metadata)
183 _merge(md_dict, metadata)
183 publish_display_data(data=format_dict, metadata=md_dict)
184 publish_display_data(data=format_dict, metadata=md_dict)
184
185
185
186
186 def display_pretty(*objs, **kwargs):
187 def display_pretty(*objs, **kwargs):
187 """Display the pretty (default) representation of an object.
188 """Display the pretty (default) representation of an object.
188
189
189 Parameters
190 Parameters
190 ----------
191 ----------
191 objs : tuple of objects
192 objs : tuple of objects
192 The Python objects to display, or if raw=True raw text data to
193 The Python objects to display, or if raw=True raw text data to
193 display.
194 display.
194 raw : bool
195 raw : bool
195 Are the data objects raw data or Python objects that need to be
196 Are the data objects raw data or Python objects that need to be
196 formatted before display? [default: False]
197 formatted before display? [default: False]
197 metadata : dict (optional)
198 metadata : dict (optional)
198 Metadata to be associated with the specific mimetype output.
199 Metadata to be associated with the specific mimetype output.
199 """
200 """
200 _display_mimetype('text/plain', objs, **kwargs)
201 _display_mimetype('text/plain', objs, **kwargs)
201
202
202
203
203 def display_html(*objs, **kwargs):
204 def display_html(*objs, **kwargs):
204 """Display the HTML representation of an object.
205 """Display the HTML representation of an object.
205
206
206 Parameters
207 Parameters
207 ----------
208 ----------
208 objs : tuple of objects
209 objs : tuple of objects
209 The Python objects to display, or if raw=True raw HTML data to
210 The Python objects to display, or if raw=True raw HTML data to
210 display.
211 display.
211 raw : bool
212 raw : bool
212 Are the data objects raw data or Python objects that need to be
213 Are the data objects raw data or Python objects that need to be
213 formatted before display? [default: False]
214 formatted before display? [default: False]
214 metadata : dict (optional)
215 metadata : dict (optional)
215 Metadata to be associated with the specific mimetype output.
216 Metadata to be associated with the specific mimetype output.
216 """
217 """
217 _display_mimetype('text/html', objs, **kwargs)
218 _display_mimetype('text/html', objs, **kwargs)
218
219
219
220
220 def display_markdown(*objs, **kwargs):
221 def display_markdown(*objs, **kwargs):
221 """Displays the Markdown representation of an object.
222 """Displays the Markdown representation of an object.
222
223
223 Parameters
224 Parameters
224 ----------
225 ----------
225 objs : tuple of objects
226 objs : tuple of objects
226 The Python objects to display, or if raw=True raw markdown data to
227 The Python objects to display, or if raw=True raw markdown data to
227 display.
228 display.
228 raw : bool
229 raw : bool
229 Are the data objects raw data or Python objects that need to be
230 Are the data objects raw data or Python objects that need to be
230 formatted before display? [default: False]
231 formatted before display? [default: False]
231 metadata : dict (optional)
232 metadata : dict (optional)
232 Metadata to be associated with the specific mimetype output.
233 Metadata to be associated with the specific mimetype output.
233 """
234 """
234
235
235 _display_mimetype('text/markdown', objs, **kwargs)
236 _display_mimetype('text/markdown', objs, **kwargs)
236
237
237
238
238 def display_svg(*objs, **kwargs):
239 def display_svg(*objs, **kwargs):
239 """Display the SVG representation of an object.
240 """Display the SVG representation of an object.
240
241
241 Parameters
242 Parameters
242 ----------
243 ----------
243 objs : tuple of objects
244 objs : tuple of objects
244 The Python objects to display, or if raw=True raw svg data to
245 The Python objects to display, or if raw=True raw svg data to
245 display.
246 display.
246 raw : bool
247 raw : bool
247 Are the data objects raw data or Python objects that need to be
248 Are the data objects raw data or Python objects that need to be
248 formatted before display? [default: False]
249 formatted before display? [default: False]
249 metadata : dict (optional)
250 metadata : dict (optional)
250 Metadata to be associated with the specific mimetype output.
251 Metadata to be associated with the specific mimetype output.
251 """
252 """
252 _display_mimetype('image/svg+xml', objs, **kwargs)
253 _display_mimetype('image/svg+xml', objs, **kwargs)
253
254
254
255
255 def display_png(*objs, **kwargs):
256 def display_png(*objs, **kwargs):
256 """Display the PNG representation of an object.
257 """Display the PNG representation of an object.
257
258
258 Parameters
259 Parameters
259 ----------
260 ----------
260 objs : tuple of objects
261 objs : tuple of objects
261 The Python objects to display, or if raw=True raw png data to
262 The Python objects to display, or if raw=True raw png data to
262 display.
263 display.
263 raw : bool
264 raw : bool
264 Are the data objects raw data or Python objects that need to be
265 Are the data objects raw data or Python objects that need to be
265 formatted before display? [default: False]
266 formatted before display? [default: False]
266 metadata : dict (optional)
267 metadata : dict (optional)
267 Metadata to be associated with the specific mimetype output.
268 Metadata to be associated with the specific mimetype output.
268 """
269 """
269 _display_mimetype('image/png', objs, **kwargs)
270 _display_mimetype('image/png', objs, **kwargs)
270
271
271
272
272 def display_jpeg(*objs, **kwargs):
273 def display_jpeg(*objs, **kwargs):
273 """Display the JPEG representation of an object.
274 """Display the JPEG representation of an object.
274
275
275 Parameters
276 Parameters
276 ----------
277 ----------
277 objs : tuple of objects
278 objs : tuple of objects
278 The Python objects to display, or if raw=True raw JPEG data to
279 The Python objects to display, or if raw=True raw JPEG data to
279 display.
280 display.
280 raw : bool
281 raw : bool
281 Are the data objects raw data or Python objects that need to be
282 Are the data objects raw data or Python objects that need to be
282 formatted before display? [default: False]
283 formatted before display? [default: False]
283 metadata : dict (optional)
284 metadata : dict (optional)
284 Metadata to be associated with the specific mimetype output.
285 Metadata to be associated with the specific mimetype output.
285 """
286 """
286 _display_mimetype('image/jpeg', objs, **kwargs)
287 _display_mimetype('image/jpeg', objs, **kwargs)
287
288
288
289
289 def display_latex(*objs, **kwargs):
290 def display_latex(*objs, **kwargs):
290 """Display the LaTeX representation of an object.
291 """Display the LaTeX representation of an object.
291
292
292 Parameters
293 Parameters
293 ----------
294 ----------
294 objs : tuple of objects
295 objs : tuple of objects
295 The Python objects to display, or if raw=True raw latex data to
296 The Python objects to display, or if raw=True raw latex data to
296 display.
297 display.
297 raw : bool
298 raw : bool
298 Are the data objects raw data or Python objects that need to be
299 Are the data objects raw data or Python objects that need to be
299 formatted before display? [default: False]
300 formatted before display? [default: False]
300 metadata : dict (optional)
301 metadata : dict (optional)
301 Metadata to be associated with the specific mimetype output.
302 Metadata to be associated with the specific mimetype output.
302 """
303 """
303 _display_mimetype('text/latex', objs, **kwargs)
304 _display_mimetype('text/latex', objs, **kwargs)
304
305
305
306
306 def display_json(*objs, **kwargs):
307 def display_json(*objs, **kwargs):
307 """Display the JSON representation of an object.
308 """Display the JSON representation of an object.
308
309
309 Note that not many frontends support displaying JSON.
310 Note that not many frontends support displaying JSON.
310
311
311 Parameters
312 Parameters
312 ----------
313 ----------
313 objs : tuple of objects
314 objs : tuple of objects
314 The Python objects to display, or if raw=True raw json data to
315 The Python objects to display, or if raw=True raw json data to
315 display.
316 display.
316 raw : bool
317 raw : bool
317 Are the data objects raw data or Python objects that need to be
318 Are the data objects raw data or Python objects that need to be
318 formatted before display? [default: False]
319 formatted before display? [default: False]
319 metadata : dict (optional)
320 metadata : dict (optional)
320 Metadata to be associated with the specific mimetype output.
321 Metadata to be associated with the specific mimetype output.
321 """
322 """
322 _display_mimetype('application/json', objs, **kwargs)
323 _display_mimetype('application/json', objs, **kwargs)
323
324
324
325
325 def display_javascript(*objs, **kwargs):
326 def display_javascript(*objs, **kwargs):
326 """Display the Javascript representation of an object.
327 """Display the Javascript representation of an object.
327
328
328 Parameters
329 Parameters
329 ----------
330 ----------
330 objs : tuple of objects
331 objs : tuple of objects
331 The Python objects to display, or if raw=True raw javascript data to
332 The Python objects to display, or if raw=True raw javascript data to
332 display.
333 display.
333 raw : bool
334 raw : bool
334 Are the data objects raw data or Python objects that need to be
335 Are the data objects raw data or Python objects that need to be
335 formatted before display? [default: False]
336 formatted before display? [default: False]
336 metadata : dict (optional)
337 metadata : dict (optional)
337 Metadata to be associated with the specific mimetype output.
338 Metadata to be associated with the specific mimetype output.
338 """
339 """
339 _display_mimetype('application/javascript', objs, **kwargs)
340 _display_mimetype('application/javascript', objs, **kwargs)
340
341
341
342
342 def display_pdf(*objs, **kwargs):
343 def display_pdf(*objs, **kwargs):
343 """Display the PDF representation of an object.
344 """Display the PDF representation of an object.
344
345
345 Parameters
346 Parameters
346 ----------
347 ----------
347 objs : tuple of objects
348 objs : tuple of objects
348 The Python objects to display, or if raw=True raw javascript data to
349 The Python objects to display, or if raw=True raw javascript data to
349 display.
350 display.
350 raw : bool
351 raw : bool
351 Are the data objects raw data or Python objects that need to be
352 Are the data objects raw data or Python objects that need to be
352 formatted before display? [default: False]
353 formatted before display? [default: False]
353 metadata : dict (optional)
354 metadata : dict (optional)
354 Metadata to be associated with the specific mimetype output.
355 Metadata to be associated with the specific mimetype output.
355 """
356 """
356 _display_mimetype('application/pdf', objs, **kwargs)
357 _display_mimetype('application/pdf', objs, **kwargs)
357
358
358
359
359 #-----------------------------------------------------------------------------
360 #-----------------------------------------------------------------------------
360 # Smart classes
361 # Smart classes
361 #-----------------------------------------------------------------------------
362 #-----------------------------------------------------------------------------
362
363
363
364
364 class DisplayObject(object):
365 class DisplayObject(object):
365 """An object that wraps data to be displayed."""
366 """An object that wraps data to be displayed."""
366
367
367 _read_flags = 'r'
368 _read_flags = 'r'
368 _show_mem_addr = False
369 _show_mem_addr = False
369
370
370 def __init__(self, data=None, url=None, filename=None):
371 def __init__(self, data=None, url=None, filename=None):
371 """Create a display object given raw data.
372 """Create a display object given raw data.
372
373
373 When this object is returned by an expression or passed to the
374 When this object is returned by an expression or passed to the
374 display function, it will result in the data being displayed
375 display function, it will result in the data being displayed
375 in the frontend. The MIME type of the data should match the
376 in the frontend. The MIME type of the data should match the
376 subclasses used, so the Png subclass should be used for 'image/png'
377 subclasses used, so the Png subclass should be used for 'image/png'
377 data. If the data is a URL, the data will first be downloaded
378 data. If the data is a URL, the data will first be downloaded
378 and then displayed. If
379 and then displayed. If
379
380
380 Parameters
381 Parameters
381 ----------
382 ----------
382 data : unicode, str or bytes
383 data : unicode, str or bytes
383 The raw data or a URL or file to load the data from
384 The raw data or a URL or file to load the data from
384 url : unicode
385 url : unicode
385 A URL to download the data from.
386 A URL to download the data from.
386 filename : unicode
387 filename : unicode
387 Path to a local file to load the data from.
388 Path to a local file to load the data from.
388 """
389 """
389 if data is not None and isinstance(data, string_types):
390 if data is not None and isinstance(data, string_types):
390 if data.startswith('http') and url is None:
391 if data.startswith('http') and url is None:
391 url = data
392 url = data
392 filename = None
393 filename = None
393 data = None
394 data = None
394 elif _safe_exists(data) and filename is None:
395 elif _safe_exists(data) and filename is None:
395 url = None
396 url = None
396 filename = data
397 filename = data
397 data = None
398 data = None
398
399
399 self.data = data
400 self.data = data
400 self.url = url
401 self.url = url
401 self.filename = None if filename is None else unicode_type(filename)
402 self.filename = None if filename is None else unicode_type(filename)
402
403
403 self.reload()
404 self.reload()
404 self._check_data()
405 self._check_data()
405
406
406 def __repr__(self):
407 def __repr__(self):
407 if not self._show_mem_addr:
408 if not self._show_mem_addr:
408 cls = self.__class__
409 cls = self.__class__
409 r = "<%s.%s object>" % (cls.__module__, cls.__name__)
410 r = "<%s.%s object>" % (cls.__module__, cls.__name__)
410 else:
411 else:
411 r = super(DisplayObject, self).__repr__()
412 r = super(DisplayObject, self).__repr__()
412 return r
413 return r
413
414
414 def _check_data(self):
415 def _check_data(self):
415 """Override in subclasses if there's something to check."""
416 """Override in subclasses if there's something to check."""
416 pass
417 pass
417
418
418 def reload(self):
419 def reload(self):
419 """Reload the raw data from file or URL."""
420 """Reload the raw data from file or URL."""
420 if self.filename is not None:
421 if self.filename is not None:
421 with open(self.filename, self._read_flags) as f:
422 with open(self.filename, self._read_flags) as f:
422 self.data = f.read()
423 self.data = f.read()
423 elif self.url is not None:
424 elif self.url is not None:
424 try:
425 try:
425 try:
426 try:
426 from urllib.request import urlopen # Py3
427 from urllib.request import urlopen # Py3
427 except ImportError:
428 except ImportError:
428 from urllib2 import urlopen
429 from urllib2 import urlopen
429 response = urlopen(self.url)
430 response = urlopen(self.url)
430 self.data = response.read()
431 self.data = response.read()
431 # extract encoding from header, if there is one:
432 # extract encoding from header, if there is one:
432 encoding = None
433 encoding = None
433 for sub in response.headers['content-type'].split(';'):
434 for sub in response.headers['content-type'].split(';'):
434 sub = sub.strip()
435 sub = sub.strip()
435 if sub.startswith('charset'):
436 if sub.startswith('charset'):
436 encoding = sub.split('=')[-1].strip()
437 encoding = sub.split('=')[-1].strip()
437 break
438 break
438 # decode data, if an encoding was specified
439 # decode data, if an encoding was specified
439 if encoding:
440 if encoding:
440 self.data = self.data.decode(encoding, 'replace')
441 self.data = self.data.decode(encoding, 'replace')
441 except:
442 except:
442 self.data = None
443 self.data = None
443
444
444 class TextDisplayObject(DisplayObject):
445 class TextDisplayObject(DisplayObject):
445 """Validate that display data is text"""
446 """Validate that display data is text"""
446 def _check_data(self):
447 def _check_data(self):
447 if self.data is not None and not isinstance(self.data, string_types):
448 if self.data is not None and not isinstance(self.data, string_types):
448 raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data))
449 raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data))
449
450
450 class Pretty(TextDisplayObject):
451 class Pretty(TextDisplayObject):
451
452
452 def _repr_pretty_(self):
453 def _repr_pretty_(self):
453 return self.data
454 return self.data
454
455
455
456
456 class HTML(TextDisplayObject):
457 class HTML(TextDisplayObject):
457
458
458 def _repr_html_(self):
459 def _repr_html_(self):
459 return self.data
460 return self.data
460
461
461 def __html__(self):
462 def __html__(self):
462 """
463 """
463 This method exists to inform other HTML-using modules (e.g. Markupsafe,
464 This method exists to inform other HTML-using modules (e.g. Markupsafe,
464 htmltag, etc) that this object is HTML and does not need things like
465 htmltag, etc) that this object is HTML and does not need things like
465 special characters (<>&) escaped.
466 special characters (<>&) escaped.
466 """
467 """
467 return self._repr_html_()
468 return self._repr_html_()
468
469
469
470
470 class Markdown(TextDisplayObject):
471 class Markdown(TextDisplayObject):
471
472
472 def _repr_markdown_(self):
473 def _repr_markdown_(self):
473 return self.data
474 return self.data
474
475
475
476
476 class Math(TextDisplayObject):
477 class Math(TextDisplayObject):
477
478
478 def _repr_latex_(self):
479 def _repr_latex_(self):
479 s = self.data.strip('$')
480 s = self.data.strip('$')
480 return "$$%s$$" % s
481 return "$$%s$$" % s
481
482
482
483
483 class Latex(TextDisplayObject):
484 class Latex(TextDisplayObject):
484
485
485 def _repr_latex_(self):
486 def _repr_latex_(self):
486 return self.data
487 return self.data
487
488
488
489
489 class SVG(DisplayObject):
490 class SVG(DisplayObject):
490
491
491 # wrap data in a property, which extracts the <svg> tag, discarding
492 # wrap data in a property, which extracts the <svg> tag, discarding
492 # document headers
493 # document headers
493 _data = None
494 _data = None
494
495
495 @property
496 @property
496 def data(self):
497 def data(self):
497 return self._data
498 return self._data
498
499
499 @data.setter
500 @data.setter
500 def data(self, svg):
501 def data(self, svg):
501 if svg is None:
502 if svg is None:
502 self._data = None
503 self._data = None
503 return
504 return
504 # parse into dom object
505 # parse into dom object
505 from xml.dom import minidom
506 from xml.dom import minidom
506 svg = cast_bytes_py2(svg)
507 svg = cast_bytes_py2(svg)
507 x = minidom.parseString(svg)
508 x = minidom.parseString(svg)
508 # get svg tag (should be 1)
509 # get svg tag (should be 1)
509 found_svg = x.getElementsByTagName('svg')
510 found_svg = x.getElementsByTagName('svg')
510 if found_svg:
511 if found_svg:
511 svg = found_svg[0].toxml()
512 svg = found_svg[0].toxml()
512 else:
513 else:
513 # fallback on the input, trust the user
514 # fallback on the input, trust the user
514 # but this is probably an error.
515 # but this is probably an error.
515 pass
516 pass
516 svg = cast_unicode(svg)
517 svg = cast_unicode(svg)
517 self._data = svg
518 self._data = svg
518
519
519 def _repr_svg_(self):
520 def _repr_svg_(self):
520 return self.data
521 return self.data
521
522
522
523
523 class JSON(TextDisplayObject):
524 class JSON(TextDisplayObject):
524
525
525 def _repr_json_(self):
526 def _repr_json_(self):
526 return self.data
527 return self.data
527
528
528 css_t = """$("head").append($("<link/>").attr({
529 css_t = """$("head").append($("<link/>").attr({
529 rel: "stylesheet",
530 rel: "stylesheet",
530 type: "text/css",
531 type: "text/css",
531 href: "%s"
532 href: "%s"
532 }));
533 }));
533 """
534 """
534
535
535 lib_t1 = """$.getScript("%s", function () {
536 lib_t1 = """$.getScript("%s", function () {
536 """
537 """
537 lib_t2 = """});
538 lib_t2 = """});
538 """
539 """
539
540
540 class Javascript(TextDisplayObject):
541 class Javascript(TextDisplayObject):
541
542
542 def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
543 def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
543 """Create a Javascript display object given raw data.
544 """Create a Javascript display object given raw data.
544
545
545 When this object is returned by an expression or passed to the
546 When this object is returned by an expression or passed to the
546 display function, it will result in the data being displayed
547 display function, it will result in the data being displayed
547 in the frontend. If the data is a URL, the data will first be
548 in the frontend. If the data is a URL, the data will first be
548 downloaded and then displayed.
549 downloaded and then displayed.
549
550
550 In the Notebook, the containing element will be available as `element`,
551 In the Notebook, the containing element will be available as `element`,
551 and jQuery will be available. Content appended to `element` will be
552 and jQuery will be available. Content appended to `element` will be
552 visible in the output area.
553 visible in the output area.
553
554
554 Parameters
555 Parameters
555 ----------
556 ----------
556 data : unicode, str or bytes
557 data : unicode, str or bytes
557 The Javascript source code or a URL to download it from.
558 The Javascript source code or a URL to download it from.
558 url : unicode
559 url : unicode
559 A URL to download the data from.
560 A URL to download the data from.
560 filename : unicode
561 filename : unicode
561 Path to a local file to load the data from.
562 Path to a local file to load the data from.
562 lib : list or str
563 lib : list or str
563 A sequence of Javascript library URLs to load asynchronously before
564 A sequence of Javascript library URLs to load asynchronously before
564 running the source code. The full URLs of the libraries should
565 running the source code. The full URLs of the libraries should
565 be given. A single Javascript library URL can also be given as a
566 be given. A single Javascript library URL can also be given as a
566 string.
567 string.
567 css: : list or str
568 css: : list or str
568 A sequence of css files to load before running the source code.
569 A sequence of css files to load before running the source code.
569 The full URLs of the css files should be given. A single css URL
570 The full URLs of the css files should be given. A single css URL
570 can also be given as a string.
571 can also be given as a string.
571 """
572 """
572 if isinstance(lib, string_types):
573 if isinstance(lib, string_types):
573 lib = [lib]
574 lib = [lib]
574 elif lib is None:
575 elif lib is None:
575 lib = []
576 lib = []
576 if isinstance(css, string_types):
577 if isinstance(css, string_types):
577 css = [css]
578 css = [css]
578 elif css is None:
579 elif css is None:
579 css = []
580 css = []
580 if not isinstance(lib, (list,tuple)):
581 if not isinstance(lib, (list,tuple)):
581 raise TypeError('expected sequence, got: %r' % lib)
582 raise TypeError('expected sequence, got: %r' % lib)
582 if not isinstance(css, (list,tuple)):
583 if not isinstance(css, (list,tuple)):
583 raise TypeError('expected sequence, got: %r' % css)
584 raise TypeError('expected sequence, got: %r' % css)
584 self.lib = lib
585 self.lib = lib
585 self.css = css
586 self.css = css
586 super(Javascript, self).__init__(data=data, url=url, filename=filename)
587 super(Javascript, self).__init__(data=data, url=url, filename=filename)
587
588
588 def _repr_javascript_(self):
589 def _repr_javascript_(self):
589 r = ''
590 r = ''
590 for c in self.css:
591 for c in self.css:
591 r += css_t % c
592 r += css_t % c
592 for l in self.lib:
593 for l in self.lib:
593 r += lib_t1 % l
594 r += lib_t1 % l
594 r += self.data
595 r += self.data
595 r += lib_t2*len(self.lib)
596 r += lib_t2*len(self.lib)
596 return r
597 return r
597
598
598 # constants for identifying png/jpeg data
599 # constants for identifying png/jpeg data
599 _PNG = b'\x89PNG\r\n\x1a\n'
600 _PNG = b'\x89PNG\r\n\x1a\n'
600 _JPEG = b'\xff\xd8'
601 _JPEG = b'\xff\xd8'
601
602
602 def _pngxy(data):
603 def _pngxy(data):
603 """read the (width, height) from a PNG header"""
604 """read the (width, height) from a PNG header"""
604 ihdr = data.index(b'IHDR')
605 ihdr = data.index(b'IHDR')
605 # next 8 bytes are width/height
606 # next 8 bytes are width/height
606 w4h4 = data[ihdr+4:ihdr+12]
607 w4h4 = data[ihdr+4:ihdr+12]
607 return struct.unpack('>ii', w4h4)
608 return struct.unpack('>ii', w4h4)
608
609
609 def _jpegxy(data):
610 def _jpegxy(data):
610 """read the (width, height) from a JPEG header"""
611 """read the (width, height) from a JPEG header"""
611 # adapted from http://www.64lines.com/jpeg-width-height
612 # adapted from http://www.64lines.com/jpeg-width-height
612
613
613 idx = 4
614 idx = 4
614 while True:
615 while True:
615 block_size = struct.unpack('>H', data[idx:idx+2])[0]
616 block_size = struct.unpack('>H', data[idx:idx+2])[0]
616 idx = idx + block_size
617 idx = idx + block_size
617 if data[idx:idx+2] == b'\xFF\xC0':
618 if data[idx:idx+2] == b'\xFF\xC0':
618 # found Start of Frame
619 # found Start of Frame
619 iSOF = idx
620 iSOF = idx
620 break
621 break
621 else:
622 else:
622 # read another block
623 # read another block
623 idx += 2
624 idx += 2
624
625
625 h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9])
626 h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9])
626 return w, h
627 return w, h
627
628
628 class Image(DisplayObject):
629 class Image(DisplayObject):
629
630
630 _read_flags = 'rb'
631 _read_flags = 'rb'
631 _FMT_JPEG = u'jpeg'
632 _FMT_JPEG = u'jpeg'
632 _FMT_PNG = u'png'
633 _FMT_PNG = u'png'
633 _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG]
634 _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG]
634
635
635 def __init__(self, data=None, url=None, filename=None, format=u'png', embed=None, width=None, height=None, retina=False):
636 def __init__(self, data=None, url=None, filename=None, format=u'png', embed=None, width=None, height=None, retina=False):
636 """Create a PNG/JPEG image object given raw data.
637 """Create a PNG/JPEG image object given raw data.
637
638
638 When this object is returned by an input cell or passed to the
639 When this object is returned by an input cell or passed to the
639 display function, it will result in the image being displayed
640 display function, it will result in the image being displayed
640 in the frontend.
641 in the frontend.
641
642
642 Parameters
643 Parameters
643 ----------
644 ----------
644 data : unicode, str or bytes
645 data : unicode, str or bytes
645 The raw image data or a URL or filename to load the data from.
646 The raw image data or a URL or filename to load the data from.
646 This always results in embedded image data.
647 This always results in embedded image data.
647 url : unicode
648 url : unicode
648 A URL to download the data from. If you specify `url=`,
649 A URL to download the data from. If you specify `url=`,
649 the image data will not be embedded unless you also specify `embed=True`.
650 the image data will not be embedded unless you also specify `embed=True`.
650 filename : unicode
651 filename : unicode
651 Path to a local file to load the data from.
652 Path to a local file to load the data from.
652 Images from a file are always embedded.
653 Images from a file are always embedded.
653 format : unicode
654 format : unicode
654 The format of the image data (png/jpeg/jpg). If a filename or URL is given
655 The format of the image data (png/jpeg/jpg). If a filename or URL is given
655 for format will be inferred from the filename extension.
656 for format will be inferred from the filename extension.
656 embed : bool
657 embed : bool
657 Should the image data be embedded using a data URI (True) or be
658 Should the image data be embedded using a data URI (True) or be
658 loaded using an <img> tag. Set this to True if you want the image
659 loaded using an <img> tag. Set this to True if you want the image
659 to be viewable later with no internet connection in the notebook.
660 to be viewable later with no internet connection in the notebook.
660
661
661 Default is `True`, unless the keyword argument `url` is set, then
662 Default is `True`, unless the keyword argument `url` is set, then
662 default value is `False`.
663 default value is `False`.
663
664
664 Note that QtConsole is not able to display images if `embed` is set to `False`
665 Note that QtConsole is not able to display images if `embed` is set to `False`
665 width : int
666 width : int
666 Width to which to constrain the image in html
667 Width to which to constrain the image in html
667 height : int
668 height : int
668 Height to which to constrain the image in html
669 Height to which to constrain the image in html
669 retina : bool
670 retina : bool
670 Automatically set the width and height to half of the measured
671 Automatically set the width and height to half of the measured
671 width and height.
672 width and height.
672 This only works for embedded images because it reads the width/height
673 This only works for embedded images because it reads the width/height
673 from image data.
674 from image data.
674 For non-embedded images, you can just set the desired display width
675 For non-embedded images, you can just set the desired display width
675 and height directly.
676 and height directly.
676
677
677 Examples
678 Examples
678 --------
679 --------
679 # embedded image data, works in qtconsole and notebook
680 # embedded image data, works in qtconsole and notebook
680 # when passed positionally, the first arg can be any of raw image data,
681 # when passed positionally, the first arg can be any of raw image data,
681 # a URL, or a filename from which to load image data.
682 # a URL, or a filename from which to load image data.
682 # The result is always embedding image data for inline images.
683 # The result is always embedding image data for inline images.
683 Image('http://www.google.fr/images/srpr/logo3w.png')
684 Image('http://www.google.fr/images/srpr/logo3w.png')
684 Image('/path/to/image.jpg')
685 Image('/path/to/image.jpg')
685 Image(b'RAW_PNG_DATA...')
686 Image(b'RAW_PNG_DATA...')
686
687
687 # Specifying Image(url=...) does not embed the image data,
688 # Specifying Image(url=...) does not embed the image data,
688 # it only generates `<img>` tag with a link to the source.
689 # it only generates `<img>` tag with a link to the source.
689 # This will not work in the qtconsole or offline.
690 # This will not work in the qtconsole or offline.
690 Image(url='http://www.google.fr/images/srpr/logo3w.png')
691 Image(url='http://www.google.fr/images/srpr/logo3w.png')
691
692
692 """
693 """
693 if filename is not None:
694 if filename is not None:
694 ext = self._find_ext(filename)
695 ext = self._find_ext(filename)
695 elif url is not None:
696 elif url is not None:
696 ext = self._find_ext(url)
697 ext = self._find_ext(url)
697 elif data is None:
698 elif data is None:
698 raise ValueError("No image data found. Expecting filename, url, or data.")
699 raise ValueError("No image data found. Expecting filename, url, or data.")
699 elif isinstance(data, string_types) and (
700 elif isinstance(data, string_types) and (
700 data.startswith('http') or _safe_exists(data)
701 data.startswith('http') or _safe_exists(data)
701 ):
702 ):
702 ext = self._find_ext(data)
703 ext = self._find_ext(data)
703 else:
704 else:
704 ext = None
705 ext = None
705
706
706 if ext is not None:
707 if ext is not None:
707 format = ext.lower()
708 format = ext.lower()
708 if ext == u'jpg' or ext == u'jpeg':
709 if ext == u'jpg' or ext == u'jpeg':
709 format = self._FMT_JPEG
710 format = self._FMT_JPEG
710 if ext == u'png':
711 if ext == u'png':
711 format = self._FMT_PNG
712 format = self._FMT_PNG
712 elif isinstance(data, bytes) and format == 'png':
713 elif isinstance(data, bytes) and format == 'png':
713 # infer image type from image data header,
714 # infer image type from image data header,
714 # only if format might not have been specified.
715 # only if format might not have been specified.
715 if data[:2] == _JPEG:
716 if data[:2] == _JPEG:
716 format = 'jpeg'
717 format = 'jpeg'
717
718
718 self.format = unicode_type(format).lower()
719 self.format = unicode_type(format).lower()
719 self.embed = embed if embed is not None else (url is None)
720 self.embed = embed if embed is not None else (url is None)
720
721
721 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
722 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
722 raise ValueError("Cannot embed the '%s' image format" % (self.format))
723 raise ValueError("Cannot embed the '%s' image format" % (self.format))
723 self.width = width
724 self.width = width
724 self.height = height
725 self.height = height
725 self.retina = retina
726 self.retina = retina
726 super(Image, self).__init__(data=data, url=url, filename=filename)
727 super(Image, self).__init__(data=data, url=url, filename=filename)
727
728
728 if retina:
729 if retina:
729 self._retina_shape()
730 self._retina_shape()
730
731
731 def _retina_shape(self):
732 def _retina_shape(self):
732 """load pixel-doubled width and height from image data"""
733 """load pixel-doubled width and height from image data"""
733 if not self.embed:
734 if not self.embed:
734 return
735 return
735 if self.format == 'png':
736 if self.format == 'png':
736 w, h = _pngxy(self.data)
737 w, h = _pngxy(self.data)
737 elif self.format == 'jpeg':
738 elif self.format == 'jpeg':
738 w, h = _jpegxy(self.data)
739 w, h = _jpegxy(self.data)
739 else:
740 else:
740 # retina only supports png
741 # retina only supports png
741 return
742 return
742 self.width = w // 2
743 self.width = w // 2
743 self.height = h // 2
744 self.height = h // 2
744
745
745 def reload(self):
746 def reload(self):
746 """Reload the raw data from file or URL."""
747 """Reload the raw data from file or URL."""
747 if self.embed:
748 if self.embed:
748 super(Image,self).reload()
749 super(Image,self).reload()
749 if self.retina:
750 if self.retina:
750 self._retina_shape()
751 self._retina_shape()
751
752
752 def _repr_html_(self):
753 def _repr_html_(self):
753 if not self.embed:
754 if not self.embed:
754 width = height = ''
755 width = height = ''
755 if self.width:
756 if self.width:
756 width = ' width="%d"' % self.width
757 width = ' width="%d"' % self.width
757 if self.height:
758 if self.height:
758 height = ' height="%d"' % self.height
759 height = ' height="%d"' % self.height
759 return u'<img src="%s"%s%s/>' % (self.url, width, height)
760 return u'<img src="%s"%s%s/>' % (self.url, width, height)
760
761
761 def _data_and_metadata(self):
762 def _data_and_metadata(self):
762 """shortcut for returning metadata with shape information, if defined"""
763 """shortcut for returning metadata with shape information, if defined"""
763 md = {}
764 md = {}
764 if self.width:
765 if self.width:
765 md['width'] = self.width
766 md['width'] = self.width
766 if self.height:
767 if self.height:
767 md['height'] = self.height
768 md['height'] = self.height
768 if md:
769 if md:
769 return self.data, md
770 return self.data, md
770 else:
771 else:
771 return self.data
772 return self.data
772
773
773 def _repr_png_(self):
774 def _repr_png_(self):
774 if self.embed and self.format == u'png':
775 if self.embed and self.format == u'png':
775 return self._data_and_metadata()
776 return self._data_and_metadata()
776
777
777 def _repr_jpeg_(self):
778 def _repr_jpeg_(self):
778 if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
779 if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
779 return self._data_and_metadata()
780 return self._data_and_metadata()
780
781
781 def _find_ext(self, s):
782 def _find_ext(self, s):
782 return unicode_type(s.split('.')[-1].lower())
783 return unicode_type(s.split('.')[-1].lower())
783
784
785 class Video(DisplayObject):
786
787 def __init__(self, data=None, url=None, filename=None, embed=None, mimetype=None):
788 """Create a video object given raw data or an URL.
789
790 When this object is returned by an input cell or passed to the
791 display function, it will result in the video being displayed
792 in the frontend.
793
794 Parameters
795 ----------
796 data : unicode, str or bytes
797 The raw image data or a URL or filename to load the data from.
798 This always results in embedded image data.
799 url : unicode
800 A URL to download the data from. If you specify `url=`,
801 the image data will not be embedded unless you also specify `embed=True`.
802 filename : unicode
803 Path to a local file to load the data from.
804 Videos from a file are always embedded.
805 embed : bool
806 Should the image data be embedded using a data URI (True) or be
807 loaded using an <img> tag. Set this to True if you want the image
808 to be viewable later with no internet connection in the notebook.
809
810 Default is `True`, unless the keyword argument `url` is set, then
811 default value is `False`.
812
813 Note that QtConsole is not able to display images if `embed` is set to `False`
814 mimetype: unicode
815 Specify the mimetype in case you load in a encoded video.
816 Examples
817 --------
818 Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4')
819 Video('path/to/video.mp4')
820 Video('path/to/video.mp4', embed=False)
821 """
822 if url is None and (data.startswith('http') or data.startswith('https')):
823 url = data
824 data = None
825 embed = False
826 elif os.path.exists(data):
827 filename = data
828 data = None
829
830 self.mimetype = mimetype
831 self.embed = embed if embed is not None else (filename is not None)
832 super(Video, self).__init__(data=data, url=url, filename=filename)
833
834 def _repr_html_(self):
835 # External URLs and potentially local files are not embedded into the
836 # notebook output.
837 if not self.embed:
838 url = self.url if self.url is not None else self.filename
839 output = """<video src="{0}" controls>
840 Your browser does not support the <code>video</code> element.
841 </video>""".format(url)
842 return output
843 # Embedded videos uses base64 encoded videos.
844 if self.filename is not None:
845 mimetypes.init()
846 mimetype, encoding = mimetypes.guess_type(self.filename)
847
848 video = open(self.filename, 'rb').read()
849 video_encoded = video.encode('base64')
850 else:
851 video_encoded = self.data
852 mimetype = self.mimetype
853 output = """<video controls>
854 <source src="data:{0};base64,{1}" type="{0}">
855 Your browser does not support the video tag.
856 </video>""".format(mimetype, video_encoded)
857 return output
858
859 def reload(self):
860 # TODO
861 pass
862
863 def _repr_png_(self):
864 # TODO
865 pass
866 def _repr_jpeg_(self):
867 # TODO
868 pass
784
869
785 def clear_output(wait=False):
870 def clear_output(wait=False):
786 """Clear the output of the current cell receiving output.
871 """Clear the output of the current cell receiving output.
787
872
788 Parameters
873 Parameters
789 ----------
874 ----------
790 wait : bool [default: false]
875 wait : bool [default: false]
791 Wait to clear the output until new output is available to replace it."""
876 Wait to clear the output until new output is available to replace it."""
792 from IPython.core.interactiveshell import InteractiveShell
877 from IPython.core.interactiveshell import InteractiveShell
793 if InteractiveShell.initialized():
878 if InteractiveShell.initialized():
794 InteractiveShell.instance().display_pub.clear_output(wait)
879 InteractiveShell.instance().display_pub.clear_output(wait)
795 else:
880 else:
796 from IPython.utils import io
881 from IPython.utils import io
797 print('\033[2K\r', file=io.stdout, end='')
882 print('\033[2K\r', file=io.stdout, end='')
798 io.stdout.flush()
883 io.stdout.flush()
799 print('\033[2K\r', file=io.stderr, end='')
884 print('\033[2K\r', file=io.stderr, end='')
800 io.stderr.flush()
885 io.stderr.flush()
801
886
802
887
803 @skip_doctest
888 @skip_doctest
804 def set_matplotlib_formats(*formats, **kwargs):
889 def set_matplotlib_formats(*formats, **kwargs):
805 """Select figure formats for the inline backend. Optionally pass quality for JPEG.
890 """Select figure formats for the inline backend. Optionally pass quality for JPEG.
806
891
807 For example, this enables PNG and JPEG output with a JPEG quality of 90%::
892 For example, this enables PNG and JPEG output with a JPEG quality of 90%::
808
893
809 In [1]: set_matplotlib_formats('png', 'jpeg', quality=90)
894 In [1]: set_matplotlib_formats('png', 'jpeg', quality=90)
810
895
811 To set this in your config files use the following::
896 To set this in your config files use the following::
812
897
813 c.InlineBackend.figure_formats = {'png', 'jpeg'}
898 c.InlineBackend.figure_formats = {'png', 'jpeg'}
814 c.InlineBackend.print_figure_kwargs.update({'quality' : 90})
899 c.InlineBackend.print_figure_kwargs.update({'quality' : 90})
815
900
816 Parameters
901 Parameters
817 ----------
902 ----------
818 *formats : strs
903 *formats : strs
819 One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
904 One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
820 **kwargs :
905 **kwargs :
821 Keyword args will be relayed to ``figure.canvas.print_figure``.
906 Keyword args will be relayed to ``figure.canvas.print_figure``.
822 """
907 """
823 from IPython.core.interactiveshell import InteractiveShell
908 from IPython.core.interactiveshell import InteractiveShell
824 from IPython.core.pylabtools import select_figure_formats
909 from IPython.core.pylabtools import select_figure_formats
825 from IPython.kernel.zmq.pylab.config import InlineBackend
910 from IPython.kernel.zmq.pylab.config import InlineBackend
826 # build kwargs, starting with InlineBackend config
911 # build kwargs, starting with InlineBackend config
827 kw = {}
912 kw = {}
828 cfg = InlineBackend.instance()
913 cfg = InlineBackend.instance()
829 kw.update(cfg.print_figure_kwargs)
914 kw.update(cfg.print_figure_kwargs)
830 kw.update(**kwargs)
915 kw.update(**kwargs)
831 shell = InteractiveShell.instance()
916 shell = InteractiveShell.instance()
832 select_figure_formats(shell, formats, **kw)
917 select_figure_formats(shell, formats, **kw)
833
918
834 @skip_doctest
919 @skip_doctest
835 def set_matplotlib_close(close=True):
920 def set_matplotlib_close(close=True):
836 """Set whether the inline backend closes all figures automatically or not.
921 """Set whether the inline backend closes all figures automatically or not.
837
922
838 By default, the inline backend used in the IPython Notebook will close all
923 By default, the inline backend used in the IPython Notebook will close all
839 matplotlib figures automatically after each cell is run. This means that
924 matplotlib figures automatically after each cell is run. This means that
840 plots in different cells won't interfere. Sometimes, you may want to make
925 plots in different cells won't interfere. Sometimes, you may want to make
841 a plot in one cell and then refine it in later cells. This can be accomplished
926 a plot in one cell and then refine it in later cells. This can be accomplished
842 by::
927 by::
843
928
844 In [1]: set_matplotlib_close(False)
929 In [1]: set_matplotlib_close(False)
845
930
846 To set this in your config files use the following::
931 To set this in your config files use the following::
847
932
848 c.InlineBackend.close_figures = False
933 c.InlineBackend.close_figures = False
849
934
850 Parameters
935 Parameters
851 ----------
936 ----------
852 close : bool
937 close : bool
853 Should all matplotlib figures be automatically closed after each cell is
938 Should all matplotlib figures be automatically closed after each cell is
854 run?
939 run?
855 """
940 """
856 from IPython.kernel.zmq.pylab.config import InlineBackend
941 from IPython.kernel.zmq.pylab.config import InlineBackend
857 cfg = InlineBackend.instance()
942 cfg = InlineBackend.instance()
858 cfg.close_figures = close
943 cfg.close_figures = close
859
944
General Comments 0
You need to be logged in to leave comments. Login now