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