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