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