##// END OF EJS Templates
Defer import of xml.dom.minidom
Thomas Kluyver -
Show More
@@ -1,558 +1,557 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) 2008-2011 The IPython Development Team
10 # Copyright (C) 2008-2011 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 from xml.dom import minidom
23
24 from .displaypub import (
22 from .displaypub import (
25 publish_pretty, publish_html,
23 publish_pretty, publish_html,
26 publish_latex, publish_svg,
24 publish_latex, publish_svg,
27 publish_png, publish_json,
25 publish_png, publish_json,
28 publish_javascript, publish_jpeg
26 publish_javascript, publish_jpeg
29 )
27 )
30
28
31 from IPython.utils.py3compat import string_types
29 from IPython.utils.py3compat import string_types
32
30
33 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
34 # Main functions
32 # Main functions
35 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
36
34
37 def display(*objs, **kwargs):
35 def display(*objs, **kwargs):
38 """Display a Python object in all frontends.
36 """Display a Python object in all frontends.
39
37
40 By default all representations will be computed and sent to the frontends.
38 By default all representations will be computed and sent to the frontends.
41 Frontends can decide which representation is used and how.
39 Frontends can decide which representation is used and how.
42
40
43 Parameters
41 Parameters
44 ----------
42 ----------
45 objs : tuple of objects
43 objs : tuple of objects
46 The Python objects to display.
44 The Python objects to display.
47 include : list or tuple, optional
45 include : list or tuple, optional
48 A list of format type strings (MIME types) to include in the
46 A list of format type strings (MIME types) to include in the
49 format data dict. If this is set *only* the format types included
47 format data dict. If this is set *only* the format types included
50 in this list will be computed.
48 in this list will be computed.
51 exclude : list or tuple, optional
49 exclude : list or tuple, optional
52 A list of format type string (MIME types) to exclue in the format
50 A list of format type string (MIME types) to exclue in the format
53 data dict. If this is set all format types will be computed,
51 data dict. If this is set all format types will be computed,
54 except for those included in this argument.
52 except for those included in this argument.
55 """
53 """
56 include = kwargs.get('include')
54 include = kwargs.get('include')
57 exclude = kwargs.get('exclude')
55 exclude = kwargs.get('exclude')
58
56
59 from IPython.core.interactiveshell import InteractiveShell
57 from IPython.core.interactiveshell import InteractiveShell
60 inst = InteractiveShell.instance()
58 inst = InteractiveShell.instance()
61 format = inst.display_formatter.format
59 format = inst.display_formatter.format
62 publish = inst.display_pub.publish
60 publish = inst.display_pub.publish
63
61
64 for obj in objs:
62 for obj in objs:
65 format_dict = format(obj, include=include, exclude=exclude)
63 format_dict = format(obj, include=include, exclude=exclude)
66 publish('IPython.core.display.display', format_dict)
64 publish('IPython.core.display.display', format_dict)
67
65
68
66
69 def display_pretty(*objs, **kwargs):
67 def display_pretty(*objs, **kwargs):
70 """Display the pretty (default) representation of an object.
68 """Display the pretty (default) representation of an object.
71
69
72 Parameters
70 Parameters
73 ----------
71 ----------
74 objs : tuple of objects
72 objs : tuple of objects
75 The Python objects to display, or if raw=True raw text data to
73 The Python objects to display, or if raw=True raw text data to
76 display.
74 display.
77 raw : bool
75 raw : bool
78 Are the data objects raw data or Python objects that need to be
76 Are the data objects raw data or Python objects that need to be
79 formatted before display? [default: False]
77 formatted before display? [default: False]
80 """
78 """
81 raw = kwargs.pop('raw',False)
79 raw = kwargs.pop('raw',False)
82 if raw:
80 if raw:
83 for obj in objs:
81 for obj in objs:
84 publish_pretty(obj)
82 publish_pretty(obj)
85 else:
83 else:
86 display(*objs, include=['text/plain'])
84 display(*objs, include=['text/plain'])
87
85
88
86
89 def display_html(*objs, **kwargs):
87 def display_html(*objs, **kwargs):
90 """Display the HTML representation of an object.
88 """Display the HTML representation of an object.
91
89
92 Parameters
90 Parameters
93 ----------
91 ----------
94 objs : tuple of objects
92 objs : tuple of objects
95 The Python objects to display, or if raw=True raw HTML data to
93 The Python objects to display, or if raw=True raw HTML data to
96 display.
94 display.
97 raw : bool
95 raw : bool
98 Are the data objects raw data or Python objects that need to be
96 Are the data objects raw data or Python objects that need to be
99 formatted before display? [default: False]
97 formatted before display? [default: False]
100 """
98 """
101 raw = kwargs.pop('raw',False)
99 raw = kwargs.pop('raw',False)
102 if raw:
100 if raw:
103 for obj in objs:
101 for obj in objs:
104 publish_html(obj)
102 publish_html(obj)
105 else:
103 else:
106 display(*objs, include=['text/plain','text/html'])
104 display(*objs, include=['text/plain','text/html'])
107
105
108
106
109 def display_svg(*objs, **kwargs):
107 def display_svg(*objs, **kwargs):
110 """Display the SVG representation of an object.
108 """Display the SVG representation of an object.
111
109
112 Parameters
110 Parameters
113 ----------
111 ----------
114 objs : tuple of objects
112 objs : tuple of objects
115 The Python objects to display, or if raw=True raw svg data to
113 The Python objects to display, or if raw=True raw svg data to
116 display.
114 display.
117 raw : bool
115 raw : bool
118 Are the data objects raw data or Python objects that need to be
116 Are the data objects raw data or Python objects that need to be
119 formatted before display? [default: False]
117 formatted before display? [default: False]
120 """
118 """
121 raw = kwargs.pop('raw',False)
119 raw = kwargs.pop('raw',False)
122 if raw:
120 if raw:
123 for obj in objs:
121 for obj in objs:
124 publish_svg(obj)
122 publish_svg(obj)
125 else:
123 else:
126 display(*objs, include=['text/plain','image/svg+xml'])
124 display(*objs, include=['text/plain','image/svg+xml'])
127
125
128
126
129 def display_png(*objs, **kwargs):
127 def display_png(*objs, **kwargs):
130 """Display the PNG representation of an object.
128 """Display the PNG representation of an object.
131
129
132 Parameters
130 Parameters
133 ----------
131 ----------
134 objs : tuple of objects
132 objs : tuple of objects
135 The Python objects to display, or if raw=True raw png data to
133 The Python objects to display, or if raw=True raw png data to
136 display.
134 display.
137 raw : bool
135 raw : bool
138 Are the data objects raw data or Python objects that need to be
136 Are the data objects raw data or Python objects that need to be
139 formatted before display? [default: False]
137 formatted before display? [default: False]
140 """
138 """
141 raw = kwargs.pop('raw',False)
139 raw = kwargs.pop('raw',False)
142 if raw:
140 if raw:
143 for obj in objs:
141 for obj in objs:
144 publish_png(obj)
142 publish_png(obj)
145 else:
143 else:
146 display(*objs, include=['text/plain','image/png'])
144 display(*objs, include=['text/plain','image/png'])
147
145
148
146
149 def display_jpeg(*objs, **kwargs):
147 def display_jpeg(*objs, **kwargs):
150 """Display the JPEG representation of an object.
148 """Display the JPEG representation of an object.
151
149
152 Parameters
150 Parameters
153 ----------
151 ----------
154 objs : tuple of objects
152 objs : tuple of objects
155 The Python objects to display, or if raw=True raw JPEG data to
153 The Python objects to display, or if raw=True raw JPEG data to
156 display.
154 display.
157 raw : bool
155 raw : bool
158 Are the data objects raw data or Python objects that need to be
156 Are the data objects raw data or Python objects that need to be
159 formatted before display? [default: False]
157 formatted before display? [default: False]
160 """
158 """
161 raw = kwargs.pop('raw',False)
159 raw = kwargs.pop('raw',False)
162 if raw:
160 if raw:
163 for obj in objs:
161 for obj in objs:
164 publish_jpeg(obj)
162 publish_jpeg(obj)
165 else:
163 else:
166 display(*objs, include=['text/plain','image/jpeg'])
164 display(*objs, include=['text/plain','image/jpeg'])
167
165
168
166
169 def display_latex(*objs, **kwargs):
167 def display_latex(*objs, **kwargs):
170 """Display the LaTeX representation of an object.
168 """Display the LaTeX representation of an object.
171
169
172 Parameters
170 Parameters
173 ----------
171 ----------
174 objs : tuple of objects
172 objs : tuple of objects
175 The Python objects to display, or if raw=True raw latex data to
173 The Python objects to display, or if raw=True raw latex data to
176 display.
174 display.
177 raw : bool
175 raw : bool
178 Are the data objects raw data or Python objects that need to be
176 Are the data objects raw data or Python objects that need to be
179 formatted before display? [default: False]
177 formatted before display? [default: False]
180 """
178 """
181 raw = kwargs.pop('raw',False)
179 raw = kwargs.pop('raw',False)
182 if raw:
180 if raw:
183 for obj in objs:
181 for obj in objs:
184 publish_latex(obj)
182 publish_latex(obj)
185 else:
183 else:
186 display(*objs, include=['text/plain','text/latex'])
184 display(*objs, include=['text/plain','text/latex'])
187
185
188
186
189 def display_json(*objs, **kwargs):
187 def display_json(*objs, **kwargs):
190 """Display the JSON representation of an object.
188 """Display the JSON representation of an object.
191
189
192 Note that not many frontends support displaying JSON.
190 Note that not many frontends support displaying JSON.
193
191
194 Parameters
192 Parameters
195 ----------
193 ----------
196 objs : tuple of objects
194 objs : tuple of objects
197 The Python objects to display, or if raw=True raw json data to
195 The Python objects to display, or if raw=True raw json data to
198 display.
196 display.
199 raw : bool
197 raw : bool
200 Are the data objects raw data or Python objects that need to be
198 Are the data objects raw data or Python objects that need to be
201 formatted before display? [default: False]
199 formatted before display? [default: False]
202 """
200 """
203 raw = kwargs.pop('raw',False)
201 raw = kwargs.pop('raw',False)
204 if raw:
202 if raw:
205 for obj in objs:
203 for obj in objs:
206 publish_json(obj)
204 publish_json(obj)
207 else:
205 else:
208 display(*objs, include=['text/plain','application/json'])
206 display(*objs, include=['text/plain','application/json'])
209
207
210
208
211 def display_javascript(*objs, **kwargs):
209 def display_javascript(*objs, **kwargs):
212 """Display the Javascript representation of an object.
210 """Display the Javascript representation of an object.
213
211
214 Parameters
212 Parameters
215 ----------
213 ----------
216 objs : tuple of objects
214 objs : tuple of objects
217 The Python objects to display, or if raw=True raw javascript data to
215 The Python objects to display, or if raw=True raw javascript data to
218 display.
216 display.
219 raw : bool
217 raw : bool
220 Are the data objects raw data or Python objects that need to be
218 Are the data objects raw data or Python objects that need to be
221 formatted before display? [default: False]
219 formatted before display? [default: False]
222 """
220 """
223 raw = kwargs.pop('raw',False)
221 raw = kwargs.pop('raw',False)
224 if raw:
222 if raw:
225 for obj in objs:
223 for obj in objs:
226 publish_javascript(obj)
224 publish_javascript(obj)
227 else:
225 else:
228 display(*objs, include=['text/plain','application/javascript'])
226 display(*objs, include=['text/plain','application/javascript'])
229
227
230 #-----------------------------------------------------------------------------
228 #-----------------------------------------------------------------------------
231 # Smart classes
229 # Smart classes
232 #-----------------------------------------------------------------------------
230 #-----------------------------------------------------------------------------
233
231
234
232
235 class DisplayObject(object):
233 class DisplayObject(object):
236 """An object that wraps data to be displayed."""
234 """An object that wraps data to be displayed."""
237
235
238 _read_flags = 'r'
236 _read_flags = 'r'
239
237
240 def __init__(self, data=None, url=None, filename=None):
238 def __init__(self, data=None, url=None, filename=None):
241 """Create a display object given raw data.
239 """Create a display object given raw data.
242
240
243 When this object is returned by an expression or passed to the
241 When this object is returned by an expression or passed to the
244 display function, it will result in the data being displayed
242 display function, it will result in the data being displayed
245 in the frontend. The MIME type of the data should match the
243 in the frontend. The MIME type of the data should match the
246 subclasses used, so the Png subclass should be used for 'image/png'
244 subclasses used, so the Png subclass should be used for 'image/png'
247 data. If the data is a URL, the data will first be downloaded
245 data. If the data is a URL, the data will first be downloaded
248 and then displayed. If
246 and then displayed. If
249
247
250 Parameters
248 Parameters
251 ----------
249 ----------
252 data : unicode, str or bytes
250 data : unicode, str or bytes
253 The raw data or a URL to download the data from.
251 The raw data or a URL to download the data from.
254 url : unicode
252 url : unicode
255 A URL to download the data from.
253 A URL to download the data from.
256 filename : unicode
254 filename : unicode
257 Path to a local file to load the data from.
255 Path to a local file to load the data from.
258 """
256 """
259 if data is not None and isinstance(data, string_types) and data.startswith('http'):
257 if data is not None and isinstance(data, string_types) and data.startswith('http'):
260 self.url = data
258 self.url = data
261 self.filename = None
259 self.filename = None
262 self.data = None
260 self.data = None
263 else:
261 else:
264 self.data = data
262 self.data = data
265 self.url = url
263 self.url = url
266 self.filename = None if filename is None else unicode(filename)
264 self.filename = None if filename is None else unicode(filename)
267 self.reload()
265 self.reload()
268
266
269 def reload(self):
267 def reload(self):
270 """Reload the raw data from file or URL."""
268 """Reload the raw data from file or URL."""
271 if self.filename is not None:
269 if self.filename is not None:
272 with open(self.filename, self._read_flags) as f:
270 with open(self.filename, self._read_flags) as f:
273 self.data = f.read()
271 self.data = f.read()
274 elif self.url is not None:
272 elif self.url is not None:
275 try:
273 try:
276 import urllib2
274 import urllib2
277 response = urllib2.urlopen(self.url)
275 response = urllib2.urlopen(self.url)
278 self.data = response.read()
276 self.data = response.read()
279 # extract encoding from header, if there is one:
277 # extract encoding from header, if there is one:
280 encoding = None
278 encoding = None
281 for sub in response.headers['content-type'].split(';'):
279 for sub in response.headers['content-type'].split(';'):
282 sub = sub.strip()
280 sub = sub.strip()
283 if sub.startswith('charset'):
281 if sub.startswith('charset'):
284 encoding = sub.split('=')[-1].strip()
282 encoding = sub.split('=')[-1].strip()
285 break
283 break
286 # decode data, if an encoding was specified
284 # decode data, if an encoding was specified
287 if encoding:
285 if encoding:
288 self.data = self.data.decode(encoding, 'replace')
286 self.data = self.data.decode(encoding, 'replace')
289 except:
287 except:
290 self.data = None
288 self.data = None
291
289
292 class Pretty(DisplayObject):
290 class Pretty(DisplayObject):
293
291
294 def _repr_pretty_(self):
292 def _repr_pretty_(self):
295 return self.data
293 return self.data
296
294
297
295
298 class HTML(DisplayObject):
296 class HTML(DisplayObject):
299
297
300 def _repr_html_(self):
298 def _repr_html_(self):
301 return self.data
299 return self.data
302
300
303
301
304 class Math(DisplayObject):
302 class Math(DisplayObject):
305
303
306 def _repr_latex_(self):
304 def _repr_latex_(self):
307 s = self.data.strip('$')
305 s = self.data.strip('$')
308 return "$$%s$$" % s
306 return "$$%s$$" % s
309
307
310
308
311 class Latex(DisplayObject):
309 class Latex(DisplayObject):
312
310
313 def _repr_latex_(self):
311 def _repr_latex_(self):
314 return self.data
312 return self.data
315
313
316
314
317 class SVG(DisplayObject):
315 class SVG(DisplayObject):
318
316
319 # wrap data in a property, which extracts the <svg> tag, discarding
317 # wrap data in a property, which extracts the <svg> tag, discarding
320 # document headers
318 # document headers
321 _data = None
319 _data = None
322
320
323 @property
321 @property
324 def data(self):
322 def data(self):
325 return self._data
323 return self._data
326
324
327 @data.setter
325 @data.setter
328 def data(self, svg):
326 def data(self, svg):
329 if svg is None:
327 if svg is None:
330 self._data = None
328 self._data = None
331 return
329 return
332 # parse into dom object
330 # parse into dom object
331 from xml.dom import minidom
333 x = minidom.parseString(svg)
332 x = minidom.parseString(svg)
334 # get svg tag (should be 1)
333 # get svg tag (should be 1)
335 found_svg = x.getElementsByTagName('svg')
334 found_svg = x.getElementsByTagName('svg')
336 if found_svg:
335 if found_svg:
337 svg = found_svg[0].toxml()
336 svg = found_svg[0].toxml()
338 else:
337 else:
339 # fallback on the input, trust the user
338 # fallback on the input, trust the user
340 # but this is probably an error.
339 # but this is probably an error.
341 pass
340 pass
342 self._data = svg
341 self._data = svg
343
342
344 def _repr_svg_(self):
343 def _repr_svg_(self):
345 return self.data
344 return self.data
346
345
347
346
348 class JSON(DisplayObject):
347 class JSON(DisplayObject):
349
348
350 def _repr_json_(self):
349 def _repr_json_(self):
351 return self.data
350 return self.data
352
351
353 css_t = """$("head").append($("<link/>").attr({
352 css_t = """$("head").append($("<link/>").attr({
354 rel: "stylesheet",
353 rel: "stylesheet",
355 type: "text/css",
354 type: "text/css",
356 href: "%s"
355 href: "%s"
357 }));
356 }));
358 """
357 """
359
358
360 lib_t1 = """$.getScript("%s", function () {
359 lib_t1 = """$.getScript("%s", function () {
361 """
360 """
362 lib_t2 = """});
361 lib_t2 = """});
363 """
362 """
364
363
365 class Javascript(DisplayObject):
364 class Javascript(DisplayObject):
366
365
367 def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
366 def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
368 """Create a Javascript display object given raw data.
367 """Create a Javascript display object given raw data.
369
368
370 When this object is returned by an expression or passed to the
369 When this object is returned by an expression or passed to the
371 display function, it will result in the data being displayed
370 display function, it will result in the data being displayed
372 in the frontend. If the data is a URL, the data will first be
371 in the frontend. If the data is a URL, the data will first be
373 downloaded and then displayed.
372 downloaded and then displayed.
374
373
375 In the Notebook, the containing element will be available as `element`,
374 In the Notebook, the containing element will be available as `element`,
376 and jQuery will be available. The output area starts hidden, so if
375 and jQuery will be available. The output area starts hidden, so if
377 the js appends content to `element` that should be visible, then
376 the js appends content to `element` that should be visible, then
378 it must call `container.show()` to unhide the area.
377 it must call `container.show()` to unhide the area.
379
378
380 Parameters
379 Parameters
381 ----------
380 ----------
382 data : unicode, str or bytes
381 data : unicode, str or bytes
383 The Javascript source code or a URL to download it from.
382 The Javascript source code or a URL to download it from.
384 url : unicode
383 url : unicode
385 A URL to download the data from.
384 A URL to download the data from.
386 filename : unicode
385 filename : unicode
387 Path to a local file to load the data from.
386 Path to a local file to load the data from.
388 lib : list or str
387 lib : list or str
389 A sequence of Javascript library URLs to load asynchronously before
388 A sequence of Javascript library URLs to load asynchronously before
390 running the source code. The full URLs of the libraries should
389 running the source code. The full URLs of the libraries should
391 be given. A single Javascript library URL can also be given as a
390 be given. A single Javascript library URL can also be given as a
392 string.
391 string.
393 css: : list or str
392 css: : list or str
394 A sequence of css files to load before running the source code.
393 A sequence of css files to load before running the source code.
395 The full URLs of the css files should be give. A single css URL
394 The full URLs of the css files should be give. A single css URL
396 can also be given as a string.
395 can also be given as a string.
397 """
396 """
398 if isinstance(lib, basestring):
397 if isinstance(lib, basestring):
399 lib = [lib]
398 lib = [lib]
400 elif lib is None:
399 elif lib is None:
401 lib = []
400 lib = []
402 if isinstance(css, basestring):
401 if isinstance(css, basestring):
403 css = [css]
402 css = [css]
404 elif css is None:
403 elif css is None:
405 css = []
404 css = []
406 if not isinstance(lib, (list,tuple)):
405 if not isinstance(lib, (list,tuple)):
407 raise TypeError('expected sequence, got: %r' % lib)
406 raise TypeError('expected sequence, got: %r' % lib)
408 if not isinstance(css, (list,tuple)):
407 if not isinstance(css, (list,tuple)):
409 raise TypeError('expected sequence, got: %r' % css)
408 raise TypeError('expected sequence, got: %r' % css)
410 self.lib = lib
409 self.lib = lib
411 self.css = css
410 self.css = css
412 super(Javascript, self).__init__(data=data, url=url, filename=filename)
411 super(Javascript, self).__init__(data=data, url=url, filename=filename)
413
412
414 def _repr_javascript_(self):
413 def _repr_javascript_(self):
415 r = ''
414 r = ''
416 for c in self.css:
415 for c in self.css:
417 r += css_t % c
416 r += css_t % c
418 for l in self.lib:
417 for l in self.lib:
419 r += lib_t1 % l
418 r += lib_t1 % l
420 r += self.data
419 r += self.data
421 r += lib_t2*len(self.lib)
420 r += lib_t2*len(self.lib)
422 return r
421 return r
423
422
424
423
425 class Image(DisplayObject):
424 class Image(DisplayObject):
426
425
427 _read_flags = 'rb'
426 _read_flags = 'rb'
428 _FMT_JPEG = u'jpeg'
427 _FMT_JPEG = u'jpeg'
429 _FMT_PNG = u'png'
428 _FMT_PNG = u'png'
430 _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG]
429 _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG]
431
430
432 def __init__(self, data=None, url=None, filename=None, format=u'png', embed=None, width=None, height=None):
431 def __init__(self, data=None, url=None, filename=None, format=u'png', embed=None, width=None, height=None):
433 """Create a display an PNG/JPEG image given raw data.
432 """Create a display an PNG/JPEG image given raw data.
434
433
435 When this object is returned by an expression or passed to the
434 When this object is returned by an expression or passed to the
436 display function, it will result in the image being displayed
435 display function, it will result in the image being displayed
437 in the frontend.
436 in the frontend.
438
437
439 Parameters
438 Parameters
440 ----------
439 ----------
441 data : unicode, str or bytes
440 data : unicode, str or bytes
442 The raw data or a URL to download the data from.
441 The raw data or a URL to download the data from.
443 url : unicode
442 url : unicode
444 A URL to download the data from.
443 A URL to download the data from.
445 filename : unicode
444 filename : unicode
446 Path to a local file to load the data from.
445 Path to a local file to load the data from.
447 format : unicode
446 format : unicode
448 The format of the image data (png/jpeg/jpg). If a filename or URL is given
447 The format of the image data (png/jpeg/jpg). If a filename or URL is given
449 for format will be inferred from the filename extension.
448 for format will be inferred from the filename extension.
450 embed : bool
449 embed : bool
451 Should the image data be embedded using a data URI (True) or be
450 Should the image data be embedded using a data URI (True) or be
452 loaded using an <img> tag. Set this to True if you want the image
451 loaded using an <img> tag. Set this to True if you want the image
453 to be viewable later with no internet connection in the notebook.
452 to be viewable later with no internet connection in the notebook.
454
453
455 Default is `True`, unless the keyword argument `url` is set, then
454 Default is `True`, unless the keyword argument `url` is set, then
456 default value is `False`.
455 default value is `False`.
457
456
458 Note that QtConsole is not able to display images if `embed` is set to `False`
457 Note that QtConsole is not able to display images if `embed` is set to `False`
459 width : int
458 width : int
460 Width to which to constrain the image in html
459 Width to which to constrain the image in html
461 height : int
460 height : int
462 Height to which to constrain the image in html
461 Height to which to constrain the image in html
463
462
464 Examples
463 Examples
465 --------
464 --------
466 # embed implicitly True, works in qtconsole and notebook
465 # embed implicitly True, works in qtconsole and notebook
467 Image('http://www.google.fr/images/srpr/logo3w.png')
466 Image('http://www.google.fr/images/srpr/logo3w.png')
468
467
469 # embed implicitly False, does not works in qtconsole but works in notebook if
468 # embed implicitly False, does not works in qtconsole but works in notebook if
470 # internet connection available
469 # internet connection available
471 Image(url='http://www.google.fr/images/srpr/logo3w.png')
470 Image(url='http://www.google.fr/images/srpr/logo3w.png')
472
471
473 """
472 """
474 if filename is not None:
473 if filename is not None:
475 ext = self._find_ext(filename)
474 ext = self._find_ext(filename)
476 elif url is not None:
475 elif url is not None:
477 ext = self._find_ext(url)
476 ext = self._find_ext(url)
478 elif data is None:
477 elif data is None:
479 raise ValueError("No image data found. Expecting filename, url, or data.")
478 raise ValueError("No image data found. Expecting filename, url, or data.")
480 elif isinstance(data, string_types) and data.startswith('http'):
479 elif isinstance(data, string_types) and data.startswith('http'):
481 ext = self._find_ext(data)
480 ext = self._find_ext(data)
482 else:
481 else:
483 ext = None
482 ext = None
484
483
485 if ext is not None:
484 if ext is not None:
486 format = ext.lower()
485 format = ext.lower()
487 if ext == u'jpg' or ext == u'jpeg':
486 if ext == u'jpg' or ext == u'jpeg':
488 format = self._FMT_JPEG
487 format = self._FMT_JPEG
489 if ext == u'png':
488 if ext == u'png':
490 format = self._FMT_PNG
489 format = self._FMT_PNG
491
490
492 self.format = unicode(format).lower()
491 self.format = unicode(format).lower()
493 self.embed = embed if embed is not None else (url is None)
492 self.embed = embed if embed is not None else (url is None)
494
493
495 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
494 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
496 raise ValueError("Cannot embed the '%s' image format" % (self.format))
495 raise ValueError("Cannot embed the '%s' image format" % (self.format))
497 self.width = width
496 self.width = width
498 self.height = height
497 self.height = height
499 super(Image, self).__init__(data=data, url=url, filename=filename)
498 super(Image, self).__init__(data=data, url=url, filename=filename)
500
499
501 def reload(self):
500 def reload(self):
502 """Reload the raw data from file or URL."""
501 """Reload the raw data from file or URL."""
503 if self.embed:
502 if self.embed:
504 super(Image,self).reload()
503 super(Image,self).reload()
505
504
506 def _repr_html_(self):
505 def _repr_html_(self):
507 if not self.embed:
506 if not self.embed:
508 width = height = ''
507 width = height = ''
509 if self.width:
508 if self.width:
510 width = ' width="%d"' % self.width
509 width = ' width="%d"' % self.width
511 if self.height:
510 if self.height:
512 height = ' height="%d"' % self.height
511 height = ' height="%d"' % self.height
513 return u'<img src="%s"%s%s/>' % (self.url, width, height)
512 return u'<img src="%s"%s%s/>' % (self.url, width, height)
514
513
515 def _repr_png_(self):
514 def _repr_png_(self):
516 if self.embed and self.format == u'png':
515 if self.embed and self.format == u'png':
517 return self.data
516 return self.data
518
517
519 def _repr_jpeg_(self):
518 def _repr_jpeg_(self):
520 if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
519 if self.embed and (self.format == u'jpeg' or self.format == u'jpg'):
521 return self.data
520 return self.data
522
521
523 def _find_ext(self, s):
522 def _find_ext(self, s):
524 return unicode(s.split('.')[-1].lower())
523 return unicode(s.split('.')[-1].lower())
525
524
526
525
527 def clear_output(stdout=True, stderr=True, other=True):
526 def clear_output(stdout=True, stderr=True, other=True):
528 """Clear the output of the current cell receiving output.
527 """Clear the output of the current cell receiving output.
529
528
530 Optionally, each of stdout/stderr or other non-stream data (e.g. anything
529 Optionally, each of stdout/stderr or other non-stream data (e.g. anything
531 produced by display()) can be excluded from the clear event.
530 produced by display()) can be excluded from the clear event.
532
531
533 By default, everything is cleared.
532 By default, everything is cleared.
534
533
535 Parameters
534 Parameters
536 ----------
535 ----------
537 stdout : bool [default: True]
536 stdout : bool [default: True]
538 Whether to clear stdout.
537 Whether to clear stdout.
539 stderr : bool [default: True]
538 stderr : bool [default: True]
540 Whether to clear stderr.
539 Whether to clear stderr.
541 other : bool [default: True]
540 other : bool [default: True]
542 Whether to clear everything else that is not stdout/stderr
541 Whether to clear everything else that is not stdout/stderr
543 (e.g. figures,images,HTML, any result of display()).
542 (e.g. figures,images,HTML, any result of display()).
544 """
543 """
545 from IPython.core.interactiveshell import InteractiveShell
544 from IPython.core.interactiveshell import InteractiveShell
546 if InteractiveShell.initialized():
545 if InteractiveShell.initialized():
547 InteractiveShell.instance().display_pub.clear_output(
546 InteractiveShell.instance().display_pub.clear_output(
548 stdout=stdout, stderr=stderr, other=other,
547 stdout=stdout, stderr=stderr, other=other,
549 )
548 )
550 else:
549 else:
551 from IPython.utils import io
550 from IPython.utils import io
552 if stdout:
551 if stdout:
553 print('\033[2K\r', file=io.stdout, end='')
552 print('\033[2K\r', file=io.stdout, end='')
554 io.stdout.flush()
553 io.stdout.flush()
555 if stderr:
554 if stderr:
556 print('\033[2K\r', file=io.stderr, end='')
555 print('\033[2K\r', file=io.stderr, end='')
557 io.stderr.flush()
556 io.stderr.flush()
558
557
General Comments 0
You need to be logged in to leave comments. Login now