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