Show More
@@ -1,274 +1,373 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Top-level display functions for displaying object in different formats. |
|
2 | """Top-level display functions for displaying object in different formats. | |
3 |
|
3 | |||
4 | Authors: |
|
4 | Authors: | |
5 |
|
5 | |||
6 | * Brian Granger |
|
6 | * Brian Granger | |
7 | """ |
|
7 | """ | |
8 |
|
8 | |||
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 | # Copyright (C) 2008-2010 The IPython Development Team |
|
10 | # Copyright (C) 2008-2010 The IPython Development Team | |
11 | # |
|
11 | # | |
12 | # Distributed under the terms of the BSD License. The full license is in |
|
12 | # Distributed under the terms of the BSD License. The full license is in | |
13 | # the file COPYING, distributed as part of this software. |
|
13 | # the file COPYING, distributed as part of this software. | |
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 |
|
15 | |||
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 | # Imports |
|
17 | # Imports | |
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 |
|
19 | |||
20 | from .displaypub import ( |
|
20 | from .displaypub import ( | |
21 | publish_pretty, publish_html, |
|
21 | publish_pretty, publish_html, | |
22 | publish_latex, publish_svg, |
|
22 | publish_latex, publish_svg, | |
23 | publish_png, publish_json, |
|
23 | publish_png, publish_json, | |
24 | publish_javascript |
|
24 | publish_javascript, publish_jpeg | |
25 | ) |
|
25 | ) | |
26 |
|
26 | |||
27 | #----------------------------------------------------------------------------- |
|
27 | #----------------------------------------------------------------------------- | |
28 | # Main functions |
|
28 | # Main functions | |
29 | #----------------------------------------------------------------------------- |
|
29 | #----------------------------------------------------------------------------- | |
30 |
|
30 | |||
31 | def display(*objs, **kwargs): |
|
31 | def display(*objs, **kwargs): | |
32 | """Display a Python object in all frontends. |
|
32 | """Display a Python object in all frontends. | |
33 |
|
33 | |||
34 | By default all representations will be computed and sent to the frontends. |
|
34 | By default all representations will be computed and sent to the frontends. | |
35 | Frontends can decide which representation is used and how. |
|
35 | Frontends can decide which representation is used and how. | |
36 |
|
36 | |||
37 | Parameters |
|
37 | Parameters | |
38 | ---------- |
|
38 | ---------- | |
39 | objs : tuple of objects |
|
39 | objs : tuple of objects | |
40 | The Python objects to display. |
|
40 | The Python objects to display. | |
41 | include : list or tuple, optional |
|
41 | include : list or tuple, optional | |
42 | A list of format type strings (MIME types) to include in the |
|
42 | A list of format type strings (MIME types) to include in the | |
43 | format data dict. If this is set *only* the format types included |
|
43 | format data dict. If this is set *only* the format types included | |
44 | in this list will be computed. |
|
44 | in this list will be computed. | |
45 | exclude : list or tuple, optional |
|
45 | exclude : list or tuple, optional | |
46 | A list of format type string (MIME types) to exclue in the format |
|
46 | A list of format type string (MIME types) to exclue in the format | |
47 | data dict. If this is set all format types will be computed, |
|
47 | data dict. If this is set all format types will be computed, | |
48 | except for those included in this argument. |
|
48 | except for those included in this argument. | |
49 | """ |
|
49 | """ | |
50 | include = kwargs.get('include') |
|
50 | include = kwargs.get('include') | |
51 | exclude = kwargs.get('exclude') |
|
51 | exclude = kwargs.get('exclude') | |
52 |
|
52 | |||
53 | from IPython.core.interactiveshell import InteractiveShell |
|
53 | from IPython.core.interactiveshell import InteractiveShell | |
54 | inst = InteractiveShell.instance() |
|
54 | inst = InteractiveShell.instance() | |
55 | format = inst.display_formatter.format |
|
55 | format = inst.display_formatter.format | |
56 | publish = inst.display_pub.publish |
|
56 | publish = inst.display_pub.publish | |
57 |
|
57 | |||
58 | for obj in objs: |
|
58 | for obj in objs: | |
59 | format_dict = format(obj, include=include, exclude=exclude) |
|
59 | format_dict = format(obj, include=include, exclude=exclude) | |
60 | publish('IPython.core.display.display', format_dict) |
|
60 | publish('IPython.core.display.display', format_dict) | |
61 |
|
61 | |||
62 |
|
62 | |||
63 | def display_pretty(*objs, **kwargs): |
|
63 | def display_pretty(*objs, **kwargs): | |
64 | """Display the pretty (default) representation of an object. |
|
64 | """Display the pretty (default) representation of an object. | |
65 |
|
65 | |||
66 | Parameters |
|
66 | Parameters | |
67 | ---------- |
|
67 | ---------- | |
68 | objs : tuple of objects |
|
68 | objs : tuple of objects | |
69 | The Python objects to display, or if raw=True raw text data to |
|
69 | The Python objects to display, or if raw=True raw text data to | |
70 | display. |
|
70 | display. | |
71 | raw : bool |
|
71 | raw : bool | |
72 | Are the data objects raw data or Python objects that need to be |
|
72 | Are the data objects raw data or Python objects that need to be | |
73 | formatted before display? [default: False] |
|
73 | formatted before display? [default: False] | |
74 | """ |
|
74 | """ | |
75 | raw = kwargs.pop('raw',False) |
|
75 | raw = kwargs.pop('raw',False) | |
76 | if raw: |
|
76 | if raw: | |
77 | for obj in objs: |
|
77 | for obj in objs: | |
78 | publish_pretty(obj) |
|
78 | publish_pretty(obj) | |
79 | else: |
|
79 | else: | |
80 | display(*objs, include=['text/plain']) |
|
80 | display(*objs, include=['text/plain']) | |
81 |
|
81 | |||
82 |
|
82 | |||
83 | def display_html(*objs, **kwargs): |
|
83 | def display_html(*objs, **kwargs): | |
84 | """Display the HTML representation of an object. |
|
84 | """Display the HTML representation of an object. | |
85 |
|
85 | |||
86 | Parameters |
|
86 | Parameters | |
87 | ---------- |
|
87 | ---------- | |
88 | objs : tuple of objects |
|
88 | objs : tuple of objects | |
89 |
The Python objects to display, or if raw=True raw |
|
89 | The Python objects to display, or if raw=True raw HTML data to | |
90 | display. |
|
90 | display. | |
91 | raw : bool |
|
91 | raw : bool | |
92 | Are the data objects raw data or Python objects that need to be |
|
92 | Are the data objects raw data or Python objects that need to be | |
93 | formatted before display? [default: False] |
|
93 | formatted before display? [default: False] | |
94 | """ |
|
94 | """ | |
95 | raw = kwargs.pop('raw',False) |
|
95 | raw = kwargs.pop('raw',False) | |
96 | if raw: |
|
96 | if raw: | |
97 | for obj in objs: |
|
97 | for obj in objs: | |
98 | publish_html(obj) |
|
98 | publish_html(obj) | |
99 | else: |
|
99 | else: | |
100 | display(*objs, include=['text/plain','text/html']) |
|
100 | display(*objs, include=['text/plain','text/html']) | |
101 |
|
101 | |||
102 |
|
102 | |||
103 | def display_svg(*objs, **kwargs): |
|
103 | def display_svg(*objs, **kwargs): | |
104 | """Display the SVG representation of an object. |
|
104 | """Display the SVG representation of an object. | |
105 |
|
105 | |||
106 | Parameters |
|
106 | Parameters | |
107 | ---------- |
|
107 | ---------- | |
108 | objs : tuple of objects |
|
108 | objs : tuple of objects | |
109 | The Python objects to display, or if raw=True raw svg data to |
|
109 | The Python objects to display, or if raw=True raw svg data to | |
110 | display. |
|
110 | display. | |
111 | raw : bool |
|
111 | raw : bool | |
112 | Are the data objects raw data or Python objects that need to be |
|
112 | Are the data objects raw data or Python objects that need to be | |
113 | formatted before display? [default: False] |
|
113 | formatted before display? [default: False] | |
114 | """ |
|
114 | """ | |
115 | raw = kwargs.pop('raw',False) |
|
115 | raw = kwargs.pop('raw',False) | |
116 | if raw: |
|
116 | if raw: | |
117 | for obj in objs: |
|
117 | for obj in objs: | |
118 | publish_svg(obj) |
|
118 | publish_svg(obj) | |
119 | else: |
|
119 | else: | |
120 | display(*objs, include=['text/plain','image/svg+xml']) |
|
120 | display(*objs, include=['text/plain','image/svg+xml']) | |
121 |
|
121 | |||
122 |
|
122 | |||
123 | def display_png(*objs, **kwargs): |
|
123 | def display_png(*objs, **kwargs): | |
124 | """Display the PNG representation of an object. |
|
124 | """Display the PNG representation of an object. | |
125 |
|
125 | |||
126 | Parameters |
|
126 | Parameters | |
127 | ---------- |
|
127 | ---------- | |
128 | objs : tuple of objects |
|
128 | objs : tuple of objects | |
129 | The Python objects to display, or if raw=True raw png data to |
|
129 | The Python objects to display, or if raw=True raw png data to | |
130 | display. |
|
130 | display. | |
131 | raw : bool |
|
131 | raw : bool | |
132 | Are the data objects raw data or Python objects that need to be |
|
132 | Are the data objects raw data or Python objects that need to be | |
133 | formatted before display? [default: False] |
|
133 | formatted before display? [default: False] | |
134 | """ |
|
134 | """ | |
135 | raw = kwargs.pop('raw',False) |
|
135 | raw = kwargs.pop('raw',False) | |
136 | if raw: |
|
136 | if raw: | |
137 | for obj in objs: |
|
137 | for obj in objs: | |
138 | publish_png(obj) |
|
138 | publish_png(obj) | |
139 | else: |
|
139 | else: | |
140 | display(*objs, include=['text/plain','image/png']) |
|
140 | display(*objs, include=['text/plain','image/png']) | |
141 |
|
141 | |||
142 |
|
142 | |||
|
143 | def display_jpeg(*objs, **kwargs): | |||
|
144 | """Display the JPEG representation of an object. | |||
|
145 | ||||
|
146 | Parameters | |||
|
147 | ---------- | |||
|
148 | objs : tuple of objects | |||
|
149 | The Python objects to display, or if raw=True raw JPEG data to | |||
|
150 | display. | |||
|
151 | raw : bool | |||
|
152 | Are the data objects raw data or Python objects that need to be | |||
|
153 | formatted before display? [default: False] | |||
|
154 | """ | |||
|
155 | raw = kwargs.pop('raw',False) | |||
|
156 | if raw: | |||
|
157 | for obj in objs: | |||
|
158 | publish_png(obj) | |||
|
159 | else: | |||
|
160 | display(*objs, include=['text/plain','image/jpeg']) | |||
|
161 | ||||
|
162 | ||||
143 | def display_latex(*objs, **kwargs): |
|
163 | def display_latex(*objs, **kwargs): | |
144 | """Display the LaTeX representation of an object. |
|
164 | """Display the LaTeX representation of an object. | |
145 |
|
165 | |||
146 | Parameters |
|
166 | Parameters | |
147 | ---------- |
|
167 | ---------- | |
148 | objs : tuple of objects |
|
168 | objs : tuple of objects | |
149 | The Python objects to display, or if raw=True raw latex data to |
|
169 | The Python objects to display, or if raw=True raw latex data to | |
150 | display. |
|
170 | display. | |
151 | raw : bool |
|
171 | raw : bool | |
152 | Are the data objects raw data or Python objects that need to be |
|
172 | Are the data objects raw data or Python objects that need to be | |
153 | formatted before display? [default: False] |
|
173 | formatted before display? [default: False] | |
154 | """ |
|
174 | """ | |
155 | raw = kwargs.pop('raw',False) |
|
175 | raw = kwargs.pop('raw',False) | |
156 | if raw: |
|
176 | if raw: | |
157 | for obj in objs: |
|
177 | for obj in objs: | |
158 | publish_latex(obj) |
|
178 | publish_latex(obj) | |
159 | else: |
|
179 | else: | |
160 | display(*objs, include=['text/plain','text/latex']) |
|
180 | display(*objs, include=['text/plain','text/latex']) | |
161 |
|
181 | |||
162 |
|
182 | |||
163 | def display_json(*objs, **kwargs): |
|
183 | def display_json(*objs, **kwargs): | |
164 | """Display the JSON representation of an object. |
|
184 | """Display the JSON representation of an object. | |
165 |
|
185 | |||
166 | Parameters |
|
186 | Parameters | |
167 | ---------- |
|
187 | ---------- | |
168 | objs : tuple of objects |
|
188 | objs : tuple of objects | |
169 | The Python objects to display, or if raw=True raw json data to |
|
189 | The Python objects to display, or if raw=True raw json data to | |
170 | display. |
|
190 | display. | |
171 | raw : bool |
|
191 | raw : bool | |
172 | Are the data objects raw data or Python objects that need to be |
|
192 | Are the data objects raw data or Python objects that need to be | |
173 | formatted before display? [default: False] |
|
193 | formatted before display? [default: False] | |
174 | """ |
|
194 | """ | |
175 | raw = kwargs.pop('raw',False) |
|
195 | raw = kwargs.pop('raw',False) | |
176 | if raw: |
|
196 | if raw: | |
177 | for obj in objs: |
|
197 | for obj in objs: | |
178 | publish_json(obj) |
|
198 | publish_json(obj) | |
179 | else: |
|
199 | else: | |
180 | display(*objs, include=['text/plain','application/json']) |
|
200 | display(*objs, include=['text/plain','application/json']) | |
181 |
|
201 | |||
182 |
|
202 | |||
183 | def display_javascript(*objs, **kwargs): |
|
203 | def display_javascript(*objs, **kwargs): | |
184 | """Display the Javascript representation of an object. |
|
204 | """Display the Javascript representation of an object. | |
185 |
|
205 | |||
186 | Parameters |
|
206 | Parameters | |
187 | ---------- |
|
207 | ---------- | |
188 | objs : tuple of objects |
|
208 | objs : tuple of objects | |
189 | The Python objects to display, or if raw=True raw javascript data to |
|
209 | The Python objects to display, or if raw=True raw javascript data to | |
190 | display. |
|
210 | display. | |
191 | raw : bool |
|
211 | raw : bool | |
192 | Are the data objects raw data or Python objects that need to be |
|
212 | Are the data objects raw data or Python objects that need to be | |
193 | formatted before display? [default: False] |
|
213 | formatted before display? [default: False] | |
194 | """ |
|
214 | """ | |
195 | raw = kwargs.pop('raw',False) |
|
215 | raw = kwargs.pop('raw',False) | |
196 | if raw: |
|
216 | if raw: | |
197 | for obj in objs: |
|
217 | for obj in objs: | |
198 | publish_javascript(obj) |
|
218 | publish_javascript(obj) | |
199 | else: |
|
219 | else: | |
200 | display(*objs, include=['text/plain','application/javascript']) |
|
220 | display(*objs, include=['text/plain','application/javascript']) | |
201 |
|
221 | |||
202 | #----------------------------------------------------------------------------- |
|
222 | #----------------------------------------------------------------------------- | |
203 | # Smart classes |
|
223 | # Smart classes | |
204 | #----------------------------------------------------------------------------- |
|
224 | #----------------------------------------------------------------------------- | |
205 |
|
225 | |||
206 |
|
226 | |||
207 | class DisplayObject(object): |
|
227 | class DisplayObject(object): | |
208 | """An object that wraps data to be displayed.""" |
|
228 | """An object that wraps data to be displayed.""" | |
209 |
|
229 | |||
210 | def __init__(self, data): |
|
230 | _read_flags = 'r' | |
211 | """Create a display object given raw data of a MIME type or a URL. |
|
231 | ||
|
232 | def __init__(self, data=None, url=None, filename=None): | |||
|
233 | """Create a display object given raw data. | |||
212 |
|
234 | |||
213 | When this object is returned by an expression or passed to the |
|
235 | When this object is returned by an expression or passed to the | |
214 | display function, it will result in the data being displayed |
|
236 | display function, it will result in the data being displayed | |
215 | in the frontend. The MIME type of the data should match the |
|
237 | in the frontend. The MIME type of the data should match the | |
216 | subclasses used, so the Png subclass should be used for 'image/png' |
|
238 | subclasses used, so the Png subclass should be used for 'image/png' | |
217 | data. If the data is a URL, the data will first be downloaded |
|
239 | data. If the data is a URL, the data will first be downloaded | |
218 | and then displayed. |
|
240 | and then displayed. If | |
219 |
|
241 | |||
220 | Parameters |
|
242 | Parameters | |
221 | ---------- |
|
243 | ---------- | |
222 | data : unicode, str or bytes |
|
244 | data : unicode, str or bytes | |
223 | The raw data or a URL to download the data from. |
|
245 | The raw data or a URL to download the data from. | |
|
246 | url : unicode | |||
|
247 | A URL to download the data from. | |||
|
248 | filename : unicode | |||
|
249 | Path to a local file to load the data from. | |||
224 | """ |
|
250 | """ | |
225 | if data.startswith('http'): |
|
251 | if data is not None and data.startswith('http'): | |
226 | import urllib2 |
|
252 | self.url = data | |
227 | response = urllib2.urlopen(data) |
|
253 | self.filename = None | |
228 |
self.data = |
|
254 | self.data = None | |
229 | else: |
|
255 | else: | |
230 | self.data = data |
|
256 | self.data = data | |
231 |
|
257 | self.url = url | ||
|
258 | self.filename = None if filename is None else unicode(filename) | |||
|
259 | self.reload() | |||
|
260 | ||||
|
261 | def reload(self): | |||
|
262 | """Reload the raw data from file or URL.""" | |||
|
263 | if self.filename is not None: | |||
|
264 | with open(self.filename, self._read_flags) as f: | |||
|
265 | self.data = f.read() | |||
|
266 | elif self.url is not None: | |||
|
267 | try: | |||
|
268 | import urllib2 | |||
|
269 | response = urllib2.urlopen(self.url) | |||
|
270 | self.data = response.read() | |||
|
271 | except: | |||
|
272 | self.data = None | |||
232 |
|
273 | |||
233 | class Pretty(DisplayObject): |
|
274 | class Pretty(DisplayObject): | |
234 |
|
275 | |||
235 | def _repr_pretty_(self): |
|
276 | def _repr_pretty_(self): | |
236 | return self.data |
|
277 | return self.data | |
237 |
|
278 | |||
238 |
|
279 | |||
239 |
class H |
|
280 | class HTML(DisplayObject): | |
240 |
|
281 | |||
241 | def _repr_html_(self): |
|
282 | def _repr_html_(self): | |
242 | return self.data |
|
283 | return self.data | |
243 |
|
284 | |||
244 |
|
285 | |||
245 |
class |
|
286 | class Math(DisplayObject): | |
246 |
|
287 | |||
247 | def _repr_latex_(self): |
|
288 | def _repr_latex_(self): | |
248 | return self.data |
|
289 | return self.data | |
249 |
|
290 | |||
250 |
|
291 | |||
251 |
class |
|
292 | class SVG(DisplayObject): | |
252 |
|
293 | |||
253 |
def _repr_ |
|
294 | def _repr_svg_(self): | |
254 | return self.data |
|
295 | return self.data | |
255 |
|
296 | |||
256 |
|
297 | |||
257 |
class |
|
298 | class JSON(DisplayObject): | |
258 |
|
299 | |||
259 |
def _repr_ |
|
300 | def _repr_json_(self): | |
260 | return self.data |
|
301 | return self.data | |
261 |
|
302 | |||
262 |
|
303 | |||
263 |
class J |
|
304 | class Javascript(DisplayObject): | |
264 |
|
305 | |||
265 |
def _repr_j |
|
306 | def _repr_javascript_(self): | |
266 | return self.data |
|
307 | return self.data | |
267 |
|
308 | |||
268 |
|
309 | |||
269 |
class |
|
310 | class Image(DisplayObject): | |
270 |
|
311 | |||
271 | def _repr_javascript_(self): |
|
312 | _read_flags = 'rb' | |
|
313 | ||||
|
314 | def __init__(self, data=None, url=None, filename=None, format=u'png', embed=False): | |||
|
315 | """Create a display an PNG/JPEG image given raw data. | |||
|
316 | ||||
|
317 | When this object is returned by an expression or passed to the | |||
|
318 | display function, it will result in the image being displayed | |||
|
319 | in the frontend. | |||
|
320 | ||||
|
321 | Parameters | |||
|
322 | ---------- | |||
|
323 | data : unicode, str or bytes | |||
|
324 | The raw data or a URL to download the data from. | |||
|
325 | url : unicode | |||
|
326 | A URL to download the data from. | |||
|
327 | filename : unicode | |||
|
328 | Path to a local file to load the data from. | |||
|
329 | format : unicode | |||
|
330 | The format of the image data (png/jpeg/jpg). If a filename or URL is given | |||
|
331 | for format will be inferred from the filename extension. | |||
|
332 | embed : bool | |||
|
333 | Should the image data be embedded in the notebook using a data URI (True) | |||
|
334 | or be loaded using an <img> tag. Set this to True if you want the image | |||
|
335 | to be viewable later with no internet connection. If a filename is given | |||
|
336 | embed is always set to True. | |||
|
337 | """ | |||
|
338 | if filename is not None: | |||
|
339 | ext = self._find_ext(filename) | |||
|
340 | elif url is not None: | |||
|
341 | ext = self._find_ext(url) | |||
|
342 | elif data.startswith('http'): | |||
|
343 | ext = self._find_ext(data) | |||
|
344 | else: | |||
|
345 | ext = None | |||
|
346 | if ext is not None: | |||
|
347 | if ext == u'jpg' or ext == u'jpeg': | |||
|
348 | format = u'jpeg' | |||
|
349 | if ext == u'png': | |||
|
350 | format = u'png' | |||
|
351 | self.format = unicode(format).lower() | |||
|
352 | self.embed = True if filename is not None else embed | |||
|
353 | super(Image, self).__init__(data=data, url=url, filename=filename) | |||
|
354 | ||||
|
355 | def reload(self): | |||
|
356 | """Reload the raw data from file or URL.""" | |||
|
357 | if self.embed: | |||
|
358 | super(Image,self).reload() | |||
|
359 | ||||
|
360 | def _repr_html_(self): | |||
|
361 | if not self.embed: | |||
|
362 | return u'<img src="%s" />' % self.url | |||
|
363 | ||||
|
364 | def _repr_png_(self): | |||
|
365 | if self.embed and self.format == u'png': | |||
272 | return self.data |
|
366 | return self.data | |
273 |
|
367 | |||
|
368 | def _repr_jpeg_(self): | |||
|
369 | if self.embed and (self.format == u'jpeg' or self.format == u'jpg'): | |||
|
370 | return self.data | |||
274 |
|
371 | |||
|
372 | def _find_ext(self, s): | |||
|
373 | return unicode(s.split('.')[-1].lower()) |
@@ -1,276 +1,298 b'' | |||||
1 | """An interface for publishing rich data to frontends. |
|
1 | """An interface for publishing rich data to frontends. | |
2 |
|
2 | |||
3 | There are two components of the display system: |
|
3 | There are two components of the display system: | |
4 |
|
4 | |||
5 | * Display formatters, which take a Python object and compute the |
|
5 | * Display formatters, which take a Python object and compute the | |
6 | representation of the object in various formats (text, HTML, SVg, etc.). |
|
6 | representation of the object in various formats (text, HTML, SVg, etc.). | |
7 | * The display publisher that is used to send the representation data to the |
|
7 | * The display publisher that is used to send the representation data to the | |
8 | various frontends. |
|
8 | various frontends. | |
9 |
|
9 | |||
10 | This module defines the logic display publishing. The display publisher uses |
|
10 | This module defines the logic display publishing. The display publisher uses | |
11 | the ``display_data`` message type that is defined in the IPython messaging |
|
11 | the ``display_data`` message type that is defined in the IPython messaging | |
12 | spec. |
|
12 | spec. | |
13 |
|
13 | |||
14 | Authors: |
|
14 | Authors: | |
15 |
|
15 | |||
16 | * Brian Granger |
|
16 | * Brian Granger | |
17 | """ |
|
17 | """ | |
18 |
|
18 | |||
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 | # Copyright (C) 2008-2010 The IPython Development Team |
|
20 | # Copyright (C) 2008-2010 The IPython Development Team | |
21 | # |
|
21 | # | |
22 | # Distributed under the terms of the BSD License. The full license is in |
|
22 | # Distributed under the terms of the BSD License. The full license is in | |
23 | # the file COPYING, distributed as part of this software. |
|
23 | # the file COPYING, distributed as part of this software. | |
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 |
|
25 | |||
26 | #----------------------------------------------------------------------------- |
|
26 | #----------------------------------------------------------------------------- | |
27 | # Imports |
|
27 | # Imports | |
28 | #----------------------------------------------------------------------------- |
|
28 | #----------------------------------------------------------------------------- | |
29 |
|
29 | |||
30 | from __future__ import print_function |
|
30 | from __future__ import print_function | |
31 |
|
31 | |||
32 | from IPython.config.configurable import Configurable |
|
32 | from IPython.config.configurable import Configurable | |
33 |
|
33 | |||
34 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
35 | # Main payload class |
|
35 | # Main payload class | |
36 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
37 |
|
37 | |||
38 | class DisplayPublisher(Configurable): |
|
38 | class DisplayPublisher(Configurable): | |
39 | """A traited class that publishes display data to frontends. |
|
39 | """A traited class that publishes display data to frontends. | |
40 |
|
40 | |||
41 | Instances of this class are created by the main IPython object and should |
|
41 | Instances of this class are created by the main IPython object and should | |
42 | be accessed there. |
|
42 | be accessed there. | |
43 | """ |
|
43 | """ | |
44 |
|
44 | |||
45 | def _validate_data(self, source, data, metadata=None): |
|
45 | def _validate_data(self, source, data, metadata=None): | |
46 | """Validate the display data. |
|
46 | """Validate the display data. | |
47 |
|
47 | |||
48 | Parameters |
|
48 | Parameters | |
49 | ---------- |
|
49 | ---------- | |
50 | source : str |
|
50 | source : str | |
51 | The fully dotted name of the callable that created the data, like |
|
51 | The fully dotted name of the callable that created the data, like | |
52 | :func:`foo.bar.my_formatter`. |
|
52 | :func:`foo.bar.my_formatter`. | |
53 | data : dict |
|
53 | data : dict | |
54 | The formata data dictionary. |
|
54 | The formata data dictionary. | |
55 | metadata : dict |
|
55 | metadata : dict | |
56 | Any metadata for the data. |
|
56 | Any metadata for the data. | |
57 | """ |
|
57 | """ | |
58 |
|
58 | |||
59 | if not isinstance(source, (str,unicode)): |
|
59 | if not isinstance(source, (str,unicode)): | |
60 | raise TypeError('source must be a str, got: %r' % source) |
|
60 | raise TypeError('source must be a str, got: %r' % source) | |
61 | if not isinstance(data, dict): |
|
61 | if not isinstance(data, dict): | |
62 | raise TypeError('data must be a dict, got: %r' % data) |
|
62 | raise TypeError('data must be a dict, got: %r' % data) | |
63 | if metadata is not None: |
|
63 | if metadata is not None: | |
64 | if not isinstance(metadata, dict): |
|
64 | if not isinstance(metadata, dict): | |
65 | raise TypeError('metadata must be a dict, got: %r' % data) |
|
65 | raise TypeError('metadata must be a dict, got: %r' % data) | |
66 |
|
66 | |||
67 | def publish(self, source, data, metadata=None): |
|
67 | def publish(self, source, data, metadata=None): | |
68 | """Publish data and metadata to all frontends. |
|
68 | """Publish data and metadata to all frontends. | |
69 |
|
69 | |||
70 | See the ``display_data`` message in the messaging documentation for |
|
70 | See the ``display_data`` message in the messaging documentation for | |
71 | more details about this message type. |
|
71 | more details about this message type. | |
72 |
|
72 | |||
73 | The following MIME types are currently implemented: |
|
73 | The following MIME types are currently implemented: | |
74 |
|
74 | |||
75 | * text/plain |
|
75 | * text/plain | |
76 | * text/html |
|
76 | * text/html | |
77 | * text/latex |
|
77 | * text/latex | |
78 | * application/json |
|
78 | * application/json | |
79 | * application/javascript |
|
79 | * application/javascript | |
80 | * image/png |
|
80 | * image/png | |
|
81 | * image/jpeg | |||
81 | * image/svg+xml |
|
82 | * image/svg+xml | |
82 |
|
83 | |||
83 | Parameters |
|
84 | Parameters | |
84 | ---------- |
|
85 | ---------- | |
85 | source : str |
|
86 | source : str | |
86 | A string that give the function or method that created the data, |
|
87 | A string that give the function or method that created the data, | |
87 | such as 'IPython.core.page'. |
|
88 | such as 'IPython.core.page'. | |
88 | data : dict |
|
89 | data : dict | |
89 | A dictionary having keys that are valid MIME types (like |
|
90 | A dictionary having keys that are valid MIME types (like | |
90 | 'text/plain' or 'image/svg+xml') and values that are the data for |
|
91 | 'text/plain' or 'image/svg+xml') and values that are the data for | |
91 | that MIME type. The data itself must be a JSON'able data |
|
92 | that MIME type. The data itself must be a JSON'able data | |
92 | structure. Minimally all data should have the 'text/plain' data, |
|
93 | structure. Minimally all data should have the 'text/plain' data, | |
93 | which can be displayed by all frontends. If more than the plain |
|
94 | which can be displayed by all frontends. If more than the plain | |
94 | text is given, it is up to the frontend to decide which |
|
95 | text is given, it is up to the frontend to decide which | |
95 | representation to use. |
|
96 | representation to use. | |
96 | metadata : dict |
|
97 | metadata : dict | |
97 | A dictionary for metadata related to the data. This can contain |
|
98 | A dictionary for metadata related to the data. This can contain | |
98 | arbitrary key, value pairs that frontends can use to interpret |
|
99 | arbitrary key, value pairs that frontends can use to interpret | |
99 | the data. |
|
100 | the data. | |
100 | """ |
|
101 | """ | |
101 | from IPython.utils import io |
|
102 | from IPython.utils import io | |
102 | # The default is to simply write the plain text data using io.stdout. |
|
103 | # The default is to simply write the plain text data using io.stdout. | |
103 | if data.has_key('text/plain'): |
|
104 | if data.has_key('text/plain'): | |
104 | print(data['text/plain'], file=io.stdout) |
|
105 | print(data['text/plain'], file=io.stdout) | |
105 |
|
106 | |||
106 |
|
107 | |||
107 | def publish_display_data(source, data, metadata=None): |
|
108 | def publish_display_data(source, data, metadata=None): | |
108 | """Publish data and metadata to all frontends. |
|
109 | """Publish data and metadata to all frontends. | |
109 |
|
110 | |||
110 | See the ``display_data`` message in the messaging documentation for |
|
111 | See the ``display_data`` message in the messaging documentation for | |
111 | more details about this message type. |
|
112 | more details about this message type. | |
112 |
|
113 | |||
113 | The following MIME types are currently implemented: |
|
114 | The following MIME types are currently implemented: | |
114 |
|
115 | |||
115 | * text/plain |
|
116 | * text/plain | |
116 | * text/html |
|
117 | * text/html | |
117 | * text/latex |
|
118 | * text/latex | |
118 | * application/json |
|
119 | * application/json | |
119 | * application/javascript |
|
120 | * application/javascript | |
120 | * image/png |
|
121 | * image/png | |
|
122 | * image/jpeg | |||
121 | * image/svg+xml |
|
123 | * image/svg+xml | |
122 |
|
124 | |||
123 | Parameters |
|
125 | Parameters | |
124 | ---------- |
|
126 | ---------- | |
125 | source : str |
|
127 | source : str | |
126 | A string that give the function or method that created the data, |
|
128 | A string that give the function or method that created the data, | |
127 | such as 'IPython.core.page'. |
|
129 | such as 'IPython.core.page'. | |
128 | data : dict |
|
130 | data : dict | |
129 | A dictionary having keys that are valid MIME types (like |
|
131 | A dictionary having keys that are valid MIME types (like | |
130 | 'text/plain' or 'image/svg+xml') and values that are the data for |
|
132 | 'text/plain' or 'image/svg+xml') and values that are the data for | |
131 | that MIME type. The data itself must be a JSON'able data |
|
133 | that MIME type. The data itself must be a JSON'able data | |
132 | structure. Minimally all data should have the 'text/plain' data, |
|
134 | structure. Minimally all data should have the 'text/plain' data, | |
133 | which can be displayed by all frontends. If more than the plain |
|
135 | which can be displayed by all frontends. If more than the plain | |
134 | text is given, it is up to the frontend to decide which |
|
136 | text is given, it is up to the frontend to decide which | |
135 | representation to use. |
|
137 | representation to use. | |
136 | metadata : dict |
|
138 | metadata : dict | |
137 | A dictionary for metadata related to the data. This can contain |
|
139 | A dictionary for metadata related to the data. This can contain | |
138 | arbitrary key, value pairs that frontends can use to interpret |
|
140 | arbitrary key, value pairs that frontends can use to interpret | |
139 | the data. |
|
141 | the data. | |
140 | """ |
|
142 | """ | |
141 | from IPython.core.interactiveshell import InteractiveShell |
|
143 | from IPython.core.interactiveshell import InteractiveShell | |
142 | InteractiveShell.instance().display_pub.publish( |
|
144 | InteractiveShell.instance().display_pub.publish( | |
143 | source, |
|
145 | source, | |
144 | data, |
|
146 | data, | |
145 | metadata |
|
147 | metadata | |
146 | ) |
|
148 | ) | |
147 |
|
149 | |||
148 |
|
150 | |||
149 | def publish_pretty(data, metadata=None): |
|
151 | def publish_pretty(data, metadata=None): | |
150 | """Publish raw text data to all frontends. |
|
152 | """Publish raw text data to all frontends. | |
151 |
|
153 | |||
152 | Parameters |
|
154 | Parameters | |
153 | ---------- |
|
155 | ---------- | |
154 | data : unicode |
|
156 | data : unicode | |
155 | The raw text data to publish. |
|
157 | The raw text data to publish. | |
156 | metadata : dict |
|
158 | metadata : dict | |
157 | A dictionary for metadata related to the data. This can contain |
|
159 | A dictionary for metadata related to the data. This can contain | |
158 | arbitrary key, value pairs that frontends can use to interpret |
|
160 | arbitrary key, value pairs that frontends can use to interpret | |
159 | the data. |
|
161 | the data. | |
160 | """ |
|
162 | """ | |
161 | publish_display_data( |
|
163 | publish_display_data( | |
162 | u'IPython.core.displaypub.publish_pretty', |
|
164 | u'IPython.core.displaypub.publish_pretty', | |
163 | {'text/plain':data}, |
|
165 | {'text/plain':data}, | |
164 | metadata=metadata |
|
166 | metadata=metadata | |
165 | ) |
|
167 | ) | |
166 |
|
168 | |||
167 |
|
169 | |||
168 | def publish_html(data, metadata=None): |
|
170 | def publish_html(data, metadata=None): | |
169 |
"""Publish raw |
|
171 | """Publish raw HTML data to all frontends. | |
170 |
|
172 | |||
171 | Parameters |
|
173 | Parameters | |
172 | ---------- |
|
174 | ---------- | |
173 | data : unicode |
|
175 | data : unicode | |
174 |
The raw |
|
176 | The raw HTML data to publish. | |
175 | metadata : dict |
|
177 | metadata : dict | |
176 | A dictionary for metadata related to the data. This can contain |
|
178 | A dictionary for metadata related to the data. This can contain | |
177 | arbitrary key, value pairs that frontends can use to interpret |
|
179 | arbitrary key, value pairs that frontends can use to interpret | |
178 | the data. |
|
180 | the data. | |
179 | """ |
|
181 | """ | |
180 | publish_display_data( |
|
182 | publish_display_data( | |
181 | u'IPython.core.displaypub.publish_html', |
|
183 | u'IPython.core.displaypub.publish_html', | |
182 | {'text/html':data}, |
|
184 | {'text/html':data}, | |
183 | metadata=metadata |
|
185 | metadata=metadata | |
184 | ) |
|
186 | ) | |
185 |
|
187 | |||
186 |
|
188 | |||
187 | def publish_latex(data, metadata=None): |
|
189 | def publish_latex(data, metadata=None): | |
188 |
"""Publish raw |
|
190 | """Publish raw LaTeX data to all frontends. | |
189 |
|
191 | |||
190 | Parameters |
|
192 | Parameters | |
191 | ---------- |
|
193 | ---------- | |
192 | data : unicode |
|
194 | data : unicode | |
193 |
The raw |
|
195 | The raw LaTeX data to publish. | |
194 | metadata : dict |
|
196 | metadata : dict | |
195 | A dictionary for metadata related to the data. This can contain |
|
197 | A dictionary for metadata related to the data. This can contain | |
196 | arbitrary key, value pairs that frontends can use to interpret |
|
198 | arbitrary key, value pairs that frontends can use to interpret | |
197 | the data. |
|
199 | the data. | |
198 | """ |
|
200 | """ | |
199 | publish_display_data( |
|
201 | publish_display_data( | |
200 | u'IPython.core.displaypub.publish_latex', |
|
202 | u'IPython.core.displaypub.publish_latex', | |
201 | {'text/latex':data}, |
|
203 | {'text/latex':data}, | |
202 | metadata=metadata |
|
204 | metadata=metadata | |
203 | ) |
|
205 | ) | |
204 |
|
206 | |||
205 | def publish_png(data, metadata=None): |
|
207 | def publish_png(data, metadata=None): | |
206 |
"""Publish raw binary |
|
208 | """Publish raw binary PNG data to all frontends. | |
207 |
|
209 | |||
208 | Parameters |
|
210 | Parameters | |
209 | ---------- |
|
211 | ---------- | |
210 | data : str/bytes |
|
212 | data : str/bytes | |
211 |
The raw binary |
|
213 | The raw binary PNG data to publish. | |
212 | metadata : dict |
|
214 | metadata : dict | |
213 | A dictionary for metadata related to the data. This can contain |
|
215 | A dictionary for metadata related to the data. This can contain | |
214 | arbitrary key, value pairs that frontends can use to interpret |
|
216 | arbitrary key, value pairs that frontends can use to interpret | |
215 | the data. |
|
217 | the data. | |
216 | """ |
|
218 | """ | |
217 | publish_display_data( |
|
219 | publish_display_data( | |
218 | u'IPython.core.displaypub.publish_png', |
|
220 | u'IPython.core.displaypub.publish_png', | |
219 | {'image/png':data}, |
|
221 | {'image/png':data}, | |
220 | metadata=metadata |
|
222 | metadata=metadata | |
221 | ) |
|
223 | ) | |
222 |
|
224 | |||
|
225 | ||||
|
226 | def publish_jpeg(data, metadata=None): | |||
|
227 | """Publish raw binary JPEG data to all frontends. | |||
|
228 | ||||
|
229 | Parameters | |||
|
230 | ---------- | |||
|
231 | data : str/bytes | |||
|
232 | The raw binary JPEG data to publish. | |||
|
233 | metadata : dict | |||
|
234 | A dictionary for metadata related to the data. This can contain | |||
|
235 | arbitrary key, value pairs that frontends can use to interpret | |||
|
236 | the data. | |||
|
237 | """ | |||
|
238 | publish_display_data( | |||
|
239 | u'IPython.core.displaypub.publish_jpeg', | |||
|
240 | {'image/jpeg':data}, | |||
|
241 | metadata=metadata | |||
|
242 | ) | |||
|
243 | ||||
|
244 | ||||
223 | def publish_svg(data, metadata=None): |
|
245 | def publish_svg(data, metadata=None): | |
224 |
"""Publish raw |
|
246 | """Publish raw SVG data to all frontends. | |
225 |
|
247 | |||
226 | Parameters |
|
248 | Parameters | |
227 | ---------- |
|
249 | ---------- | |
228 | data : unicode |
|
250 | data : unicode | |
229 |
The raw |
|
251 | The raw SVG data to publish. | |
230 | metadata : dict |
|
252 | metadata : dict | |
231 | A dictionary for metadata related to the data. This can contain |
|
253 | A dictionary for metadata related to the data. This can contain | |
232 | arbitrary key, value pairs that frontends can use to interpret |
|
254 | arbitrary key, value pairs that frontends can use to interpret | |
233 | the data. |
|
255 | the data. | |
234 | """ |
|
256 | """ | |
235 | publish_display_data( |
|
257 | publish_display_data( | |
236 | u'IPython.core.displaypub.publish_svg', |
|
258 | u'IPython.core.displaypub.publish_svg', | |
237 | {'image/svg+xml':data}, |
|
259 | {'image/svg+xml':data}, | |
238 | metadata=metadata |
|
260 | metadata=metadata | |
239 | ) |
|
261 | ) | |
240 |
|
262 | |||
241 | def publish_json(data, metadata=None): |
|
263 | def publish_json(data, metadata=None): | |
242 |
"""Publish raw |
|
264 | """Publish raw JSON data to all frontends. | |
243 |
|
265 | |||
244 | Parameters |
|
266 | Parameters | |
245 | ---------- |
|
267 | ---------- | |
246 | data : unicode |
|
268 | data : unicode | |
247 |
The raw |
|
269 | The raw JSON data to publish. | |
248 | metadata : dict |
|
270 | metadata : dict | |
249 | A dictionary for metadata related to the data. This can contain |
|
271 | A dictionary for metadata related to the data. This can contain | |
250 | arbitrary key, value pairs that frontends can use to interpret |
|
272 | arbitrary key, value pairs that frontends can use to interpret | |
251 | the data. |
|
273 | the data. | |
252 | """ |
|
274 | """ | |
253 | publish_display_data( |
|
275 | publish_display_data( | |
254 | u'IPython.core.displaypub.publish_json', |
|
276 | u'IPython.core.displaypub.publish_json', | |
255 | {'application/json':data}, |
|
277 | {'application/json':data}, | |
256 | metadata=metadata |
|
278 | metadata=metadata | |
257 | ) |
|
279 | ) | |
258 |
|
280 | |||
259 | def publish_javascript(data, metadata=None): |
|
281 | def publish_javascript(data, metadata=None): | |
260 |
"""Publish raw |
|
282 | """Publish raw Javascript data to all frontends. | |
261 |
|
283 | |||
262 | Parameters |
|
284 | Parameters | |
263 | ---------- |
|
285 | ---------- | |
264 | data : unicode |
|
286 | data : unicode | |
265 |
The raw |
|
287 | The raw Javascript data to publish. | |
266 | metadata : dict |
|
288 | metadata : dict | |
267 | A dictionary for metadata related to the data. This can contain |
|
289 | A dictionary for metadata related to the data. This can contain | |
268 | arbitrary key, value pairs that frontends can use to interpret |
|
290 | arbitrary key, value pairs that frontends can use to interpret | |
269 | the data. |
|
291 | the data. | |
270 | """ |
|
292 | """ | |
271 | publish_display_data( |
|
293 | publish_display_data( | |
272 | u'IPython.core.displaypub.publish_javascript', |
|
294 | u'IPython.core.displaypub.publish_javascript', | |
273 | {'application/javascript':data}, |
|
295 | {'application/javascript':data}, | |
274 | metadata=metadata |
|
296 | metadata=metadata | |
275 | ) |
|
297 | ) | |
276 |
|
298 |
@@ -1,598 +1,619 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Display formatters. |
|
2 | """Display formatters. | |
3 |
|
3 | |||
4 |
|
4 | |||
5 | Authors: |
|
5 | Authors: | |
6 |
|
6 | |||
7 | * Robert Kern |
|
7 | * Robert Kern | |
8 | * Brian Granger |
|
8 | * Brian Granger | |
9 | """ |
|
9 | """ | |
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Copyright (c) 2010, IPython Development Team. |
|
11 | # Copyright (c) 2010, IPython Development Team. | |
12 | # |
|
12 | # | |
13 | # Distributed under the terms of the Modified BSD License. |
|
13 | # Distributed under the terms of the Modified BSD License. | |
14 | # |
|
14 | # | |
15 | # The full license is in the file COPYING.txt, distributed with this software. |
|
15 | # The full license is in the file COPYING.txt, distributed with this software. | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 | # Imports |
|
19 | # Imports | |
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 |
|
21 | |||
22 | # Stdlib imports |
|
22 | # Stdlib imports | |
23 | import abc |
|
23 | import abc | |
24 | import sys |
|
24 | import sys | |
25 | # We must use StringIO, as cStringIO doesn't handle unicode properly. |
|
25 | # We must use StringIO, as cStringIO doesn't handle unicode properly. | |
26 | from StringIO import StringIO |
|
26 | from StringIO import StringIO | |
27 |
|
27 | |||
28 | # Our own imports |
|
28 | # Our own imports | |
29 | from IPython.config.configurable import Configurable |
|
29 | from IPython.config.configurable import Configurable | |
30 | from IPython.lib import pretty |
|
30 | from IPython.lib import pretty | |
31 | from IPython.utils.traitlets import Bool, Dict, Int, Unicode, CUnicode, ObjectName |
|
31 | from IPython.utils.traitlets import Bool, Dict, Int, Unicode, CUnicode, ObjectName | |
32 |
|
32 | |||
33 |
|
33 | |||
34 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
35 | # The main DisplayFormatter class |
|
35 | # The main DisplayFormatter class | |
36 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
37 |
|
37 | |||
38 |
|
38 | |||
39 | class DisplayFormatter(Configurable): |
|
39 | class DisplayFormatter(Configurable): | |
40 |
|
40 | |||
41 | # When set to true only the default plain text formatter will be used. |
|
41 | # When set to true only the default plain text formatter will be used. | |
42 | plain_text_only = Bool(False, config=True) |
|
42 | plain_text_only = Bool(False, config=True) | |
43 |
|
43 | |||
44 | # A dict of formatter whose keys are format types (MIME types) and whose |
|
44 | # A dict of formatter whose keys are format types (MIME types) and whose | |
45 | # values are subclasses of BaseFormatter. |
|
45 | # values are subclasses of BaseFormatter. | |
46 | formatters = Dict(config=True) |
|
46 | formatters = Dict(config=True) | |
47 | def _formatters_default(self): |
|
47 | def _formatters_default(self): | |
48 | """Activate the default formatters.""" |
|
48 | """Activate the default formatters.""" | |
49 | formatter_classes = [ |
|
49 | formatter_classes = [ | |
50 | PlainTextFormatter, |
|
50 | PlainTextFormatter, | |
51 | HTMLFormatter, |
|
51 | HTMLFormatter, | |
52 | SVGFormatter, |
|
52 | SVGFormatter, | |
53 | PNGFormatter, |
|
53 | PNGFormatter, | |
|
54 | JPEGFormatter, | |||
54 | LatexFormatter, |
|
55 | LatexFormatter, | |
55 | JSONFormatter, |
|
56 | JSONFormatter, | |
56 | JavascriptFormatter |
|
57 | JavascriptFormatter | |
57 | ] |
|
58 | ] | |
58 | d = {} |
|
59 | d = {} | |
59 | for cls in formatter_classes: |
|
60 | for cls in formatter_classes: | |
60 | f = cls(config=self.config) |
|
61 | f = cls(config=self.config) | |
61 | d[f.format_type] = f |
|
62 | d[f.format_type] = f | |
62 | return d |
|
63 | return d | |
63 |
|
64 | |||
64 | def format(self, obj, include=None, exclude=None): |
|
65 | def format(self, obj, include=None, exclude=None): | |
65 | """Return a format data dict for an object. |
|
66 | """Return a format data dict for an object. | |
66 |
|
67 | |||
67 | By default all format types will be computed. |
|
68 | By default all format types will be computed. | |
68 |
|
69 | |||
69 | The following MIME types are currently implemented: |
|
70 | The following MIME types are currently implemented: | |
70 |
|
71 | |||
71 | * text/plain |
|
72 | * text/plain | |
72 | * text/html |
|
73 | * text/html | |
73 | * text/latex |
|
74 | * text/latex | |
74 | * application/json |
|
75 | * application/json | |
75 | * application/javascript |
|
76 | * application/javascript | |
76 | * image/png |
|
77 | * image/png | |
|
78 | * image/jpeg | |||
77 | * image/svg+xml |
|
79 | * image/svg+xml | |
78 |
|
80 | |||
79 | Parameters |
|
81 | Parameters | |
80 | ---------- |
|
82 | ---------- | |
81 | obj : object |
|
83 | obj : object | |
82 | The Python object whose format data will be computed. |
|
84 | The Python object whose format data will be computed. | |
83 | include : list or tuple, optional |
|
85 | include : list or tuple, optional | |
84 | A list of format type strings (MIME types) to include in the |
|
86 | A list of format type strings (MIME types) to include in the | |
85 | format data dict. If this is set *only* the format types included |
|
87 | format data dict. If this is set *only* the format types included | |
86 | in this list will be computed. |
|
88 | in this list will be computed. | |
87 | exclude : list or tuple, optional |
|
89 | exclude : list or tuple, optional | |
88 | A list of format type string (MIME types) to exclue in the format |
|
90 | A list of format type string (MIME types) to exclue in the format | |
89 | data dict. If this is set all format types will be computed, |
|
91 | data dict. If this is set all format types will be computed, | |
90 | except for those included in this argument. |
|
92 | except for those included in this argument. | |
91 |
|
93 | |||
92 | Returns |
|
94 | Returns | |
93 | ------- |
|
95 | ------- | |
94 | format_dict : dict |
|
96 | format_dict : dict | |
95 | A dictionary of key/value pairs, one or each format that was |
|
97 | A dictionary of key/value pairs, one or each format that was | |
96 | generated for the object. The keys are the format types, which |
|
98 | generated for the object. The keys are the format types, which | |
97 | will usually be MIME type strings and the values and JSON'able |
|
99 | will usually be MIME type strings and the values and JSON'able | |
98 | data structure containing the raw data for the representation in |
|
100 | data structure containing the raw data for the representation in | |
99 | that format. |
|
101 | that format. | |
100 | """ |
|
102 | """ | |
101 | format_dict = {} |
|
103 | format_dict = {} | |
102 |
|
104 | |||
103 | # If plain text only is active |
|
105 | # If plain text only is active | |
104 | if self.plain_text_only: |
|
106 | if self.plain_text_only: | |
105 | formatter = self.formatters['text/plain'] |
|
107 | formatter = self.formatters['text/plain'] | |
106 | try: |
|
108 | try: | |
107 | data = formatter(obj) |
|
109 | data = formatter(obj) | |
108 | except: |
|
110 | except: | |
109 | # FIXME: log the exception |
|
111 | # FIXME: log the exception | |
110 | raise |
|
112 | raise | |
111 | if data is not None: |
|
113 | if data is not None: | |
112 | format_dict['text/plain'] = data |
|
114 | format_dict['text/plain'] = data | |
113 | return format_dict |
|
115 | return format_dict | |
114 |
|
116 | |||
115 | for format_type, formatter in self.formatters.items(): |
|
117 | for format_type, formatter in self.formatters.items(): | |
116 | if include is not None: |
|
118 | if include is not None: | |
117 | if format_type not in include: |
|
119 | if format_type not in include: | |
118 | continue |
|
120 | continue | |
119 | if exclude is not None: |
|
121 | if exclude is not None: | |
120 | if format_type in exclude: |
|
122 | if format_type in exclude: | |
121 | continue |
|
123 | continue | |
122 | try: |
|
124 | try: | |
123 | data = formatter(obj) |
|
125 | data = formatter(obj) | |
124 | except: |
|
126 | except: | |
125 | # FIXME: log the exception |
|
127 | # FIXME: log the exception | |
126 | raise |
|
128 | raise | |
127 | if data is not None: |
|
129 | if data is not None: | |
128 | format_dict[format_type] = data |
|
130 | format_dict[format_type] = data | |
129 | return format_dict |
|
131 | return format_dict | |
130 |
|
132 | |||
131 | @property |
|
133 | @property | |
132 | def format_types(self): |
|
134 | def format_types(self): | |
133 | """Return the format types (MIME types) of the active formatters.""" |
|
135 | """Return the format types (MIME types) of the active formatters.""" | |
134 | return self.formatters.keys() |
|
136 | return self.formatters.keys() | |
135 |
|
137 | |||
136 |
|
138 | |||
137 | #----------------------------------------------------------------------------- |
|
139 | #----------------------------------------------------------------------------- | |
138 | # Formatters for specific format types (text, html, svg, etc.) |
|
140 | # Formatters for specific format types (text, html, svg, etc.) | |
139 | #----------------------------------------------------------------------------- |
|
141 | #----------------------------------------------------------------------------- | |
140 |
|
142 | |||
141 |
|
143 | |||
142 | class FormatterABC(object): |
|
144 | class FormatterABC(object): | |
143 | """ Abstract base class for Formatters. |
|
145 | """ Abstract base class for Formatters. | |
144 |
|
146 | |||
145 | A formatter is a callable class that is responsible for computing the |
|
147 | A formatter is a callable class that is responsible for computing the | |
146 | raw format data for a particular format type (MIME type). For example, |
|
148 | raw format data for a particular format type (MIME type). For example, | |
147 | an HTML formatter would have a format type of `text/html` and would return |
|
149 | an HTML formatter would have a format type of `text/html` and would return | |
148 | the HTML representation of the object when called. |
|
150 | the HTML representation of the object when called. | |
149 | """ |
|
151 | """ | |
150 | __metaclass__ = abc.ABCMeta |
|
152 | __metaclass__ = abc.ABCMeta | |
151 |
|
153 | |||
152 | # The format type of the data returned, usually a MIME type. |
|
154 | # The format type of the data returned, usually a MIME type. | |
153 | format_type = 'text/plain' |
|
155 | format_type = 'text/plain' | |
154 |
|
156 | |||
155 | # Is the formatter enabled... |
|
157 | # Is the formatter enabled... | |
156 | enabled = True |
|
158 | enabled = True | |
157 |
|
159 | |||
158 | @abc.abstractmethod |
|
160 | @abc.abstractmethod | |
159 | def __call__(self, obj): |
|
161 | def __call__(self, obj): | |
160 | """Return a JSON'able representation of the object. |
|
162 | """Return a JSON'able representation of the object. | |
161 |
|
163 | |||
162 | If the object cannot be formatted by this formatter, then return None |
|
164 | If the object cannot be formatted by this formatter, then return None | |
163 | """ |
|
165 | """ | |
164 | try: |
|
166 | try: | |
165 | return repr(obj) |
|
167 | return repr(obj) | |
166 | except TypeError: |
|
168 | except TypeError: | |
167 | return None |
|
169 | return None | |
168 |
|
170 | |||
169 |
|
171 | |||
170 | class BaseFormatter(Configurable): |
|
172 | class BaseFormatter(Configurable): | |
171 | """A base formatter class that is configurable. |
|
173 | """A base formatter class that is configurable. | |
172 |
|
174 | |||
173 | This formatter should usually be used as the base class of all formatters. |
|
175 | This formatter should usually be used as the base class of all formatters. | |
174 | It is a traited :class:`Configurable` class and includes an extensible |
|
176 | It is a traited :class:`Configurable` class and includes an extensible | |
175 | API for users to determine how their objects are formatted. The following |
|
177 | API for users to determine how their objects are formatted. The following | |
176 | logic is used to find a function to format an given object. |
|
178 | logic is used to find a function to format an given object. | |
177 |
|
179 | |||
178 | 1. The object is introspected to see if it has a method with the name |
|
180 | 1. The object is introspected to see if it has a method with the name | |
179 | :attr:`print_method`. If is does, that object is passed to that method |
|
181 | :attr:`print_method`. If is does, that object is passed to that method | |
180 | for formatting. |
|
182 | for formatting. | |
181 | 2. If no print method is found, three internal dictionaries are consulted |
|
183 | 2. If no print method is found, three internal dictionaries are consulted | |
182 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` |
|
184 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` | |
183 | and :attr:`deferred_printers`. |
|
185 | and :attr:`deferred_printers`. | |
184 |
|
186 | |||
185 | Users should use these dictionaries to register functions that will be |
|
187 | Users should use these dictionaries to register functions that will be | |
186 | used to compute the format data for their objects (if those objects don't |
|
188 | used to compute the format data for their objects (if those objects don't | |
187 | have the special print methods). The easiest way of using these |
|
189 | have the special print methods). The easiest way of using these | |
188 | dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name` |
|
190 | dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name` | |
189 | methods. |
|
191 | methods. | |
190 |
|
192 | |||
191 | If no function/callable is found to compute the format data, ``None`` is |
|
193 | If no function/callable is found to compute the format data, ``None`` is | |
192 | returned and this format type is not used. |
|
194 | returned and this format type is not used. | |
193 | """ |
|
195 | """ | |
194 |
|
196 | |||
195 | format_type = Unicode('text/plain') |
|
197 | format_type = Unicode('text/plain') | |
196 |
|
198 | |||
197 | enabled = Bool(True, config=True) |
|
199 | enabled = Bool(True, config=True) | |
198 |
|
200 | |||
199 | print_method = ObjectName('__repr__') |
|
201 | print_method = ObjectName('__repr__') | |
200 |
|
202 | |||
201 | # The singleton printers. |
|
203 | # The singleton printers. | |
202 | # Maps the IDs of the builtin singleton objects to the format functions. |
|
204 | # Maps the IDs of the builtin singleton objects to the format functions. | |
203 | singleton_printers = Dict(config=True) |
|
205 | singleton_printers = Dict(config=True) | |
204 | def _singleton_printers_default(self): |
|
206 | def _singleton_printers_default(self): | |
205 | return {} |
|
207 | return {} | |
206 |
|
208 | |||
207 | # The type-specific printers. |
|
209 | # The type-specific printers. | |
208 | # Map type objects to the format functions. |
|
210 | # Map type objects to the format functions. | |
209 | type_printers = Dict(config=True) |
|
211 | type_printers = Dict(config=True) | |
210 | def _type_printers_default(self): |
|
212 | def _type_printers_default(self): | |
211 | return {} |
|
213 | return {} | |
212 |
|
214 | |||
213 | # The deferred-import type-specific printers. |
|
215 | # The deferred-import type-specific printers. | |
214 | # Map (modulename, classname) pairs to the format functions. |
|
216 | # Map (modulename, classname) pairs to the format functions. | |
215 | deferred_printers = Dict(config=True) |
|
217 | deferred_printers = Dict(config=True) | |
216 | def _deferred_printers_default(self): |
|
218 | def _deferred_printers_default(self): | |
217 | return {} |
|
219 | return {} | |
218 |
|
220 | |||
219 | def __call__(self, obj): |
|
221 | def __call__(self, obj): | |
220 | """Compute the format for an object.""" |
|
222 | """Compute the format for an object.""" | |
221 | if self.enabled: |
|
223 | if self.enabled: | |
222 | obj_id = id(obj) |
|
224 | obj_id = id(obj) | |
223 | try: |
|
225 | try: | |
224 | obj_class = getattr(obj, '__class__', None) or type(obj) |
|
226 | obj_class = getattr(obj, '__class__', None) or type(obj) | |
225 | # First try to find registered singleton printers for the type. |
|
227 | # First try to find registered singleton printers for the type. | |
226 | try: |
|
228 | try: | |
227 | printer = self.singleton_printers[obj_id] |
|
229 | printer = self.singleton_printers[obj_id] | |
228 | except (TypeError, KeyError): |
|
230 | except (TypeError, KeyError): | |
229 | pass |
|
231 | pass | |
230 | else: |
|
232 | else: | |
231 | return printer(obj) |
|
233 | return printer(obj) | |
232 | # Next look for type_printers. |
|
234 | # Next look for type_printers. | |
233 | for cls in pretty._get_mro(obj_class): |
|
235 | for cls in pretty._get_mro(obj_class): | |
234 | if cls in self.type_printers: |
|
236 | if cls in self.type_printers: | |
235 | return self.type_printers[cls](obj) |
|
237 | return self.type_printers[cls](obj) | |
236 | else: |
|
238 | else: | |
237 | printer = self._in_deferred_types(cls) |
|
239 | printer = self._in_deferred_types(cls) | |
238 | if printer is not None: |
|
240 | if printer is not None: | |
239 | return printer(obj) |
|
241 | return printer(obj) | |
240 | # Finally look for special method names. |
|
242 | # Finally look for special method names. | |
241 | if hasattr(obj_class, self.print_method): |
|
243 | if hasattr(obj_class, self.print_method): | |
242 | printer = getattr(obj_class, self.print_method) |
|
244 | printer = getattr(obj_class, self.print_method) | |
243 | return printer(obj) |
|
245 | return printer(obj) | |
244 | return None |
|
246 | return None | |
245 | except Exception: |
|
247 | except Exception: | |
246 | pass |
|
248 | pass | |
247 | else: |
|
249 | else: | |
248 | return None |
|
250 | return None | |
249 |
|
251 | |||
250 | def for_type(self, typ, func): |
|
252 | def for_type(self, typ, func): | |
251 | """Add a format function for a given type. |
|
253 | """Add a format function for a given type. | |
252 |
|
254 | |||
253 | Parameters |
|
255 | Parameters | |
254 | ----------- |
|
256 | ----------- | |
255 | typ : class |
|
257 | typ : class | |
256 | The class of the object that will be formatted using `func`. |
|
258 | The class of the object that will be formatted using `func`. | |
257 | func : callable |
|
259 | func : callable | |
258 | The callable that will be called to compute the format data. The |
|
260 | The callable that will be called to compute the format data. The | |
259 | call signature of this function is simple, it must take the |
|
261 | call signature of this function is simple, it must take the | |
260 | object to be formatted and return the raw data for the given |
|
262 | object to be formatted and return the raw data for the given | |
261 | format. Subclasses may use a different call signature for the |
|
263 | format. Subclasses may use a different call signature for the | |
262 | `func` argument. |
|
264 | `func` argument. | |
263 | """ |
|
265 | """ | |
264 | oldfunc = self.type_printers.get(typ, None) |
|
266 | oldfunc = self.type_printers.get(typ, None) | |
265 | if func is not None: |
|
267 | if func is not None: | |
266 | # To support easy restoration of old printers, we need to ignore |
|
268 | # To support easy restoration of old printers, we need to ignore | |
267 | # Nones. |
|
269 | # Nones. | |
268 | self.type_printers[typ] = func |
|
270 | self.type_printers[typ] = func | |
269 | return oldfunc |
|
271 | return oldfunc | |
270 |
|
272 | |||
271 | def for_type_by_name(self, type_module, type_name, func): |
|
273 | def for_type_by_name(self, type_module, type_name, func): | |
272 | """Add a format function for a type specified by the full dotted |
|
274 | """Add a format function for a type specified by the full dotted | |
273 | module and name of the type, rather than the type of the object. |
|
275 | module and name of the type, rather than the type of the object. | |
274 |
|
276 | |||
275 | Parameters |
|
277 | Parameters | |
276 | ---------- |
|
278 | ---------- | |
277 | type_module : str |
|
279 | type_module : str | |
278 | The full dotted name of the module the type is defined in, like |
|
280 | The full dotted name of the module the type is defined in, like | |
279 | ``numpy``. |
|
281 | ``numpy``. | |
280 | type_name : str |
|
282 | type_name : str | |
281 | The name of the type (the class name), like ``dtype`` |
|
283 | The name of the type (the class name), like ``dtype`` | |
282 | func : callable |
|
284 | func : callable | |
283 | The callable that will be called to compute the format data. The |
|
285 | The callable that will be called to compute the format data. The | |
284 | call signature of this function is simple, it must take the |
|
286 | call signature of this function is simple, it must take the | |
285 | object to be formatted and return the raw data for the given |
|
287 | object to be formatted and return the raw data for the given | |
286 | format. Subclasses may use a different call signature for the |
|
288 | format. Subclasses may use a different call signature for the | |
287 | `func` argument. |
|
289 | `func` argument. | |
288 | """ |
|
290 | """ | |
289 | key = (type_module, type_name) |
|
291 | key = (type_module, type_name) | |
290 | oldfunc = self.deferred_printers.get(key, None) |
|
292 | oldfunc = self.deferred_printers.get(key, None) | |
291 | if func is not None: |
|
293 | if func is not None: | |
292 | # To support easy restoration of old printers, we need to ignore |
|
294 | # To support easy restoration of old printers, we need to ignore | |
293 | # Nones. |
|
295 | # Nones. | |
294 | self.deferred_printers[key] = func |
|
296 | self.deferred_printers[key] = func | |
295 | return oldfunc |
|
297 | return oldfunc | |
296 |
|
298 | |||
297 | def _in_deferred_types(self, cls): |
|
299 | def _in_deferred_types(self, cls): | |
298 | """ |
|
300 | """ | |
299 | Check if the given class is specified in the deferred type registry. |
|
301 | Check if the given class is specified in the deferred type registry. | |
300 |
|
302 | |||
301 | Returns the printer from the registry if it exists, and None if the |
|
303 | Returns the printer from the registry if it exists, and None if the | |
302 | class is not in the registry. Successful matches will be moved to the |
|
304 | class is not in the registry. Successful matches will be moved to the | |
303 | regular type registry for future use. |
|
305 | regular type registry for future use. | |
304 | """ |
|
306 | """ | |
305 | mod = getattr(cls, '__module__', None) |
|
307 | mod = getattr(cls, '__module__', None) | |
306 | name = getattr(cls, '__name__', None) |
|
308 | name = getattr(cls, '__name__', None) | |
307 | key = (mod, name) |
|
309 | key = (mod, name) | |
308 | printer = None |
|
310 | printer = None | |
309 | if key in self.deferred_printers: |
|
311 | if key in self.deferred_printers: | |
310 | # Move the printer over to the regular registry. |
|
312 | # Move the printer over to the regular registry. | |
311 | printer = self.deferred_printers.pop(key) |
|
313 | printer = self.deferred_printers.pop(key) | |
312 | self.type_printers[cls] = printer |
|
314 | self.type_printers[cls] = printer | |
313 | return printer |
|
315 | return printer | |
314 |
|
316 | |||
315 |
|
317 | |||
316 | class PlainTextFormatter(BaseFormatter): |
|
318 | class PlainTextFormatter(BaseFormatter): | |
317 | """The default pretty-printer. |
|
319 | """The default pretty-printer. | |
318 |
|
320 | |||
319 | This uses :mod:`IPython.external.pretty` to compute the format data of |
|
321 | This uses :mod:`IPython.external.pretty` to compute the format data of | |
320 | the object. If the object cannot be pretty printed, :func:`repr` is used. |
|
322 | the object. If the object cannot be pretty printed, :func:`repr` is used. | |
321 | See the documentation of :mod:`IPython.external.pretty` for details on |
|
323 | See the documentation of :mod:`IPython.external.pretty` for details on | |
322 | how to write pretty printers. Here is a simple example:: |
|
324 | how to write pretty printers. Here is a simple example:: | |
323 |
|
325 | |||
324 | def dtype_pprinter(obj, p, cycle): |
|
326 | def dtype_pprinter(obj, p, cycle): | |
325 | if cycle: |
|
327 | if cycle: | |
326 | return p.text('dtype(...)') |
|
328 | return p.text('dtype(...)') | |
327 | if hasattr(obj, 'fields'): |
|
329 | if hasattr(obj, 'fields'): | |
328 | if obj.fields is None: |
|
330 | if obj.fields is None: | |
329 | p.text(repr(obj)) |
|
331 | p.text(repr(obj)) | |
330 | else: |
|
332 | else: | |
331 | p.begin_group(7, 'dtype([') |
|
333 | p.begin_group(7, 'dtype([') | |
332 | for i, field in enumerate(obj.descr): |
|
334 | for i, field in enumerate(obj.descr): | |
333 | if i > 0: |
|
335 | if i > 0: | |
334 | p.text(',') |
|
336 | p.text(',') | |
335 | p.breakable() |
|
337 | p.breakable() | |
336 | p.pretty(field) |
|
338 | p.pretty(field) | |
337 | p.end_group(7, '])') |
|
339 | p.end_group(7, '])') | |
338 | """ |
|
340 | """ | |
339 |
|
341 | |||
340 | # The format type of data returned. |
|
342 | # The format type of data returned. | |
341 | format_type = Unicode('text/plain') |
|
343 | format_type = Unicode('text/plain') | |
342 |
|
344 | |||
343 | # This subclass ignores this attribute as it always need to return |
|
345 | # This subclass ignores this attribute as it always need to return | |
344 | # something. |
|
346 | # something. | |
345 | enabled = Bool(True, config=False) |
|
347 | enabled = Bool(True, config=False) | |
346 |
|
348 | |||
347 | # Look for a _repr_pretty_ methods to use for pretty printing. |
|
349 | # Look for a _repr_pretty_ methods to use for pretty printing. | |
348 | print_method = ObjectName('_repr_pretty_') |
|
350 | print_method = ObjectName('_repr_pretty_') | |
349 |
|
351 | |||
350 | # Whether to pretty-print or not. |
|
352 | # Whether to pretty-print or not. | |
351 | pprint = Bool(True, config=True) |
|
353 | pprint = Bool(True, config=True) | |
352 |
|
354 | |||
353 | # Whether to be verbose or not. |
|
355 | # Whether to be verbose or not. | |
354 | verbose = Bool(False, config=True) |
|
356 | verbose = Bool(False, config=True) | |
355 |
|
357 | |||
356 | # The maximum width. |
|
358 | # The maximum width. | |
357 | max_width = Int(79, config=True) |
|
359 | max_width = Int(79, config=True) | |
358 |
|
360 | |||
359 | # The newline character. |
|
361 | # The newline character. | |
360 | newline = Unicode('\n', config=True) |
|
362 | newline = Unicode('\n', config=True) | |
361 |
|
363 | |||
362 | # format-string for pprinting floats |
|
364 | # format-string for pprinting floats | |
363 | float_format = Unicode('%r') |
|
365 | float_format = Unicode('%r') | |
364 | # setter for float precision, either int or direct format-string |
|
366 | # setter for float precision, either int or direct format-string | |
365 | float_precision = CUnicode('', config=True) |
|
367 | float_precision = CUnicode('', config=True) | |
366 |
|
368 | |||
367 | def _float_precision_changed(self, name, old, new): |
|
369 | def _float_precision_changed(self, name, old, new): | |
368 | """float_precision changed, set float_format accordingly. |
|
370 | """float_precision changed, set float_format accordingly. | |
369 |
|
371 | |||
370 | float_precision can be set by int or str. |
|
372 | float_precision can be set by int or str. | |
371 | This will set float_format, after interpreting input. |
|
373 | This will set float_format, after interpreting input. | |
372 | If numpy has been imported, numpy print precision will also be set. |
|
374 | If numpy has been imported, numpy print precision will also be set. | |
373 |
|
375 | |||
374 | integer `n` sets format to '%.nf', otherwise, format set directly. |
|
376 | integer `n` sets format to '%.nf', otherwise, format set directly. | |
375 |
|
377 | |||
376 | An empty string returns to defaults (repr for float, 8 for numpy). |
|
378 | An empty string returns to defaults (repr for float, 8 for numpy). | |
377 |
|
379 | |||
378 | This parameter can be set via the '%precision' magic. |
|
380 | This parameter can be set via the '%precision' magic. | |
379 | """ |
|
381 | """ | |
380 |
|
382 | |||
381 | if '%' in new: |
|
383 | if '%' in new: | |
382 | # got explicit format string |
|
384 | # got explicit format string | |
383 | fmt = new |
|
385 | fmt = new | |
384 | try: |
|
386 | try: | |
385 | fmt%3.14159 |
|
387 | fmt%3.14159 | |
386 | except Exception: |
|
388 | except Exception: | |
387 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
389 | raise ValueError("Precision must be int or format string, not %r"%new) | |
388 | elif new: |
|
390 | elif new: | |
389 | # otherwise, should be an int |
|
391 | # otherwise, should be an int | |
390 | try: |
|
392 | try: | |
391 | i = int(new) |
|
393 | i = int(new) | |
392 | assert i >= 0 |
|
394 | assert i >= 0 | |
393 | except ValueError: |
|
395 | except ValueError: | |
394 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
396 | raise ValueError("Precision must be int or format string, not %r"%new) | |
395 | except AssertionError: |
|
397 | except AssertionError: | |
396 | raise ValueError("int precision must be non-negative, not %r"%i) |
|
398 | raise ValueError("int precision must be non-negative, not %r"%i) | |
397 |
|
399 | |||
398 | fmt = '%%.%if'%i |
|
400 | fmt = '%%.%if'%i | |
399 | if 'numpy' in sys.modules: |
|
401 | if 'numpy' in sys.modules: | |
400 | # set numpy precision if it has been imported |
|
402 | # set numpy precision if it has been imported | |
401 | import numpy |
|
403 | import numpy | |
402 | numpy.set_printoptions(precision=i) |
|
404 | numpy.set_printoptions(precision=i) | |
403 | else: |
|
405 | else: | |
404 | # default back to repr |
|
406 | # default back to repr | |
405 | fmt = '%r' |
|
407 | fmt = '%r' | |
406 | if 'numpy' in sys.modules: |
|
408 | if 'numpy' in sys.modules: | |
407 | import numpy |
|
409 | import numpy | |
408 | # numpy default is 8 |
|
410 | # numpy default is 8 | |
409 | numpy.set_printoptions(precision=8) |
|
411 | numpy.set_printoptions(precision=8) | |
410 | self.float_format = fmt |
|
412 | self.float_format = fmt | |
411 |
|
413 | |||
412 | # Use the default pretty printers from IPython.external.pretty. |
|
414 | # Use the default pretty printers from IPython.external.pretty. | |
413 | def _singleton_printers_default(self): |
|
415 | def _singleton_printers_default(self): | |
414 | return pretty._singleton_pprinters.copy() |
|
416 | return pretty._singleton_pprinters.copy() | |
415 |
|
417 | |||
416 | def _type_printers_default(self): |
|
418 | def _type_printers_default(self): | |
417 | d = pretty._type_pprinters.copy() |
|
419 | d = pretty._type_pprinters.copy() | |
418 | d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) |
|
420 | d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) | |
419 | return d |
|
421 | return d | |
420 |
|
422 | |||
421 | def _deferred_printers_default(self): |
|
423 | def _deferred_printers_default(self): | |
422 | return pretty._deferred_type_pprinters.copy() |
|
424 | return pretty._deferred_type_pprinters.copy() | |
423 |
|
425 | |||
424 | #### FormatterABC interface #### |
|
426 | #### FormatterABC interface #### | |
425 |
|
427 | |||
426 | def __call__(self, obj): |
|
428 | def __call__(self, obj): | |
427 | """Compute the pretty representation of the object.""" |
|
429 | """Compute the pretty representation of the object.""" | |
428 | if not self.pprint: |
|
430 | if not self.pprint: | |
429 | try: |
|
431 | try: | |
430 | return repr(obj) |
|
432 | return repr(obj) | |
431 | except TypeError: |
|
433 | except TypeError: | |
432 | return '' |
|
434 | return '' | |
433 | else: |
|
435 | else: | |
434 | # This uses use StringIO, as cStringIO doesn't handle unicode. |
|
436 | # This uses use StringIO, as cStringIO doesn't handle unicode. | |
435 | stream = StringIO() |
|
437 | stream = StringIO() | |
436 | # self.newline.encode() is a quick fix for issue gh-597. We need to |
|
438 | # self.newline.encode() is a quick fix for issue gh-597. We need to | |
437 | # ensure that stream does not get a mix of unicode and bytestrings, |
|
439 | # ensure that stream does not get a mix of unicode and bytestrings, | |
438 | # or it will cause trouble. |
|
440 | # or it will cause trouble. | |
439 | printer = pretty.RepresentationPrinter(stream, self.verbose, |
|
441 | printer = pretty.RepresentationPrinter(stream, self.verbose, | |
440 | self.max_width, self.newline.encode(), |
|
442 | self.max_width, self.newline.encode(), | |
441 | singleton_pprinters=self.singleton_printers, |
|
443 | singleton_pprinters=self.singleton_printers, | |
442 | type_pprinters=self.type_printers, |
|
444 | type_pprinters=self.type_printers, | |
443 | deferred_pprinters=self.deferred_printers) |
|
445 | deferred_pprinters=self.deferred_printers) | |
444 | printer.pretty(obj) |
|
446 | printer.pretty(obj) | |
445 | printer.flush() |
|
447 | printer.flush() | |
446 | return stream.getvalue() |
|
448 | return stream.getvalue() | |
447 |
|
449 | |||
448 |
|
450 | |||
449 | class HTMLFormatter(BaseFormatter): |
|
451 | class HTMLFormatter(BaseFormatter): | |
450 | """An HTML formatter. |
|
452 | """An HTML formatter. | |
451 |
|
453 | |||
452 | To define the callables that compute the HTML representation of your |
|
454 | To define the callables that compute the HTML representation of your | |
453 | objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` |
|
455 | objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` | |
454 | or :meth:`for_type_by_name` methods to register functions that handle |
|
456 | or :meth:`for_type_by_name` methods to register functions that handle | |
455 | this. |
|
457 | this. | |
456 |
|
458 | |||
457 | The return value of this formatter should be a valid HTML snippet that |
|
459 | The return value of this formatter should be a valid HTML snippet that | |
458 | could be injected into an existing DOM. It should *not* include the |
|
460 | could be injected into an existing DOM. It should *not* include the | |
459 | ```<html>`` or ```<body>`` tags. |
|
461 | ```<html>`` or ```<body>`` tags. | |
460 | """ |
|
462 | """ | |
461 | format_type = Unicode('text/html') |
|
463 | format_type = Unicode('text/html') | |
462 |
|
464 | |||
463 | print_method = ObjectName('_repr_html_') |
|
465 | print_method = ObjectName('_repr_html_') | |
464 |
|
466 | |||
465 |
|
467 | |||
466 | class SVGFormatter(BaseFormatter): |
|
468 | class SVGFormatter(BaseFormatter): | |
467 | """An SVG formatter. |
|
469 | """An SVG formatter. | |
468 |
|
470 | |||
469 | To define the callables that compute the SVG representation of your |
|
471 | To define the callables that compute the SVG representation of your | |
470 | objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type` |
|
472 | objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type` | |
471 | or :meth:`for_type_by_name` methods to register functions that handle |
|
473 | or :meth:`for_type_by_name` methods to register functions that handle | |
472 | this. |
|
474 | this. | |
473 |
|
475 | |||
474 | The return value of this formatter should be valid SVG enclosed in |
|
476 | The return value of this formatter should be valid SVG enclosed in | |
475 | ```<svg>``` tags, that could be injected into an existing DOM. It should |
|
477 | ```<svg>``` tags, that could be injected into an existing DOM. It should | |
476 | *not* include the ```<html>`` or ```<body>`` tags. |
|
478 | *not* include the ```<html>`` or ```<body>`` tags. | |
477 | """ |
|
479 | """ | |
478 | format_type = Unicode('image/svg+xml') |
|
480 | format_type = Unicode('image/svg+xml') | |
479 |
|
481 | |||
480 | print_method = ObjectName('_repr_svg_') |
|
482 | print_method = ObjectName('_repr_svg_') | |
481 |
|
483 | |||
482 |
|
484 | |||
483 | class PNGFormatter(BaseFormatter): |
|
485 | class PNGFormatter(BaseFormatter): | |
484 | """A PNG formatter. |
|
486 | """A PNG formatter. | |
485 |
|
487 | |||
486 | To define the callables that compute the PNG representation of your |
|
488 | To define the callables that compute the PNG representation of your | |
487 | objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` |
|
489 | objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` | |
488 | or :meth:`for_type_by_name` methods to register functions that handle |
|
490 | or :meth:`for_type_by_name` methods to register functions that handle | |
489 | this. |
|
491 | this. | |
490 |
|
492 | |||
491 | The return value of this formatter should be raw PNG data, *not* |
|
493 | The return value of this formatter should be raw PNG data, *not* | |
492 | base64 encoded. |
|
494 | base64 encoded. | |
493 | """ |
|
495 | """ | |
494 | format_type = Unicode('image/png') |
|
496 | format_type = Unicode('image/png') | |
495 |
|
497 | |||
496 | print_method = ObjectName('_repr_png_') |
|
498 | print_method = ObjectName('_repr_png_') | |
497 |
|
499 | |||
498 |
|
500 | |||
|
501 | class JPEGFormatter(BaseFormatter): | |||
|
502 | """A JPEG formatter. | |||
|
503 | ||||
|
504 | To define the callables that compute the JPEG representation of your | |||
|
505 | objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type` | |||
|
506 | or :meth:`for_type_by_name` methods to register functions that handle | |||
|
507 | this. | |||
|
508 | ||||
|
509 | The return value of this formatter should be raw JPEG data, *not* | |||
|
510 | base64 encoded. | |||
|
511 | """ | |||
|
512 | format_type = Unicode('image/jpeg') | |||
|
513 | ||||
|
514 | print_method = ObjectName('_repr_jpeg_') | |||
|
515 | ||||
|
516 | ||||
499 | class LatexFormatter(BaseFormatter): |
|
517 | class LatexFormatter(BaseFormatter): | |
500 | """A LaTeX formatter. |
|
518 | """A LaTeX formatter. | |
501 |
|
519 | |||
502 | To define the callables that compute the LaTeX representation of your |
|
520 | To define the callables that compute the LaTeX representation of your | |
503 | objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type` |
|
521 | objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type` | |
504 | or :meth:`for_type_by_name` methods to register functions that handle |
|
522 | or :meth:`for_type_by_name` methods to register functions that handle | |
505 | this. |
|
523 | this. | |
506 |
|
524 | |||
507 | The return value of this formatter should be a valid LaTeX equation, |
|
525 | The return value of this formatter should be a valid LaTeX equation, | |
508 | enclosed in either ```$``` or ```$$```. |
|
526 | enclosed in either ```$``` or ```$$```. | |
509 | """ |
|
527 | """ | |
510 | format_type = Unicode('text/latex') |
|
528 | format_type = Unicode('text/latex') | |
511 |
|
529 | |||
512 | print_method = ObjectName('_repr_latex_') |
|
530 | print_method = ObjectName('_repr_latex_') | |
513 |
|
531 | |||
514 |
|
532 | |||
515 | class JSONFormatter(BaseFormatter): |
|
533 | class JSONFormatter(BaseFormatter): | |
516 | """A JSON string formatter. |
|
534 | """A JSON string formatter. | |
517 |
|
535 | |||
518 | To define the callables that compute the JSON string representation of |
|
536 | To define the callables that compute the JSON string representation of | |
519 | your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` |
|
537 | your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` | |
520 | or :meth:`for_type_by_name` methods to register functions that handle |
|
538 | or :meth:`for_type_by_name` methods to register functions that handle | |
521 | this. |
|
539 | this. | |
522 |
|
540 | |||
523 | The return value of this formatter should be a valid JSON string. |
|
541 | The return value of this formatter should be a valid JSON string. | |
524 | """ |
|
542 | """ | |
525 | format_type = Unicode('application/json') |
|
543 | format_type = Unicode('application/json') | |
526 |
|
544 | |||
527 | print_method = ObjectName('_repr_json_') |
|
545 | print_method = ObjectName('_repr_json_') | |
528 |
|
546 | |||
529 |
|
547 | |||
530 | class JavascriptFormatter(BaseFormatter): |
|
548 | class JavascriptFormatter(BaseFormatter): | |
531 | """A Javascript formatter. |
|
549 | """A Javascript formatter. | |
532 |
|
550 | |||
533 | To define the callables that compute the Javascript representation of |
|
551 | To define the callables that compute the Javascript representation of | |
534 | your objects, define a :meth:`_repr_javascript_` method or use the |
|
552 | your objects, define a :meth:`_repr_javascript_` method or use the | |
535 | :meth:`for_type` or :meth:`for_type_by_name` methods to register functions |
|
553 | :meth:`for_type` or :meth:`for_type_by_name` methods to register functions | |
536 | that handle this. |
|
554 | that handle this. | |
537 |
|
555 | |||
538 | The return value of this formatter should be valid Javascript code and |
|
556 | The return value of this formatter should be valid Javascript code and | |
539 | should *not* be enclosed in ```<script>``` tags. |
|
557 | should *not* be enclosed in ```<script>``` tags. | |
540 | """ |
|
558 | """ | |
541 | format_type = Unicode('application/javascript') |
|
559 | format_type = Unicode('application/javascript') | |
542 |
|
560 | |||
543 | print_method = ObjectName('_repr_javascript_') |
|
561 | print_method = ObjectName('_repr_javascript_') | |
544 |
|
562 | |||
545 | FormatterABC.register(BaseFormatter) |
|
563 | FormatterABC.register(BaseFormatter) | |
546 | FormatterABC.register(PlainTextFormatter) |
|
564 | FormatterABC.register(PlainTextFormatter) | |
547 | FormatterABC.register(HTMLFormatter) |
|
565 | FormatterABC.register(HTMLFormatter) | |
548 | FormatterABC.register(SVGFormatter) |
|
566 | FormatterABC.register(SVGFormatter) | |
549 | FormatterABC.register(PNGFormatter) |
|
567 | FormatterABC.register(PNGFormatter) | |
|
568 | FormatterABC.register(JPEGFormatter) | |||
550 | FormatterABC.register(LatexFormatter) |
|
569 | FormatterABC.register(LatexFormatter) | |
551 | FormatterABC.register(JSONFormatter) |
|
570 | FormatterABC.register(JSONFormatter) | |
552 | FormatterABC.register(JavascriptFormatter) |
|
571 | FormatterABC.register(JavascriptFormatter) | |
553 |
|
572 | |||
554 |
|
573 | |||
555 | def format_display_data(obj, include=None, exclude=None): |
|
574 | def format_display_data(obj, include=None, exclude=None): | |
556 | """Return a format data dict for an object. |
|
575 | """Return a format data dict for an object. | |
557 |
|
576 | |||
558 | By default all format types will be computed. |
|
577 | By default all format types will be computed. | |
559 |
|
578 | |||
560 | The following MIME types are currently implemented: |
|
579 | The following MIME types are currently implemented: | |
561 |
|
580 | |||
562 | * text/plain |
|
581 | * text/plain | |
563 | * text/html |
|
582 | * text/html | |
564 | * text/latex |
|
583 | * text/latex | |
565 | * application/json |
|
584 | * application/json | |
566 | * application/javascript |
|
585 | * application/javascript | |
567 | * image/png |
|
586 | * image/png | |
|
587 | * image/jpeg | |||
568 | * image/svg+xml |
|
588 | * image/svg+xml | |
569 |
|
589 | |||
570 | Parameters |
|
590 | Parameters | |
571 | ---------- |
|
591 | ---------- | |
572 | obj : object |
|
592 | obj : object | |
573 | The Python object whose format data will be computed. |
|
593 | The Python object whose format data will be computed. | |
574 |
|
594 | |||
575 | Returns |
|
595 | Returns | |
576 | ------- |
|
596 | ------- | |
577 | format_dict : dict |
|
597 | format_dict : dict | |
578 | A dictionary of key/value pairs, one or each format that was |
|
598 | A dictionary of key/value pairs, one or each format that was | |
579 | generated for the object. The keys are the format types, which |
|
599 | generated for the object. The keys are the format types, which | |
580 | will usually be MIME type strings and the values and JSON'able |
|
600 | will usually be MIME type strings and the values and JSON'able | |
581 | data structure containing the raw data for the representation in |
|
601 | data structure containing the raw data for the representation in | |
582 | that format. |
|
602 | that format. | |
583 | include : list or tuple, optional |
|
603 | include : list or tuple, optional | |
584 | A list of format type strings (MIME types) to include in the |
|
604 | A list of format type strings (MIME types) to include in the | |
585 | format data dict. If this is set *only* the format types included |
|
605 | format data dict. If this is set *only* the format types included | |
586 | in this list will be computed. |
|
606 | in this list will be computed. | |
587 | exclude : list or tuple, optional |
|
607 | exclude : list or tuple, optional | |
588 | A list of format type string (MIME types) to exclue in the format |
|
608 | A list of format type string (MIME types) to exclue in the format | |
589 | data dict. If this is set all format types will be computed, |
|
609 | data dict. If this is set all format types will be computed, | |
590 | except for those included in this argument. |
|
610 | except for those included in this argument. | |
591 | """ |
|
611 | """ | |
592 | from IPython.core.interactiveshell import InteractiveShell |
|
612 | from IPython.core.interactiveshell import InteractiveShell | |
593 |
|
613 | |||
594 | InteractiveShell.instance().display_formatter.format( |
|
614 | InteractiveShell.instance().display_formatter.format( | |
595 | obj, |
|
615 | obj, | |
596 | include, |
|
616 | include, | |
597 | exclude |
|
617 | exclude | |
598 | ) |
|
618 | ) | |
|
619 |
@@ -1,3563 +1,3564 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """Magic functions for InteractiveShell. |
|
2 | """Magic functions for InteractiveShell. | |
3 | """ |
|
3 | """ | |
4 |
|
4 | |||
5 | #----------------------------------------------------------------------------- |
|
5 | #----------------------------------------------------------------------------- | |
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> | |
8 | # Copyright (C) 2008-2009 The IPython Development Team |
|
8 | # Copyright (C) 2008-2009 The IPython Development Team | |
9 |
|
9 | |||
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | import __builtin__ |
|
18 | import __builtin__ | |
19 | import __future__ |
|
19 | import __future__ | |
20 | import bdb |
|
20 | import bdb | |
21 | import inspect |
|
21 | import inspect | |
22 | import os |
|
22 | import os | |
23 | import sys |
|
23 | import sys | |
24 | import shutil |
|
24 | import shutil | |
25 | import re |
|
25 | import re | |
26 | import time |
|
26 | import time | |
27 | import textwrap |
|
27 | import textwrap | |
28 | from cStringIO import StringIO |
|
28 | from cStringIO import StringIO | |
29 | from getopt import getopt,GetoptError |
|
29 | from getopt import getopt,GetoptError | |
30 | from pprint import pformat |
|
30 | from pprint import pformat | |
31 | from xmlrpclib import ServerProxy |
|
31 | from xmlrpclib import ServerProxy | |
32 |
|
32 | |||
33 | # cProfile was added in Python2.5 |
|
33 | # cProfile was added in Python2.5 | |
34 | try: |
|
34 | try: | |
35 | import cProfile as profile |
|
35 | import cProfile as profile | |
36 | import pstats |
|
36 | import pstats | |
37 | except ImportError: |
|
37 | except ImportError: | |
38 | # profile isn't bundled by default in Debian for license reasons |
|
38 | # profile isn't bundled by default in Debian for license reasons | |
39 | try: |
|
39 | try: | |
40 | import profile,pstats |
|
40 | import profile,pstats | |
41 | except ImportError: |
|
41 | except ImportError: | |
42 | profile = pstats = None |
|
42 | profile = pstats = None | |
43 |
|
43 | |||
44 | import IPython |
|
44 | import IPython | |
45 | from IPython.core import debugger, oinspect |
|
45 | from IPython.core import debugger, oinspect | |
46 | from IPython.core.error import TryNext |
|
46 | from IPython.core.error import TryNext | |
47 | from IPython.core.error import UsageError |
|
47 | from IPython.core.error import UsageError | |
48 | from IPython.core.fakemodule import FakeModule |
|
48 | from IPython.core.fakemodule import FakeModule | |
49 | from IPython.core.profiledir import ProfileDir |
|
49 | from IPython.core.profiledir import ProfileDir | |
50 | from IPython.core.macro import Macro |
|
50 | from IPython.core.macro import Macro | |
51 | from IPython.core import magic_arguments |
|
51 | from IPython.core import magic_arguments | |
52 | from IPython.core import page |
|
52 | from IPython.core import page | |
53 | from IPython.core.prefilter import ESC_MAGIC |
|
53 | from IPython.core.prefilter import ESC_MAGIC | |
54 | from IPython.lib.pylabtools import mpl_runner |
|
54 | from IPython.lib.pylabtools import mpl_runner | |
55 | from IPython.testing.skipdoctest import skip_doctest |
|
55 | from IPython.testing.skipdoctest import skip_doctest | |
56 | from IPython.utils.io import file_read, nlprint |
|
56 | from IPython.utils.io import file_read, nlprint | |
57 | from IPython.utils.path import get_py_filename |
|
57 | from IPython.utils.path import get_py_filename | |
58 | from IPython.utils.process import arg_split, abbrev_cwd |
|
58 | from IPython.utils.process import arg_split, abbrev_cwd | |
59 | from IPython.utils.terminal import set_term_title |
|
59 | from IPython.utils.terminal import set_term_title | |
60 | from IPython.utils.text import LSString, SList, format_screen |
|
60 | from IPython.utils.text import LSString, SList, format_screen | |
61 | from IPython.utils.timing import clock, clock2 |
|
61 | from IPython.utils.timing import clock, clock2 | |
62 | from IPython.utils.warn import warn, error |
|
62 | from IPython.utils.warn import warn, error | |
63 | from IPython.utils.ipstruct import Struct |
|
63 | from IPython.utils.ipstruct import Struct | |
64 | import IPython.utils.generics |
|
64 | import IPython.utils.generics | |
65 |
|
65 | |||
66 | #----------------------------------------------------------------------------- |
|
66 | #----------------------------------------------------------------------------- | |
67 | # Utility functions |
|
67 | # Utility functions | |
68 | #----------------------------------------------------------------------------- |
|
68 | #----------------------------------------------------------------------------- | |
69 |
|
69 | |||
70 | def on_off(tag): |
|
70 | def on_off(tag): | |
71 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
71 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
72 | return ['OFF','ON'][tag] |
|
72 | return ['OFF','ON'][tag] | |
73 |
|
73 | |||
74 | class Bunch: pass |
|
74 | class Bunch: pass | |
75 |
|
75 | |||
76 | def compress_dhist(dh): |
|
76 | def compress_dhist(dh): | |
77 | head, tail = dh[:-10], dh[-10:] |
|
77 | head, tail = dh[:-10], dh[-10:] | |
78 |
|
78 | |||
79 | newhead = [] |
|
79 | newhead = [] | |
80 | done = set() |
|
80 | done = set() | |
81 | for h in head: |
|
81 | for h in head: | |
82 | if h in done: |
|
82 | if h in done: | |
83 | continue |
|
83 | continue | |
84 | newhead.append(h) |
|
84 | newhead.append(h) | |
85 | done.add(h) |
|
85 | done.add(h) | |
86 |
|
86 | |||
87 | return newhead + tail |
|
87 | return newhead + tail | |
88 |
|
88 | |||
89 | def needs_local_scope(func): |
|
89 | def needs_local_scope(func): | |
90 | """Decorator to mark magic functions which need to local scope to run.""" |
|
90 | """Decorator to mark magic functions which need to local scope to run.""" | |
91 | func.needs_local_scope = True |
|
91 | func.needs_local_scope = True | |
92 | return func |
|
92 | return func | |
93 |
|
93 | |||
94 | # Used for exception handling in magic_edit |
|
94 | # Used for exception handling in magic_edit | |
95 | class MacroToEdit(ValueError): pass |
|
95 | class MacroToEdit(ValueError): pass | |
96 |
|
96 | |||
97 | #*************************************************************************** |
|
97 | #*************************************************************************** | |
98 | # Main class implementing Magic functionality |
|
98 | # Main class implementing Magic functionality | |
99 |
|
99 | |||
100 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors |
|
100 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors | |
101 | # on construction of the main InteractiveShell object. Something odd is going |
|
101 | # on construction of the main InteractiveShell object. Something odd is going | |
102 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but |
|
102 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but | |
103 | # eventually this needs to be clarified. |
|
103 | # eventually this needs to be clarified. | |
104 | # BG: This is because InteractiveShell inherits from this, but is itself a |
|
104 | # BG: This is because InteractiveShell inherits from this, but is itself a | |
105 | # Configurable. This messes up the MRO in some way. The fix is that we need to |
|
105 | # Configurable. This messes up the MRO in some way. The fix is that we need to | |
106 | # make Magic a configurable that InteractiveShell does not subclass. |
|
106 | # make Magic a configurable that InteractiveShell does not subclass. | |
107 |
|
107 | |||
108 | class Magic: |
|
108 | class Magic: | |
109 | """Magic functions for InteractiveShell. |
|
109 | """Magic functions for InteractiveShell. | |
110 |
|
110 | |||
111 | Shell functions which can be reached as %function_name. All magic |
|
111 | Shell functions which can be reached as %function_name. All magic | |
112 | functions should accept a string, which they can parse for their own |
|
112 | functions should accept a string, which they can parse for their own | |
113 | needs. This can make some functions easier to type, eg `%cd ../` |
|
113 | needs. This can make some functions easier to type, eg `%cd ../` | |
114 | vs. `%cd("../")` |
|
114 | vs. `%cd("../")` | |
115 |
|
115 | |||
116 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
116 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
117 | at the command line, but it is is needed in the definition. """ |
|
117 | at the command line, but it is is needed in the definition. """ | |
118 |
|
118 | |||
119 | # class globals |
|
119 | # class globals | |
120 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
120 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
121 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
121 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
122 |
|
122 | |||
123 | #...................................................................... |
|
123 | #...................................................................... | |
124 | # some utility functions |
|
124 | # some utility functions | |
125 |
|
125 | |||
126 | def __init__(self,shell): |
|
126 | def __init__(self,shell): | |
127 |
|
127 | |||
128 | self.options_table = {} |
|
128 | self.options_table = {} | |
129 | if profile is None: |
|
129 | if profile is None: | |
130 | self.magic_prun = self.profile_missing_notice |
|
130 | self.magic_prun = self.profile_missing_notice | |
131 | self.shell = shell |
|
131 | self.shell = shell | |
132 |
|
132 | |||
133 | # namespace for holding state we may need |
|
133 | # namespace for holding state we may need | |
134 | self._magic_state = Bunch() |
|
134 | self._magic_state = Bunch() | |
135 |
|
135 | |||
136 | def profile_missing_notice(self, *args, **kwargs): |
|
136 | def profile_missing_notice(self, *args, **kwargs): | |
137 | error("""\ |
|
137 | error("""\ | |
138 | The profile module could not be found. It has been removed from the standard |
|
138 | The profile module could not be found. It has been removed from the standard | |
139 | python packages because of its non-free license. To use profiling, install the |
|
139 | python packages because of its non-free license. To use profiling, install the | |
140 | python-profiler package from non-free.""") |
|
140 | python-profiler package from non-free.""") | |
141 |
|
141 | |||
142 | def default_option(self,fn,optstr): |
|
142 | def default_option(self,fn,optstr): | |
143 | """Make an entry in the options_table for fn, with value optstr""" |
|
143 | """Make an entry in the options_table for fn, with value optstr""" | |
144 |
|
144 | |||
145 | if fn not in self.lsmagic(): |
|
145 | if fn not in self.lsmagic(): | |
146 | error("%s is not a magic function" % fn) |
|
146 | error("%s is not a magic function" % fn) | |
147 | self.options_table[fn] = optstr |
|
147 | self.options_table[fn] = optstr | |
148 |
|
148 | |||
149 | def lsmagic(self): |
|
149 | def lsmagic(self): | |
150 | """Return a list of currently available magic functions. |
|
150 | """Return a list of currently available magic functions. | |
151 |
|
151 | |||
152 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
152 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
153 | ['magic_ls','magic_cd',...]""" |
|
153 | ['magic_ls','magic_cd',...]""" | |
154 |
|
154 | |||
155 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
155 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
156 |
|
156 | |||
157 | # magics in class definition |
|
157 | # magics in class definition | |
158 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
158 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
159 | callable(Magic.__dict__[fn]) |
|
159 | callable(Magic.__dict__[fn]) | |
160 | # in instance namespace (run-time user additions) |
|
160 | # in instance namespace (run-time user additions) | |
161 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
161 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
162 | callable(self.__dict__[fn]) |
|
162 | callable(self.__dict__[fn]) | |
163 | # and bound magics by user (so they can access self): |
|
163 | # and bound magics by user (so they can access self): | |
164 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
164 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
165 | callable(self.__class__.__dict__[fn]) |
|
165 | callable(self.__class__.__dict__[fn]) | |
166 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
166 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
167 | filter(inst_magic,self.__dict__.keys()) + \ |
|
167 | filter(inst_magic,self.__dict__.keys()) + \ | |
168 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
168 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
169 | out = [] |
|
169 | out = [] | |
170 | for fn in set(magics): |
|
170 | for fn in set(magics): | |
171 | out.append(fn.replace('magic_','',1)) |
|
171 | out.append(fn.replace('magic_','',1)) | |
172 | out.sort() |
|
172 | out.sort() | |
173 | return out |
|
173 | return out | |
174 |
|
174 | |||
175 | def extract_input_lines(self, range_str, raw=False): |
|
175 | def extract_input_lines(self, range_str, raw=False): | |
176 | """Return as a string a set of input history slices. |
|
176 | """Return as a string a set of input history slices. | |
177 |
|
177 | |||
178 | Inputs: |
|
178 | Inputs: | |
179 |
|
179 | |||
180 | - range_str: the set of slices is given as a string, like |
|
180 | - range_str: the set of slices is given as a string, like | |
181 | "~5/6-~4/2 4:8 9", since this function is for use by magic functions |
|
181 | "~5/6-~4/2 4:8 9", since this function is for use by magic functions | |
182 | which get their arguments as strings. The number before the / is the |
|
182 | which get their arguments as strings. The number before the / is the | |
183 | session number: ~n goes n back from the current session. |
|
183 | session number: ~n goes n back from the current session. | |
184 |
|
184 | |||
185 | Optional inputs: |
|
185 | Optional inputs: | |
186 |
|
186 | |||
187 | - raw(False): by default, the processed input is used. If this is |
|
187 | - raw(False): by default, the processed input is used. If this is | |
188 | true, the raw input history is used instead. |
|
188 | true, the raw input history is used instead. | |
189 |
|
189 | |||
190 | Note that slices can be called with two notations: |
|
190 | Note that slices can be called with two notations: | |
191 |
|
191 | |||
192 | N:M -> standard python form, means including items N...(M-1). |
|
192 | N:M -> standard python form, means including items N...(M-1). | |
193 |
|
193 | |||
194 | N-M -> include items N..M (closed endpoint).""" |
|
194 | N-M -> include items N..M (closed endpoint).""" | |
195 | lines = self.shell.history_manager.\ |
|
195 | lines = self.shell.history_manager.\ | |
196 | get_range_by_str(range_str, raw=raw) |
|
196 | get_range_by_str(range_str, raw=raw) | |
197 | return "\n".join(x for _, _, x in lines) |
|
197 | return "\n".join(x for _, _, x in lines) | |
198 |
|
198 | |||
199 | def arg_err(self,func): |
|
199 | def arg_err(self,func): | |
200 | """Print docstring if incorrect arguments were passed""" |
|
200 | """Print docstring if incorrect arguments were passed""" | |
201 | print 'Error in arguments:' |
|
201 | print 'Error in arguments:' | |
202 | print oinspect.getdoc(func) |
|
202 | print oinspect.getdoc(func) | |
203 |
|
203 | |||
204 | def format_latex(self,strng): |
|
204 | def format_latex(self,strng): | |
205 | """Format a string for latex inclusion.""" |
|
205 | """Format a string for latex inclusion.""" | |
206 |
|
206 | |||
207 | # Characters that need to be escaped for latex: |
|
207 | # Characters that need to be escaped for latex: | |
208 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
208 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
209 | # Magic command names as headers: |
|
209 | # Magic command names as headers: | |
210 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
210 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, | |
211 | re.MULTILINE) |
|
211 | re.MULTILINE) | |
212 | # Magic commands |
|
212 | # Magic commands | |
213 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
213 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, | |
214 | re.MULTILINE) |
|
214 | re.MULTILINE) | |
215 | # Paragraph continue |
|
215 | # Paragraph continue | |
216 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
216 | par_re = re.compile(r'\\$',re.MULTILINE) | |
217 |
|
217 | |||
218 | # The "\n" symbol |
|
218 | # The "\n" symbol | |
219 | newline_re = re.compile(r'\\n') |
|
219 | newline_re = re.compile(r'\\n') | |
220 |
|
220 | |||
221 | # Now build the string for output: |
|
221 | # Now build the string for output: | |
222 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
222 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
223 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
223 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
224 | strng) |
|
224 | strng) | |
225 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
225 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
226 | strng = par_re.sub(r'\\\\',strng) |
|
226 | strng = par_re.sub(r'\\\\',strng) | |
227 | strng = escape_re.sub(r'\\\1',strng) |
|
227 | strng = escape_re.sub(r'\\\1',strng) | |
228 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
228 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
229 | return strng |
|
229 | return strng | |
230 |
|
230 | |||
231 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
231 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
232 | """Parse options passed to an argument string. |
|
232 | """Parse options passed to an argument string. | |
233 |
|
233 | |||
234 | The interface is similar to that of getopt(), but it returns back a |
|
234 | The interface is similar to that of getopt(), but it returns back a | |
235 | Struct with the options as keys and the stripped argument string still |
|
235 | Struct with the options as keys and the stripped argument string still | |
236 | as a string. |
|
236 | as a string. | |
237 |
|
237 | |||
238 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
238 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
239 | This allows us to easily expand variables, glob files, quote |
|
239 | This allows us to easily expand variables, glob files, quote | |
240 | arguments, etc. |
|
240 | arguments, etc. | |
241 |
|
241 | |||
242 | Options: |
|
242 | Options: | |
243 | -mode: default 'string'. If given as 'list', the argument string is |
|
243 | -mode: default 'string'. If given as 'list', the argument string is | |
244 | returned as a list (split on whitespace) instead of a string. |
|
244 | returned as a list (split on whitespace) instead of a string. | |
245 |
|
245 | |||
246 | -list_all: put all option values in lists. Normally only options |
|
246 | -list_all: put all option values in lists. Normally only options | |
247 | appearing more than once are put in a list. |
|
247 | appearing more than once are put in a list. | |
248 |
|
248 | |||
249 | -posix (True): whether to split the input line in POSIX mode or not, |
|
249 | -posix (True): whether to split the input line in POSIX mode or not, | |
250 | as per the conventions outlined in the shlex module from the |
|
250 | as per the conventions outlined in the shlex module from the | |
251 | standard library.""" |
|
251 | standard library.""" | |
252 |
|
252 | |||
253 | # inject default options at the beginning of the input line |
|
253 | # inject default options at the beginning of the input line | |
254 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
254 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
255 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
255 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
256 |
|
256 | |||
257 | mode = kw.get('mode','string') |
|
257 | mode = kw.get('mode','string') | |
258 | if mode not in ['string','list']: |
|
258 | if mode not in ['string','list']: | |
259 | raise ValueError,'incorrect mode given: %s' % mode |
|
259 | raise ValueError,'incorrect mode given: %s' % mode | |
260 | # Get options |
|
260 | # Get options | |
261 | list_all = kw.get('list_all',0) |
|
261 | list_all = kw.get('list_all',0) | |
262 | posix = kw.get('posix', os.name == 'posix') |
|
262 | posix = kw.get('posix', os.name == 'posix') | |
263 |
|
263 | |||
264 | # Check if we have more than one argument to warrant extra processing: |
|
264 | # Check if we have more than one argument to warrant extra processing: | |
265 | odict = {} # Dictionary with options |
|
265 | odict = {} # Dictionary with options | |
266 | args = arg_str.split() |
|
266 | args = arg_str.split() | |
267 | if len(args) >= 1: |
|
267 | if len(args) >= 1: | |
268 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
268 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
269 | # need to look for options |
|
269 | # need to look for options | |
270 | argv = arg_split(arg_str,posix) |
|
270 | argv = arg_split(arg_str,posix) | |
271 | # Do regular option processing |
|
271 | # Do regular option processing | |
272 | try: |
|
272 | try: | |
273 | opts,args = getopt(argv,opt_str,*long_opts) |
|
273 | opts,args = getopt(argv,opt_str,*long_opts) | |
274 | except GetoptError,e: |
|
274 | except GetoptError,e: | |
275 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
275 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
276 | " ".join(long_opts))) |
|
276 | " ".join(long_opts))) | |
277 | for o,a in opts: |
|
277 | for o,a in opts: | |
278 | if o.startswith('--'): |
|
278 | if o.startswith('--'): | |
279 | o = o[2:] |
|
279 | o = o[2:] | |
280 | else: |
|
280 | else: | |
281 | o = o[1:] |
|
281 | o = o[1:] | |
282 | try: |
|
282 | try: | |
283 | odict[o].append(a) |
|
283 | odict[o].append(a) | |
284 | except AttributeError: |
|
284 | except AttributeError: | |
285 | odict[o] = [odict[o],a] |
|
285 | odict[o] = [odict[o],a] | |
286 | except KeyError: |
|
286 | except KeyError: | |
287 | if list_all: |
|
287 | if list_all: | |
288 | odict[o] = [a] |
|
288 | odict[o] = [a] | |
289 | else: |
|
289 | else: | |
290 | odict[o] = a |
|
290 | odict[o] = a | |
291 |
|
291 | |||
292 | # Prepare opts,args for return |
|
292 | # Prepare opts,args for return | |
293 | opts = Struct(odict) |
|
293 | opts = Struct(odict) | |
294 | if mode == 'string': |
|
294 | if mode == 'string': | |
295 | args = ' '.join(args) |
|
295 | args = ' '.join(args) | |
296 |
|
296 | |||
297 | return opts,args |
|
297 | return opts,args | |
298 |
|
298 | |||
299 | #...................................................................... |
|
299 | #...................................................................... | |
300 | # And now the actual magic functions |
|
300 | # And now the actual magic functions | |
301 |
|
301 | |||
302 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
302 | # Functions for IPython shell work (vars,funcs, config, etc) | |
303 | def magic_lsmagic(self, parameter_s = ''): |
|
303 | def magic_lsmagic(self, parameter_s = ''): | |
304 | """List currently available magic functions.""" |
|
304 | """List currently available magic functions.""" | |
305 | mesc = ESC_MAGIC |
|
305 | mesc = ESC_MAGIC | |
306 | print 'Available magic functions:\n'+mesc+\ |
|
306 | print 'Available magic functions:\n'+mesc+\ | |
307 | (' '+mesc).join(self.lsmagic()) |
|
307 | (' '+mesc).join(self.lsmagic()) | |
308 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
308 | print '\n' + Magic.auto_status[self.shell.automagic] | |
309 | return None |
|
309 | return None | |
310 |
|
310 | |||
311 | def magic_magic(self, parameter_s = ''): |
|
311 | def magic_magic(self, parameter_s = ''): | |
312 | """Print information about the magic function system. |
|
312 | """Print information about the magic function system. | |
313 |
|
313 | |||
314 | Supported formats: -latex, -brief, -rest |
|
314 | Supported formats: -latex, -brief, -rest | |
315 | """ |
|
315 | """ | |
316 |
|
316 | |||
317 | mode = '' |
|
317 | mode = '' | |
318 | try: |
|
318 | try: | |
319 | if parameter_s.split()[0] == '-latex': |
|
319 | if parameter_s.split()[0] == '-latex': | |
320 | mode = 'latex' |
|
320 | mode = 'latex' | |
321 | if parameter_s.split()[0] == '-brief': |
|
321 | if parameter_s.split()[0] == '-brief': | |
322 | mode = 'brief' |
|
322 | mode = 'brief' | |
323 | if parameter_s.split()[0] == '-rest': |
|
323 | if parameter_s.split()[0] == '-rest': | |
324 | mode = 'rest' |
|
324 | mode = 'rest' | |
325 | rest_docs = [] |
|
325 | rest_docs = [] | |
326 | except: |
|
326 | except: | |
327 | pass |
|
327 | pass | |
328 |
|
328 | |||
329 | magic_docs = [] |
|
329 | magic_docs = [] | |
330 | for fname in self.lsmagic(): |
|
330 | for fname in self.lsmagic(): | |
331 | mname = 'magic_' + fname |
|
331 | mname = 'magic_' + fname | |
332 | for space in (Magic,self,self.__class__): |
|
332 | for space in (Magic,self,self.__class__): | |
333 | try: |
|
333 | try: | |
334 | fn = space.__dict__[mname] |
|
334 | fn = space.__dict__[mname] | |
335 | except KeyError: |
|
335 | except KeyError: | |
336 | pass |
|
336 | pass | |
337 | else: |
|
337 | else: | |
338 | break |
|
338 | break | |
339 | if mode == 'brief': |
|
339 | if mode == 'brief': | |
340 | # only first line |
|
340 | # only first line | |
341 | if fn.__doc__: |
|
341 | if fn.__doc__: | |
342 | fndoc = fn.__doc__.split('\n',1)[0] |
|
342 | fndoc = fn.__doc__.split('\n',1)[0] | |
343 | else: |
|
343 | else: | |
344 | fndoc = 'No documentation' |
|
344 | fndoc = 'No documentation' | |
345 | else: |
|
345 | else: | |
346 | if fn.__doc__: |
|
346 | if fn.__doc__: | |
347 | fndoc = fn.__doc__.rstrip() |
|
347 | fndoc = fn.__doc__.rstrip() | |
348 | else: |
|
348 | else: | |
349 | fndoc = 'No documentation' |
|
349 | fndoc = 'No documentation' | |
350 |
|
350 | |||
351 |
|
351 | |||
352 | if mode == 'rest': |
|
352 | if mode == 'rest': | |
353 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
353 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, | |
354 | fname,fndoc)) |
|
354 | fname,fndoc)) | |
355 |
|
355 | |||
356 | else: |
|
356 | else: | |
357 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
357 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, | |
358 | fname,fndoc)) |
|
358 | fname,fndoc)) | |
359 |
|
359 | |||
360 | magic_docs = ''.join(magic_docs) |
|
360 | magic_docs = ''.join(magic_docs) | |
361 |
|
361 | |||
362 | if mode == 'rest': |
|
362 | if mode == 'rest': | |
363 | return "".join(rest_docs) |
|
363 | return "".join(rest_docs) | |
364 |
|
364 | |||
365 | if mode == 'latex': |
|
365 | if mode == 'latex': | |
366 | print self.format_latex(magic_docs) |
|
366 | print self.format_latex(magic_docs) | |
367 | return |
|
367 | return | |
368 | else: |
|
368 | else: | |
369 | magic_docs = format_screen(magic_docs) |
|
369 | magic_docs = format_screen(magic_docs) | |
370 | if mode == 'brief': |
|
370 | if mode == 'brief': | |
371 | return magic_docs |
|
371 | return magic_docs | |
372 |
|
372 | |||
373 | outmsg = """ |
|
373 | outmsg = """ | |
374 | IPython's 'magic' functions |
|
374 | IPython's 'magic' functions | |
375 | =========================== |
|
375 | =========================== | |
376 |
|
376 | |||
377 | The magic function system provides a series of functions which allow you to |
|
377 | The magic function system provides a series of functions which allow you to | |
378 | control the behavior of IPython itself, plus a lot of system-type |
|
378 | control the behavior of IPython itself, plus a lot of system-type | |
379 | features. All these functions are prefixed with a % character, but parameters |
|
379 | features. All these functions are prefixed with a % character, but parameters | |
380 | are given without parentheses or quotes. |
|
380 | are given without parentheses or quotes. | |
381 |
|
381 | |||
382 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
382 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
383 | %automagic function), you don't need to type in the % explicitly. By default, |
|
383 | %automagic function), you don't need to type in the % explicitly. By default, | |
384 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
384 | IPython ships with automagic on, so you should only rarely need the % escape. | |
385 |
|
385 | |||
386 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
386 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
387 | to 'mydir', if it exists. |
|
387 | to 'mydir', if it exists. | |
388 |
|
388 | |||
389 | For a list of the available magic functions, use %lsmagic. For a description |
|
389 | For a list of the available magic functions, use %lsmagic. For a description | |
390 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
390 | of any of them, type %magic_name?, e.g. '%cd?'. | |
391 |
|
391 | |||
392 | Currently the magic system has the following functions:\n""" |
|
392 | Currently the magic system has the following functions:\n""" | |
393 |
|
393 | |||
394 | mesc = ESC_MAGIC |
|
394 | mesc = ESC_MAGIC | |
395 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
395 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
396 | "\n\n%s%s\n\n%s" % (outmsg, |
|
396 | "\n\n%s%s\n\n%s" % (outmsg, | |
397 | magic_docs,mesc,mesc, |
|
397 | magic_docs,mesc,mesc, | |
398 | (' '+mesc).join(self.lsmagic()), |
|
398 | (' '+mesc).join(self.lsmagic()), | |
399 | Magic.auto_status[self.shell.automagic] ) ) |
|
399 | Magic.auto_status[self.shell.automagic] ) ) | |
400 | page.page(outmsg) |
|
400 | page.page(outmsg) | |
401 |
|
401 | |||
402 | def magic_automagic(self, parameter_s = ''): |
|
402 | def magic_automagic(self, parameter_s = ''): | |
403 | """Make magic functions callable without having to type the initial %. |
|
403 | """Make magic functions callable without having to type the initial %. | |
404 |
|
404 | |||
405 | Without argumentsl toggles on/off (when off, you must call it as |
|
405 | Without argumentsl toggles on/off (when off, you must call it as | |
406 | %automagic, of course). With arguments it sets the value, and you can |
|
406 | %automagic, of course). With arguments it sets the value, and you can | |
407 | use any of (case insensitive): |
|
407 | use any of (case insensitive): | |
408 |
|
408 | |||
409 | - on,1,True: to activate |
|
409 | - on,1,True: to activate | |
410 |
|
410 | |||
411 | - off,0,False: to deactivate. |
|
411 | - off,0,False: to deactivate. | |
412 |
|
412 | |||
413 | Note that magic functions have lowest priority, so if there's a |
|
413 | Note that magic functions have lowest priority, so if there's a | |
414 | variable whose name collides with that of a magic fn, automagic won't |
|
414 | variable whose name collides with that of a magic fn, automagic won't | |
415 | work for that function (you get the variable instead). However, if you |
|
415 | work for that function (you get the variable instead). However, if you | |
416 | delete the variable (del var), the previously shadowed magic function |
|
416 | delete the variable (del var), the previously shadowed magic function | |
417 | becomes visible to automagic again.""" |
|
417 | becomes visible to automagic again.""" | |
418 |
|
418 | |||
419 | arg = parameter_s.lower() |
|
419 | arg = parameter_s.lower() | |
420 | if parameter_s in ('on','1','true'): |
|
420 | if parameter_s in ('on','1','true'): | |
421 | self.shell.automagic = True |
|
421 | self.shell.automagic = True | |
422 | elif parameter_s in ('off','0','false'): |
|
422 | elif parameter_s in ('off','0','false'): | |
423 | self.shell.automagic = False |
|
423 | self.shell.automagic = False | |
424 | else: |
|
424 | else: | |
425 | self.shell.automagic = not self.shell.automagic |
|
425 | self.shell.automagic = not self.shell.automagic | |
426 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
426 | print '\n' + Magic.auto_status[self.shell.automagic] | |
427 |
|
427 | |||
428 | @skip_doctest |
|
428 | @skip_doctest | |
429 | def magic_autocall(self, parameter_s = ''): |
|
429 | def magic_autocall(self, parameter_s = ''): | |
430 | """Make functions callable without having to type parentheses. |
|
430 | """Make functions callable without having to type parentheses. | |
431 |
|
431 | |||
432 | Usage: |
|
432 | Usage: | |
433 |
|
433 | |||
434 | %autocall [mode] |
|
434 | %autocall [mode] | |
435 |
|
435 | |||
436 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
436 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
437 | value is toggled on and off (remembering the previous state). |
|
437 | value is toggled on and off (remembering the previous state). | |
438 |
|
438 | |||
439 | In more detail, these values mean: |
|
439 | In more detail, these values mean: | |
440 |
|
440 | |||
441 | 0 -> fully disabled |
|
441 | 0 -> fully disabled | |
442 |
|
442 | |||
443 | 1 -> active, but do not apply if there are no arguments on the line. |
|
443 | 1 -> active, but do not apply if there are no arguments on the line. | |
444 |
|
444 | |||
445 | In this mode, you get: |
|
445 | In this mode, you get: | |
446 |
|
446 | |||
447 | In [1]: callable |
|
447 | In [1]: callable | |
448 | Out[1]: <built-in function callable> |
|
448 | Out[1]: <built-in function callable> | |
449 |
|
449 | |||
450 | In [2]: callable 'hello' |
|
450 | In [2]: callable 'hello' | |
451 | ------> callable('hello') |
|
451 | ------> callable('hello') | |
452 | Out[2]: False |
|
452 | Out[2]: False | |
453 |
|
453 | |||
454 | 2 -> Active always. Even if no arguments are present, the callable |
|
454 | 2 -> Active always. Even if no arguments are present, the callable | |
455 | object is called: |
|
455 | object is called: | |
456 |
|
456 | |||
457 | In [2]: float |
|
457 | In [2]: float | |
458 | ------> float() |
|
458 | ------> float() | |
459 | Out[2]: 0.0 |
|
459 | Out[2]: 0.0 | |
460 |
|
460 | |||
461 | Note that even with autocall off, you can still use '/' at the start of |
|
461 | Note that even with autocall off, you can still use '/' at the start of | |
462 | a line to treat the first argument on the command line as a function |
|
462 | a line to treat the first argument on the command line as a function | |
463 | and add parentheses to it: |
|
463 | and add parentheses to it: | |
464 |
|
464 | |||
465 | In [8]: /str 43 |
|
465 | In [8]: /str 43 | |
466 | ------> str(43) |
|
466 | ------> str(43) | |
467 | Out[8]: '43' |
|
467 | Out[8]: '43' | |
468 |
|
468 | |||
469 | # all-random (note for auto-testing) |
|
469 | # all-random (note for auto-testing) | |
470 | """ |
|
470 | """ | |
471 |
|
471 | |||
472 | if parameter_s: |
|
472 | if parameter_s: | |
473 | arg = int(parameter_s) |
|
473 | arg = int(parameter_s) | |
474 | else: |
|
474 | else: | |
475 | arg = 'toggle' |
|
475 | arg = 'toggle' | |
476 |
|
476 | |||
477 | if not arg in (0,1,2,'toggle'): |
|
477 | if not arg in (0,1,2,'toggle'): | |
478 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
478 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
479 | return |
|
479 | return | |
480 |
|
480 | |||
481 | if arg in (0,1,2): |
|
481 | if arg in (0,1,2): | |
482 | self.shell.autocall = arg |
|
482 | self.shell.autocall = arg | |
483 | else: # toggle |
|
483 | else: # toggle | |
484 | if self.shell.autocall: |
|
484 | if self.shell.autocall: | |
485 | self._magic_state.autocall_save = self.shell.autocall |
|
485 | self._magic_state.autocall_save = self.shell.autocall | |
486 | self.shell.autocall = 0 |
|
486 | self.shell.autocall = 0 | |
487 | else: |
|
487 | else: | |
488 | try: |
|
488 | try: | |
489 | self.shell.autocall = self._magic_state.autocall_save |
|
489 | self.shell.autocall = self._magic_state.autocall_save | |
490 | except AttributeError: |
|
490 | except AttributeError: | |
491 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
491 | self.shell.autocall = self._magic_state.autocall_save = 1 | |
492 |
|
492 | |||
493 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
493 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] | |
494 |
|
494 | |||
495 |
|
495 | |||
496 | def magic_page(self, parameter_s=''): |
|
496 | def magic_page(self, parameter_s=''): | |
497 | """Pretty print the object and display it through a pager. |
|
497 | """Pretty print the object and display it through a pager. | |
498 |
|
498 | |||
499 | %page [options] OBJECT |
|
499 | %page [options] OBJECT | |
500 |
|
500 | |||
501 | If no object is given, use _ (last output). |
|
501 | If no object is given, use _ (last output). | |
502 |
|
502 | |||
503 | Options: |
|
503 | Options: | |
504 |
|
504 | |||
505 | -r: page str(object), don't pretty-print it.""" |
|
505 | -r: page str(object), don't pretty-print it.""" | |
506 |
|
506 | |||
507 | # After a function contributed by Olivier Aubert, slightly modified. |
|
507 | # After a function contributed by Olivier Aubert, slightly modified. | |
508 |
|
508 | |||
509 | # Process options/args |
|
509 | # Process options/args | |
510 | opts,args = self.parse_options(parameter_s,'r') |
|
510 | opts,args = self.parse_options(parameter_s,'r') | |
511 | raw = 'r' in opts |
|
511 | raw = 'r' in opts | |
512 |
|
512 | |||
513 | oname = args and args or '_' |
|
513 | oname = args and args or '_' | |
514 | info = self._ofind(oname) |
|
514 | info = self._ofind(oname) | |
515 | if info['found']: |
|
515 | if info['found']: | |
516 | txt = (raw and str or pformat)( info['obj'] ) |
|
516 | txt = (raw and str or pformat)( info['obj'] ) | |
517 | page.page(txt) |
|
517 | page.page(txt) | |
518 | else: |
|
518 | else: | |
519 | print 'Object `%s` not found' % oname |
|
519 | print 'Object `%s` not found' % oname | |
520 |
|
520 | |||
521 | def magic_profile(self, parameter_s=''): |
|
521 | def magic_profile(self, parameter_s=''): | |
522 | """Print your currently active IPython profile.""" |
|
522 | """Print your currently active IPython profile.""" | |
523 | print self.shell.profile |
|
523 | print self.shell.profile | |
524 |
|
524 | |||
525 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
525 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
526 | """Provide detailed information about an object. |
|
526 | """Provide detailed information about an object. | |
527 |
|
527 | |||
528 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
528 | '%pinfo object' is just a synonym for object? or ?object.""" | |
529 |
|
529 | |||
530 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
530 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
531 |
|
531 | |||
532 |
|
532 | |||
533 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
533 | # detail_level: 0 -> obj? , 1 -> obj?? | |
534 | detail_level = 0 |
|
534 | detail_level = 0 | |
535 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
535 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
536 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
536 | # happen if the user types 'pinfo foo?' at the cmd line. | |
537 | pinfo,qmark1,oname,qmark2 = \ |
|
537 | pinfo,qmark1,oname,qmark2 = \ | |
538 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
538 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
539 | if pinfo or qmark1 or qmark2: |
|
539 | if pinfo or qmark1 or qmark2: | |
540 | detail_level = 1 |
|
540 | detail_level = 1 | |
541 | if "*" in oname: |
|
541 | if "*" in oname: | |
542 | self.magic_psearch(oname) |
|
542 | self.magic_psearch(oname) | |
543 | else: |
|
543 | else: | |
544 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
544 | self.shell._inspect('pinfo', oname, detail_level=detail_level, | |
545 | namespaces=namespaces) |
|
545 | namespaces=namespaces) | |
546 |
|
546 | |||
547 | def magic_pinfo2(self, parameter_s='', namespaces=None): |
|
547 | def magic_pinfo2(self, parameter_s='', namespaces=None): | |
548 | """Provide extra detailed information about an object. |
|
548 | """Provide extra detailed information about an object. | |
549 |
|
549 | |||
550 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
550 | '%pinfo2 object' is just a synonym for object?? or ??object.""" | |
551 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
551 | self.shell._inspect('pinfo', parameter_s, detail_level=1, | |
552 | namespaces=namespaces) |
|
552 | namespaces=namespaces) | |
553 |
|
553 | |||
554 | @skip_doctest |
|
554 | @skip_doctest | |
555 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
555 | def magic_pdef(self, parameter_s='', namespaces=None): | |
556 | """Print the definition header for any callable object. |
|
556 | """Print the definition header for any callable object. | |
557 |
|
557 | |||
558 | If the object is a class, print the constructor information. |
|
558 | If the object is a class, print the constructor information. | |
559 |
|
559 | |||
560 | Examples |
|
560 | Examples | |
561 | -------- |
|
561 | -------- | |
562 | :: |
|
562 | :: | |
563 |
|
563 | |||
564 | In [3]: %pdef urllib.urlopen |
|
564 | In [3]: %pdef urllib.urlopen | |
565 | urllib.urlopen(url, data=None, proxies=None) |
|
565 | urllib.urlopen(url, data=None, proxies=None) | |
566 | """ |
|
566 | """ | |
567 | self._inspect('pdef',parameter_s, namespaces) |
|
567 | self._inspect('pdef',parameter_s, namespaces) | |
568 |
|
568 | |||
569 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
569 | def magic_pdoc(self, parameter_s='', namespaces=None): | |
570 | """Print the docstring for an object. |
|
570 | """Print the docstring for an object. | |
571 |
|
571 | |||
572 | If the given object is a class, it will print both the class and the |
|
572 | If the given object is a class, it will print both the class and the | |
573 | constructor docstrings.""" |
|
573 | constructor docstrings.""" | |
574 | self._inspect('pdoc',parameter_s, namespaces) |
|
574 | self._inspect('pdoc',parameter_s, namespaces) | |
575 |
|
575 | |||
576 | def magic_psource(self, parameter_s='', namespaces=None): |
|
576 | def magic_psource(self, parameter_s='', namespaces=None): | |
577 | """Print (or run through pager) the source code for an object.""" |
|
577 | """Print (or run through pager) the source code for an object.""" | |
578 | self._inspect('psource',parameter_s, namespaces) |
|
578 | self._inspect('psource',parameter_s, namespaces) | |
579 |
|
579 | |||
580 | def magic_pfile(self, parameter_s=''): |
|
580 | def magic_pfile(self, parameter_s=''): | |
581 | """Print (or run through pager) the file where an object is defined. |
|
581 | """Print (or run through pager) the file where an object is defined. | |
582 |
|
582 | |||
583 | The file opens at the line where the object definition begins. IPython |
|
583 | The file opens at the line where the object definition begins. IPython | |
584 | will honor the environment variable PAGER if set, and otherwise will |
|
584 | will honor the environment variable PAGER if set, and otherwise will | |
585 | do its best to print the file in a convenient form. |
|
585 | do its best to print the file in a convenient form. | |
586 |
|
586 | |||
587 | If the given argument is not an object currently defined, IPython will |
|
587 | If the given argument is not an object currently defined, IPython will | |
588 | try to interpret it as a filename (automatically adding a .py extension |
|
588 | try to interpret it as a filename (automatically adding a .py extension | |
589 | if needed). You can thus use %pfile as a syntax highlighting code |
|
589 | if needed). You can thus use %pfile as a syntax highlighting code | |
590 | viewer.""" |
|
590 | viewer.""" | |
591 |
|
591 | |||
592 | # first interpret argument as an object name |
|
592 | # first interpret argument as an object name | |
593 | out = self._inspect('pfile',parameter_s) |
|
593 | out = self._inspect('pfile',parameter_s) | |
594 | # if not, try the input as a filename |
|
594 | # if not, try the input as a filename | |
595 | if out == 'not found': |
|
595 | if out == 'not found': | |
596 | try: |
|
596 | try: | |
597 | filename = get_py_filename(parameter_s) |
|
597 | filename = get_py_filename(parameter_s) | |
598 | except IOError,msg: |
|
598 | except IOError,msg: | |
599 | print msg |
|
599 | print msg | |
600 | return |
|
600 | return | |
601 | page.page(self.shell.inspector.format(file(filename).read())) |
|
601 | page.page(self.shell.inspector.format(file(filename).read())) | |
602 |
|
602 | |||
603 | def magic_psearch(self, parameter_s=''): |
|
603 | def magic_psearch(self, parameter_s=''): | |
604 | """Search for object in namespaces by wildcard. |
|
604 | """Search for object in namespaces by wildcard. | |
605 |
|
605 | |||
606 | %psearch [options] PATTERN [OBJECT TYPE] |
|
606 | %psearch [options] PATTERN [OBJECT TYPE] | |
607 |
|
607 | |||
608 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
608 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
609 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
609 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
610 | rest of the command line must be unchanged (options come first), so |
|
610 | rest of the command line must be unchanged (options come first), so | |
611 | for example the following forms are equivalent |
|
611 | for example the following forms are equivalent | |
612 |
|
612 | |||
613 | %psearch -i a* function |
|
613 | %psearch -i a* function | |
614 | -i a* function? |
|
614 | -i a* function? | |
615 | ?-i a* function |
|
615 | ?-i a* function | |
616 |
|
616 | |||
617 | Arguments: |
|
617 | Arguments: | |
618 |
|
618 | |||
619 | PATTERN |
|
619 | PATTERN | |
620 |
|
620 | |||
621 | where PATTERN is a string containing * as a wildcard similar to its |
|
621 | where PATTERN is a string containing * as a wildcard similar to its | |
622 | use in a shell. The pattern is matched in all namespaces on the |
|
622 | use in a shell. The pattern is matched in all namespaces on the | |
623 | search path. By default objects starting with a single _ are not |
|
623 | search path. By default objects starting with a single _ are not | |
624 | matched, many IPython generated objects have a single |
|
624 | matched, many IPython generated objects have a single | |
625 | underscore. The default is case insensitive matching. Matching is |
|
625 | underscore. The default is case insensitive matching. Matching is | |
626 | also done on the attributes of objects and not only on the objects |
|
626 | also done on the attributes of objects and not only on the objects | |
627 | in a module. |
|
627 | in a module. | |
628 |
|
628 | |||
629 | [OBJECT TYPE] |
|
629 | [OBJECT TYPE] | |
630 |
|
630 | |||
631 | Is the name of a python type from the types module. The name is |
|
631 | Is the name of a python type from the types module. The name is | |
632 | given in lowercase without the ending type, ex. StringType is |
|
632 | given in lowercase without the ending type, ex. StringType is | |
633 | written string. By adding a type here only objects matching the |
|
633 | written string. By adding a type here only objects matching the | |
634 | given type are matched. Using all here makes the pattern match all |
|
634 | given type are matched. Using all here makes the pattern match all | |
635 | types (this is the default). |
|
635 | types (this is the default). | |
636 |
|
636 | |||
637 | Options: |
|
637 | Options: | |
638 |
|
638 | |||
639 | -a: makes the pattern match even objects whose names start with a |
|
639 | -a: makes the pattern match even objects whose names start with a | |
640 | single underscore. These names are normally ommitted from the |
|
640 | single underscore. These names are normally ommitted from the | |
641 | search. |
|
641 | search. | |
642 |
|
642 | |||
643 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
643 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
644 | these options is given, the default is read from your ipythonrc |
|
644 | these options is given, the default is read from your ipythonrc | |
645 | file. The option name which sets this value is |
|
645 | file. The option name which sets this value is | |
646 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
646 | 'wildcards_case_sensitive'. If this option is not specified in your | |
647 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
647 | ipythonrc file, IPython's internal default is to do a case sensitive | |
648 | search. |
|
648 | search. | |
649 |
|
649 | |||
650 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
650 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
651 | specifiy can be searched in any of the following namespaces: |
|
651 | specifiy can be searched in any of the following namespaces: | |
652 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
652 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
653 | 'builtin' and 'user' are the search defaults. Note that you should |
|
653 | 'builtin' and 'user' are the search defaults. Note that you should | |
654 | not use quotes when specifying namespaces. |
|
654 | not use quotes when specifying namespaces. | |
655 |
|
655 | |||
656 | 'Builtin' contains the python module builtin, 'user' contains all |
|
656 | 'Builtin' contains the python module builtin, 'user' contains all | |
657 | user data, 'alias' only contain the shell aliases and no python |
|
657 | user data, 'alias' only contain the shell aliases and no python | |
658 | objects, 'internal' contains objects used by IPython. The |
|
658 | objects, 'internal' contains objects used by IPython. The | |
659 | 'user_global' namespace is only used by embedded IPython instances, |
|
659 | 'user_global' namespace is only used by embedded IPython instances, | |
660 | and it contains module-level globals. You can add namespaces to the |
|
660 | and it contains module-level globals. You can add namespaces to the | |
661 | search with -s or exclude them with -e (these options can be given |
|
661 | search with -s or exclude them with -e (these options can be given | |
662 | more than once). |
|
662 | more than once). | |
663 |
|
663 | |||
664 | Examples: |
|
664 | Examples: | |
665 |
|
665 | |||
666 | %psearch a* -> objects beginning with an a |
|
666 | %psearch a* -> objects beginning with an a | |
667 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
667 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
668 | %psearch a* function -> all functions beginning with an a |
|
668 | %psearch a* function -> all functions beginning with an a | |
669 | %psearch re.e* -> objects beginning with an e in module re |
|
669 | %psearch re.e* -> objects beginning with an e in module re | |
670 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
670 | %psearch r*.e* -> objects that start with e in modules starting in r | |
671 | %psearch r*.* string -> all strings in modules beginning with r |
|
671 | %psearch r*.* string -> all strings in modules beginning with r | |
672 |
|
672 | |||
673 | Case sensitve search: |
|
673 | Case sensitve search: | |
674 |
|
674 | |||
675 | %psearch -c a* list all object beginning with lower case a |
|
675 | %psearch -c a* list all object beginning with lower case a | |
676 |
|
676 | |||
677 | Show objects beginning with a single _: |
|
677 | Show objects beginning with a single _: | |
678 |
|
678 | |||
679 | %psearch -a _* list objects beginning with a single underscore""" |
|
679 | %psearch -a _* list objects beginning with a single underscore""" | |
680 | try: |
|
680 | try: | |
681 | parameter_s = parameter_s.encode('ascii') |
|
681 | parameter_s = parameter_s.encode('ascii') | |
682 | except UnicodeEncodeError: |
|
682 | except UnicodeEncodeError: | |
683 | print 'Python identifiers can only contain ascii characters.' |
|
683 | print 'Python identifiers can only contain ascii characters.' | |
684 | return |
|
684 | return | |
685 |
|
685 | |||
686 | # default namespaces to be searched |
|
686 | # default namespaces to be searched | |
687 | def_search = ['user','builtin'] |
|
687 | def_search = ['user','builtin'] | |
688 |
|
688 | |||
689 | # Process options/args |
|
689 | # Process options/args | |
690 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
690 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
691 | opt = opts.get |
|
691 | opt = opts.get | |
692 | shell = self.shell |
|
692 | shell = self.shell | |
693 | psearch = shell.inspector.psearch |
|
693 | psearch = shell.inspector.psearch | |
694 |
|
694 | |||
695 | # select case options |
|
695 | # select case options | |
696 | if opts.has_key('i'): |
|
696 | if opts.has_key('i'): | |
697 | ignore_case = True |
|
697 | ignore_case = True | |
698 | elif opts.has_key('c'): |
|
698 | elif opts.has_key('c'): | |
699 | ignore_case = False |
|
699 | ignore_case = False | |
700 | else: |
|
700 | else: | |
701 | ignore_case = not shell.wildcards_case_sensitive |
|
701 | ignore_case = not shell.wildcards_case_sensitive | |
702 |
|
702 | |||
703 | # Build list of namespaces to search from user options |
|
703 | # Build list of namespaces to search from user options | |
704 | def_search.extend(opt('s',[])) |
|
704 | def_search.extend(opt('s',[])) | |
705 | ns_exclude = ns_exclude=opt('e',[]) |
|
705 | ns_exclude = ns_exclude=opt('e',[]) | |
706 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
706 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
707 |
|
707 | |||
708 | # Call the actual search |
|
708 | # Call the actual search | |
709 | try: |
|
709 | try: | |
710 | psearch(args,shell.ns_table,ns_search, |
|
710 | psearch(args,shell.ns_table,ns_search, | |
711 | show_all=opt('a'),ignore_case=ignore_case) |
|
711 | show_all=opt('a'),ignore_case=ignore_case) | |
712 | except: |
|
712 | except: | |
713 | shell.showtraceback() |
|
713 | shell.showtraceback() | |
714 |
|
714 | |||
715 | @skip_doctest |
|
715 | @skip_doctest | |
716 | def magic_who_ls(self, parameter_s=''): |
|
716 | def magic_who_ls(self, parameter_s=''): | |
717 | """Return a sorted list of all interactive variables. |
|
717 | """Return a sorted list of all interactive variables. | |
718 |
|
718 | |||
719 | If arguments are given, only variables of types matching these |
|
719 | If arguments are given, only variables of types matching these | |
720 | arguments are returned. |
|
720 | arguments are returned. | |
721 |
|
721 | |||
722 | Examples |
|
722 | Examples | |
723 | -------- |
|
723 | -------- | |
724 |
|
724 | |||
725 | Define two variables and list them with who_ls:: |
|
725 | Define two variables and list them with who_ls:: | |
726 |
|
726 | |||
727 | In [1]: alpha = 123 |
|
727 | In [1]: alpha = 123 | |
728 |
|
728 | |||
729 | In [2]: beta = 'test' |
|
729 | In [2]: beta = 'test' | |
730 |
|
730 | |||
731 | In [3]: %who_ls |
|
731 | In [3]: %who_ls | |
732 | Out[3]: ['alpha', 'beta'] |
|
732 | Out[3]: ['alpha', 'beta'] | |
733 |
|
733 | |||
734 | In [4]: %who_ls int |
|
734 | In [4]: %who_ls int | |
735 | Out[4]: ['alpha'] |
|
735 | Out[4]: ['alpha'] | |
736 |
|
736 | |||
737 | In [5]: %who_ls str |
|
737 | In [5]: %who_ls str | |
738 | Out[5]: ['beta'] |
|
738 | Out[5]: ['beta'] | |
739 | """ |
|
739 | """ | |
740 |
|
740 | |||
741 | user_ns = self.shell.user_ns |
|
741 | user_ns = self.shell.user_ns | |
742 | internal_ns = self.shell.internal_ns |
|
742 | internal_ns = self.shell.internal_ns | |
743 | user_ns_hidden = self.shell.user_ns_hidden |
|
743 | user_ns_hidden = self.shell.user_ns_hidden | |
744 | out = [ i for i in user_ns |
|
744 | out = [ i for i in user_ns | |
745 | if not i.startswith('_') \ |
|
745 | if not i.startswith('_') \ | |
746 | and not (i in internal_ns or i in user_ns_hidden) ] |
|
746 | and not (i in internal_ns or i in user_ns_hidden) ] | |
747 |
|
747 | |||
748 | typelist = parameter_s.split() |
|
748 | typelist = parameter_s.split() | |
749 | if typelist: |
|
749 | if typelist: | |
750 | typeset = set(typelist) |
|
750 | typeset = set(typelist) | |
751 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] |
|
751 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] | |
752 |
|
752 | |||
753 | out.sort() |
|
753 | out.sort() | |
754 | return out |
|
754 | return out | |
755 |
|
755 | |||
756 | @skip_doctest |
|
756 | @skip_doctest | |
757 | def magic_who(self, parameter_s=''): |
|
757 | def magic_who(self, parameter_s=''): | |
758 | """Print all interactive variables, with some minimal formatting. |
|
758 | """Print all interactive variables, with some minimal formatting. | |
759 |
|
759 | |||
760 | If any arguments are given, only variables whose type matches one of |
|
760 | If any arguments are given, only variables whose type matches one of | |
761 | these are printed. For example: |
|
761 | these are printed. For example: | |
762 |
|
762 | |||
763 | %who function str |
|
763 | %who function str | |
764 |
|
764 | |||
765 | will only list functions and strings, excluding all other types of |
|
765 | will only list functions and strings, excluding all other types of | |
766 | variables. To find the proper type names, simply use type(var) at a |
|
766 | variables. To find the proper type names, simply use type(var) at a | |
767 | command line to see how python prints type names. For example: |
|
767 | command line to see how python prints type names. For example: | |
768 |
|
768 | |||
769 | In [1]: type('hello')\\ |
|
769 | In [1]: type('hello')\\ | |
770 | Out[1]: <type 'str'> |
|
770 | Out[1]: <type 'str'> | |
771 |
|
771 | |||
772 | indicates that the type name for strings is 'str'. |
|
772 | indicates that the type name for strings is 'str'. | |
773 |
|
773 | |||
774 | %who always excludes executed names loaded through your configuration |
|
774 | %who always excludes executed names loaded through your configuration | |
775 | file and things which are internal to IPython. |
|
775 | file and things which are internal to IPython. | |
776 |
|
776 | |||
777 | This is deliberate, as typically you may load many modules and the |
|
777 | This is deliberate, as typically you may load many modules and the | |
778 | purpose of %who is to show you only what you've manually defined. |
|
778 | purpose of %who is to show you only what you've manually defined. | |
779 |
|
779 | |||
780 | Examples |
|
780 | Examples | |
781 | -------- |
|
781 | -------- | |
782 |
|
782 | |||
783 | Define two variables and list them with who:: |
|
783 | Define two variables and list them with who:: | |
784 |
|
784 | |||
785 | In [1]: alpha = 123 |
|
785 | In [1]: alpha = 123 | |
786 |
|
786 | |||
787 | In [2]: beta = 'test' |
|
787 | In [2]: beta = 'test' | |
788 |
|
788 | |||
789 | In [3]: %who |
|
789 | In [3]: %who | |
790 | alpha beta |
|
790 | alpha beta | |
791 |
|
791 | |||
792 | In [4]: %who int |
|
792 | In [4]: %who int | |
793 | alpha |
|
793 | alpha | |
794 |
|
794 | |||
795 | In [5]: %who str |
|
795 | In [5]: %who str | |
796 | beta |
|
796 | beta | |
797 | """ |
|
797 | """ | |
798 |
|
798 | |||
799 | varlist = self.magic_who_ls(parameter_s) |
|
799 | varlist = self.magic_who_ls(parameter_s) | |
800 | if not varlist: |
|
800 | if not varlist: | |
801 | if parameter_s: |
|
801 | if parameter_s: | |
802 | print 'No variables match your requested type.' |
|
802 | print 'No variables match your requested type.' | |
803 | else: |
|
803 | else: | |
804 | print 'Interactive namespace is empty.' |
|
804 | print 'Interactive namespace is empty.' | |
805 | return |
|
805 | return | |
806 |
|
806 | |||
807 | # if we have variables, move on... |
|
807 | # if we have variables, move on... | |
808 | count = 0 |
|
808 | count = 0 | |
809 | for i in varlist: |
|
809 | for i in varlist: | |
810 | print i+'\t', |
|
810 | print i+'\t', | |
811 | count += 1 |
|
811 | count += 1 | |
812 | if count > 8: |
|
812 | if count > 8: | |
813 | count = 0 |
|
813 | count = 0 | |
814 |
|
814 | |||
815 |
|
815 | |||
816 |
|
816 | |||
817 | @skip_doctest |
|
817 | @skip_doctest | |
818 | def magic_whos(self, parameter_s=''): |
|
818 | def magic_whos(self, parameter_s=''): | |
819 | """Like %who, but gives some extra information about each variable. |
|
819 | """Like %who, but gives some extra information about each variable. | |
820 |
|
820 | |||
821 | The same type filtering of %who can be applied here. |
|
821 | The same type filtering of %who can be applied here. | |
822 |
|
822 | |||
823 | For all variables, the type is printed. Additionally it prints: |
|
823 | For all variables, the type is printed. Additionally it prints: | |
824 |
|
824 | |||
825 | - For {},[],(): their length. |
|
825 | - For {},[],(): their length. | |
826 |
|
826 | |||
827 | - For numpy arrays, a summary with shape, number of |
|
827 | - For numpy arrays, a summary with shape, number of | |
828 | elements, typecode and size in memory. |
|
828 | elements, typecode and size in memory. | |
829 |
|
829 | |||
830 | - Everything else: a string representation, snipping their middle if |
|
830 | - Everything else: a string representation, snipping their middle if | |
831 | too long. |
|
831 | too long. | |
832 |
|
832 | |||
833 | Examples |
|
833 | Examples | |
834 | -------- |
|
834 | -------- | |
835 |
|
835 | |||
836 | Define two variables and list them with whos:: |
|
836 | Define two variables and list them with whos:: | |
837 |
|
837 | |||
838 | In [1]: alpha = 123 |
|
838 | In [1]: alpha = 123 | |
839 |
|
839 | |||
840 | In [2]: beta = 'test' |
|
840 | In [2]: beta = 'test' | |
841 |
|
841 | |||
842 | In [3]: %whos |
|
842 | In [3]: %whos | |
843 | Variable Type Data/Info |
|
843 | Variable Type Data/Info | |
844 | -------------------------------- |
|
844 | -------------------------------- | |
845 | alpha int 123 |
|
845 | alpha int 123 | |
846 | beta str test |
|
846 | beta str test | |
847 | """ |
|
847 | """ | |
848 |
|
848 | |||
849 | varnames = self.magic_who_ls(parameter_s) |
|
849 | varnames = self.magic_who_ls(parameter_s) | |
850 | if not varnames: |
|
850 | if not varnames: | |
851 | if parameter_s: |
|
851 | if parameter_s: | |
852 | print 'No variables match your requested type.' |
|
852 | print 'No variables match your requested type.' | |
853 | else: |
|
853 | else: | |
854 | print 'Interactive namespace is empty.' |
|
854 | print 'Interactive namespace is empty.' | |
855 | return |
|
855 | return | |
856 |
|
856 | |||
857 | # if we have variables, move on... |
|
857 | # if we have variables, move on... | |
858 |
|
858 | |||
859 | # for these types, show len() instead of data: |
|
859 | # for these types, show len() instead of data: | |
860 | seq_types = ['dict', 'list', 'tuple'] |
|
860 | seq_types = ['dict', 'list', 'tuple'] | |
861 |
|
861 | |||
862 | # for numpy/Numeric arrays, display summary info |
|
862 | # for numpy/Numeric arrays, display summary info | |
863 | try: |
|
863 | try: | |
864 | import numpy |
|
864 | import numpy | |
865 | except ImportError: |
|
865 | except ImportError: | |
866 | ndarray_type = None |
|
866 | ndarray_type = None | |
867 | else: |
|
867 | else: | |
868 | ndarray_type = numpy.ndarray.__name__ |
|
868 | ndarray_type = numpy.ndarray.__name__ | |
869 | try: |
|
869 | try: | |
870 | import Numeric |
|
870 | import Numeric | |
871 | except ImportError: |
|
871 | except ImportError: | |
872 | array_type = None |
|
872 | array_type = None | |
873 | else: |
|
873 | else: | |
874 | array_type = Numeric.ArrayType.__name__ |
|
874 | array_type = Numeric.ArrayType.__name__ | |
875 |
|
875 | |||
876 | # Find all variable names and types so we can figure out column sizes |
|
876 | # Find all variable names and types so we can figure out column sizes | |
877 | def get_vars(i): |
|
877 | def get_vars(i): | |
878 | return self.shell.user_ns[i] |
|
878 | return self.shell.user_ns[i] | |
879 |
|
879 | |||
880 | # some types are well known and can be shorter |
|
880 | # some types are well known and can be shorter | |
881 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
881 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
882 | def type_name(v): |
|
882 | def type_name(v): | |
883 | tn = type(v).__name__ |
|
883 | tn = type(v).__name__ | |
884 | return abbrevs.get(tn,tn) |
|
884 | return abbrevs.get(tn,tn) | |
885 |
|
885 | |||
886 | varlist = map(get_vars,varnames) |
|
886 | varlist = map(get_vars,varnames) | |
887 |
|
887 | |||
888 | typelist = [] |
|
888 | typelist = [] | |
889 | for vv in varlist: |
|
889 | for vv in varlist: | |
890 | tt = type_name(vv) |
|
890 | tt = type_name(vv) | |
891 |
|
891 | |||
892 | if tt=='instance': |
|
892 | if tt=='instance': | |
893 | typelist.append( abbrevs.get(str(vv.__class__), |
|
893 | typelist.append( abbrevs.get(str(vv.__class__), | |
894 | str(vv.__class__))) |
|
894 | str(vv.__class__))) | |
895 | else: |
|
895 | else: | |
896 | typelist.append(tt) |
|
896 | typelist.append(tt) | |
897 |
|
897 | |||
898 | # column labels and # of spaces as separator |
|
898 | # column labels and # of spaces as separator | |
899 | varlabel = 'Variable' |
|
899 | varlabel = 'Variable' | |
900 | typelabel = 'Type' |
|
900 | typelabel = 'Type' | |
901 | datalabel = 'Data/Info' |
|
901 | datalabel = 'Data/Info' | |
902 | colsep = 3 |
|
902 | colsep = 3 | |
903 | # variable format strings |
|
903 | # variable format strings | |
904 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" |
|
904 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" | |
905 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
905 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
906 | # find the size of the columns to format the output nicely |
|
906 | # find the size of the columns to format the output nicely | |
907 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
907 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
908 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
908 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
909 | # table header |
|
909 | # table header | |
910 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
910 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
911 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
911 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
912 | # and the table itself |
|
912 | # and the table itself | |
913 | kb = 1024 |
|
913 | kb = 1024 | |
914 | Mb = 1048576 # kb**2 |
|
914 | Mb = 1048576 # kb**2 | |
915 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
915 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
916 | print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), |
|
916 | print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), | |
917 | if vtype in seq_types: |
|
917 | if vtype in seq_types: | |
918 | print "n="+str(len(var)) |
|
918 | print "n="+str(len(var)) | |
919 | elif vtype in [array_type,ndarray_type]: |
|
919 | elif vtype in [array_type,ndarray_type]: | |
920 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
920 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
921 | if vtype==ndarray_type: |
|
921 | if vtype==ndarray_type: | |
922 | # numpy |
|
922 | # numpy | |
923 | vsize = var.size |
|
923 | vsize = var.size | |
924 | vbytes = vsize*var.itemsize |
|
924 | vbytes = vsize*var.itemsize | |
925 | vdtype = var.dtype |
|
925 | vdtype = var.dtype | |
926 | else: |
|
926 | else: | |
927 | # Numeric |
|
927 | # Numeric | |
928 | vsize = Numeric.size(var) |
|
928 | vsize = Numeric.size(var) | |
929 | vbytes = vsize*var.itemsize() |
|
929 | vbytes = vsize*var.itemsize() | |
930 | vdtype = var.typecode() |
|
930 | vdtype = var.typecode() | |
931 |
|
931 | |||
932 | if vbytes < 100000: |
|
932 | if vbytes < 100000: | |
933 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
933 | print aformat % (vshape,vsize,vdtype,vbytes) | |
934 | else: |
|
934 | else: | |
935 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
935 | print aformat % (vshape,vsize,vdtype,vbytes), | |
936 | if vbytes < Mb: |
|
936 | if vbytes < Mb: | |
937 | print '(%s kb)' % (vbytes/kb,) |
|
937 | print '(%s kb)' % (vbytes/kb,) | |
938 | else: |
|
938 | else: | |
939 | print '(%s Mb)' % (vbytes/Mb,) |
|
939 | print '(%s Mb)' % (vbytes/Mb,) | |
940 | else: |
|
940 | else: | |
941 | try: |
|
941 | try: | |
942 | vstr = str(var) |
|
942 | vstr = str(var) | |
943 | except UnicodeEncodeError: |
|
943 | except UnicodeEncodeError: | |
944 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
944 | vstr = unicode(var).encode(sys.getdefaultencoding(), | |
945 | 'backslashreplace') |
|
945 | 'backslashreplace') | |
946 | vstr = vstr.replace('\n','\\n') |
|
946 | vstr = vstr.replace('\n','\\n') | |
947 | if len(vstr) < 50: |
|
947 | if len(vstr) < 50: | |
948 | print vstr |
|
948 | print vstr | |
949 | else: |
|
949 | else: | |
950 | print vstr[:25] + "<...>" + vstr[-25:] |
|
950 | print vstr[:25] + "<...>" + vstr[-25:] | |
951 |
|
951 | |||
952 | def magic_reset(self, parameter_s=''): |
|
952 | def magic_reset(self, parameter_s=''): | |
953 | """Resets the namespace by removing all names defined by the user. |
|
953 | """Resets the namespace by removing all names defined by the user. | |
954 |
|
954 | |||
955 | Parameters |
|
955 | Parameters | |
956 | ---------- |
|
956 | ---------- | |
957 | -f : force reset without asking for confirmation. |
|
957 | -f : force reset without asking for confirmation. | |
958 |
|
958 | |||
959 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. |
|
959 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. | |
960 | References to objects may be kept. By default (without this option), |
|
960 | References to objects may be kept. By default (without this option), | |
961 | we do a 'hard' reset, giving you a new session and removing all |
|
961 | we do a 'hard' reset, giving you a new session and removing all | |
962 | references to objects from the current session. |
|
962 | references to objects from the current session. | |
963 |
|
963 | |||
964 | Examples |
|
964 | Examples | |
965 | -------- |
|
965 | -------- | |
966 | In [6]: a = 1 |
|
966 | In [6]: a = 1 | |
967 |
|
967 | |||
968 | In [7]: a |
|
968 | In [7]: a | |
969 | Out[7]: 1 |
|
969 | Out[7]: 1 | |
970 |
|
970 | |||
971 | In [8]: 'a' in _ip.user_ns |
|
971 | In [8]: 'a' in _ip.user_ns | |
972 | Out[8]: True |
|
972 | Out[8]: True | |
973 |
|
973 | |||
974 | In [9]: %reset -f |
|
974 | In [9]: %reset -f | |
975 |
|
975 | |||
976 | In [1]: 'a' in _ip.user_ns |
|
976 | In [1]: 'a' in _ip.user_ns | |
977 | Out[1]: False |
|
977 | Out[1]: False | |
978 | """ |
|
978 | """ | |
979 | opts, args = self.parse_options(parameter_s,'sf') |
|
979 | opts, args = self.parse_options(parameter_s,'sf') | |
980 | if 'f' in opts: |
|
980 | if 'f' in opts: | |
981 | ans = True |
|
981 | ans = True | |
982 | else: |
|
982 | else: | |
983 | ans = self.shell.ask_yes_no( |
|
983 | ans = self.shell.ask_yes_no( | |
984 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
984 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
985 | if not ans: |
|
985 | if not ans: | |
986 | print 'Nothing done.' |
|
986 | print 'Nothing done.' | |
987 | return |
|
987 | return | |
988 |
|
988 | |||
989 | if 's' in opts: # Soft reset |
|
989 | if 's' in opts: # Soft reset | |
990 | user_ns = self.shell.user_ns |
|
990 | user_ns = self.shell.user_ns | |
991 | for i in self.magic_who_ls(): |
|
991 | for i in self.magic_who_ls(): | |
992 | del(user_ns[i]) |
|
992 | del(user_ns[i]) | |
993 |
|
993 | |||
994 | else: # Hard reset |
|
994 | else: # Hard reset | |
995 | self.shell.reset(new_session = False) |
|
995 | self.shell.reset(new_session = False) | |
996 |
|
996 | |||
997 |
|
997 | |||
998 |
|
998 | |||
999 | def magic_reset_selective(self, parameter_s=''): |
|
999 | def magic_reset_selective(self, parameter_s=''): | |
1000 | """Resets the namespace by removing names defined by the user. |
|
1000 | """Resets the namespace by removing names defined by the user. | |
1001 |
|
1001 | |||
1002 | Input/Output history are left around in case you need them. |
|
1002 | Input/Output history are left around in case you need them. | |
1003 |
|
1003 | |||
1004 | %reset_selective [-f] regex |
|
1004 | %reset_selective [-f] regex | |
1005 |
|
1005 | |||
1006 | No action is taken if regex is not included |
|
1006 | No action is taken if regex is not included | |
1007 |
|
1007 | |||
1008 | Options |
|
1008 | Options | |
1009 | -f : force reset without asking for confirmation. |
|
1009 | -f : force reset without asking for confirmation. | |
1010 |
|
1010 | |||
1011 | Examples |
|
1011 | Examples | |
1012 | -------- |
|
1012 | -------- | |
1013 |
|
1013 | |||
1014 | We first fully reset the namespace so your output looks identical to |
|
1014 | We first fully reset the namespace so your output looks identical to | |
1015 | this example for pedagogical reasons; in practice you do not need a |
|
1015 | this example for pedagogical reasons; in practice you do not need a | |
1016 | full reset. |
|
1016 | full reset. | |
1017 |
|
1017 | |||
1018 | In [1]: %reset -f |
|
1018 | In [1]: %reset -f | |
1019 |
|
1019 | |||
1020 | Now, with a clean namespace we can make a few variables and use |
|
1020 | Now, with a clean namespace we can make a few variables and use | |
1021 | %reset_selective to only delete names that match our regexp: |
|
1021 | %reset_selective to only delete names that match our regexp: | |
1022 |
|
1022 | |||
1023 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
1023 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 | |
1024 |
|
1024 | |||
1025 | In [3]: who_ls |
|
1025 | In [3]: who_ls | |
1026 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
1026 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] | |
1027 |
|
1027 | |||
1028 | In [4]: %reset_selective -f b[2-3]m |
|
1028 | In [4]: %reset_selective -f b[2-3]m | |
1029 |
|
1029 | |||
1030 | In [5]: who_ls |
|
1030 | In [5]: who_ls | |
1031 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1031 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
1032 |
|
1032 | |||
1033 | In [6]: %reset_selective -f d |
|
1033 | In [6]: %reset_selective -f d | |
1034 |
|
1034 | |||
1035 | In [7]: who_ls |
|
1035 | In [7]: who_ls | |
1036 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1036 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
1037 |
|
1037 | |||
1038 | In [8]: %reset_selective -f c |
|
1038 | In [8]: %reset_selective -f c | |
1039 |
|
1039 | |||
1040 | In [9]: who_ls |
|
1040 | In [9]: who_ls | |
1041 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
1041 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] | |
1042 |
|
1042 | |||
1043 | In [10]: %reset_selective -f b |
|
1043 | In [10]: %reset_selective -f b | |
1044 |
|
1044 | |||
1045 | In [11]: who_ls |
|
1045 | In [11]: who_ls | |
1046 | Out[11]: ['a'] |
|
1046 | Out[11]: ['a'] | |
1047 | """ |
|
1047 | """ | |
1048 |
|
1048 | |||
1049 | opts, regex = self.parse_options(parameter_s,'f') |
|
1049 | opts, regex = self.parse_options(parameter_s,'f') | |
1050 |
|
1050 | |||
1051 | if opts.has_key('f'): |
|
1051 | if opts.has_key('f'): | |
1052 | ans = True |
|
1052 | ans = True | |
1053 | else: |
|
1053 | else: | |
1054 | ans = self.shell.ask_yes_no( |
|
1054 | ans = self.shell.ask_yes_no( | |
1055 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1055 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1056 | if not ans: |
|
1056 | if not ans: | |
1057 | print 'Nothing done.' |
|
1057 | print 'Nothing done.' | |
1058 | return |
|
1058 | return | |
1059 | user_ns = self.shell.user_ns |
|
1059 | user_ns = self.shell.user_ns | |
1060 | if not regex: |
|
1060 | if not regex: | |
1061 | print 'No regex pattern specified. Nothing done.' |
|
1061 | print 'No regex pattern specified. Nothing done.' | |
1062 | return |
|
1062 | return | |
1063 | else: |
|
1063 | else: | |
1064 | try: |
|
1064 | try: | |
1065 | m = re.compile(regex) |
|
1065 | m = re.compile(regex) | |
1066 | except TypeError: |
|
1066 | except TypeError: | |
1067 | raise TypeError('regex must be a string or compiled pattern') |
|
1067 | raise TypeError('regex must be a string or compiled pattern') | |
1068 | for i in self.magic_who_ls(): |
|
1068 | for i in self.magic_who_ls(): | |
1069 | if m.search(i): |
|
1069 | if m.search(i): | |
1070 | del(user_ns[i]) |
|
1070 | del(user_ns[i]) | |
1071 |
|
1071 | |||
1072 | def magic_xdel(self, parameter_s=''): |
|
1072 | def magic_xdel(self, parameter_s=''): | |
1073 | """Delete a variable, trying to clear it from anywhere that |
|
1073 | """Delete a variable, trying to clear it from anywhere that | |
1074 | IPython's machinery has references to it. By default, this uses |
|
1074 | IPython's machinery has references to it. By default, this uses | |
1075 | the identity of the named object in the user namespace to remove |
|
1075 | the identity of the named object in the user namespace to remove | |
1076 | references held under other names. The object is also removed |
|
1076 | references held under other names. The object is also removed | |
1077 | from the output history. |
|
1077 | from the output history. | |
1078 |
|
1078 | |||
1079 | Options |
|
1079 | Options | |
1080 | -n : Delete the specified name from all namespaces, without |
|
1080 | -n : Delete the specified name from all namespaces, without | |
1081 | checking their identity. |
|
1081 | checking their identity. | |
1082 | """ |
|
1082 | """ | |
1083 | opts, varname = self.parse_options(parameter_s,'n') |
|
1083 | opts, varname = self.parse_options(parameter_s,'n') | |
1084 | try: |
|
1084 | try: | |
1085 | self.shell.del_var(varname, ('n' in opts)) |
|
1085 | self.shell.del_var(varname, ('n' in opts)) | |
1086 | except (NameError, ValueError) as e: |
|
1086 | except (NameError, ValueError) as e: | |
1087 | print type(e).__name__ +": "+ str(e) |
|
1087 | print type(e).__name__ +": "+ str(e) | |
1088 |
|
1088 | |||
1089 | def magic_logstart(self,parameter_s=''): |
|
1089 | def magic_logstart(self,parameter_s=''): | |
1090 | """Start logging anywhere in a session. |
|
1090 | """Start logging anywhere in a session. | |
1091 |
|
1091 | |||
1092 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1092 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1093 |
|
1093 | |||
1094 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1094 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1095 | current directory, in 'rotate' mode (see below). |
|
1095 | current directory, in 'rotate' mode (see below). | |
1096 |
|
1096 | |||
1097 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1097 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1098 | history up to that point and then continues logging. |
|
1098 | history up to that point and then continues logging. | |
1099 |
|
1099 | |||
1100 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1100 | %logstart takes a second optional parameter: logging mode. This can be one | |
1101 | of (note that the modes are given unquoted):\\ |
|
1101 | of (note that the modes are given unquoted):\\ | |
1102 | append: well, that says it.\\ |
|
1102 | append: well, that says it.\\ | |
1103 | backup: rename (if exists) to name~ and start name.\\ |
|
1103 | backup: rename (if exists) to name~ and start name.\\ | |
1104 | global: single logfile in your home dir, appended to.\\ |
|
1104 | global: single logfile in your home dir, appended to.\\ | |
1105 | over : overwrite existing log.\\ |
|
1105 | over : overwrite existing log.\\ | |
1106 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1106 | rotate: create rotating logs name.1~, name.2~, etc. | |
1107 |
|
1107 | |||
1108 | Options: |
|
1108 | Options: | |
1109 |
|
1109 | |||
1110 | -o: log also IPython's output. In this mode, all commands which |
|
1110 | -o: log also IPython's output. In this mode, all commands which | |
1111 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1111 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1112 | their corresponding input line. The output lines are always |
|
1112 | their corresponding input line. The output lines are always | |
1113 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1113 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1114 | Python code. |
|
1114 | Python code. | |
1115 |
|
1115 | |||
1116 | Since this marker is always the same, filtering only the output from |
|
1116 | Since this marker is always the same, filtering only the output from | |
1117 | a log is very easy, using for example a simple awk call: |
|
1117 | a log is very easy, using for example a simple awk call: | |
1118 |
|
1118 | |||
1119 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1119 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1120 |
|
1120 | |||
1121 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1121 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1122 | input, so that user lines are logged in their final form, converted |
|
1122 | input, so that user lines are logged in their final form, converted | |
1123 | into valid Python. For example, %Exit is logged as |
|
1123 | into valid Python. For example, %Exit is logged as | |
1124 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1124 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
1125 | exactly as typed, with no transformations applied. |
|
1125 | exactly as typed, with no transformations applied. | |
1126 |
|
1126 | |||
1127 | -t: put timestamps before each input line logged (these are put in |
|
1127 | -t: put timestamps before each input line logged (these are put in | |
1128 | comments).""" |
|
1128 | comments).""" | |
1129 |
|
1129 | |||
1130 | opts,par = self.parse_options(parameter_s,'ort') |
|
1130 | opts,par = self.parse_options(parameter_s,'ort') | |
1131 | log_output = 'o' in opts |
|
1131 | log_output = 'o' in opts | |
1132 | log_raw_input = 'r' in opts |
|
1132 | log_raw_input = 'r' in opts | |
1133 | timestamp = 't' in opts |
|
1133 | timestamp = 't' in opts | |
1134 |
|
1134 | |||
1135 | logger = self.shell.logger |
|
1135 | logger = self.shell.logger | |
1136 |
|
1136 | |||
1137 | # if no args are given, the defaults set in the logger constructor by |
|
1137 | # if no args are given, the defaults set in the logger constructor by | |
1138 | # ipytohn remain valid |
|
1138 | # ipytohn remain valid | |
1139 | if par: |
|
1139 | if par: | |
1140 | try: |
|
1140 | try: | |
1141 | logfname,logmode = par.split() |
|
1141 | logfname,logmode = par.split() | |
1142 | except: |
|
1142 | except: | |
1143 | logfname = par |
|
1143 | logfname = par | |
1144 | logmode = 'backup' |
|
1144 | logmode = 'backup' | |
1145 | else: |
|
1145 | else: | |
1146 | logfname = logger.logfname |
|
1146 | logfname = logger.logfname | |
1147 | logmode = logger.logmode |
|
1147 | logmode = logger.logmode | |
1148 | # put logfname into rc struct as if it had been called on the command |
|
1148 | # put logfname into rc struct as if it had been called on the command | |
1149 | # line, so it ends up saved in the log header Save it in case we need |
|
1149 | # line, so it ends up saved in the log header Save it in case we need | |
1150 | # to restore it... |
|
1150 | # to restore it... | |
1151 | old_logfile = self.shell.logfile |
|
1151 | old_logfile = self.shell.logfile | |
1152 | if logfname: |
|
1152 | if logfname: | |
1153 | logfname = os.path.expanduser(logfname) |
|
1153 | logfname = os.path.expanduser(logfname) | |
1154 | self.shell.logfile = logfname |
|
1154 | self.shell.logfile = logfname | |
1155 |
|
1155 | |||
1156 | loghead = '# IPython log file\n\n' |
|
1156 | loghead = '# IPython log file\n\n' | |
1157 | try: |
|
1157 | try: | |
1158 | started = logger.logstart(logfname,loghead,logmode, |
|
1158 | started = logger.logstart(logfname,loghead,logmode, | |
1159 | log_output,timestamp,log_raw_input) |
|
1159 | log_output,timestamp,log_raw_input) | |
1160 | except: |
|
1160 | except: | |
1161 | self.shell.logfile = old_logfile |
|
1161 | self.shell.logfile = old_logfile | |
1162 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1162 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1163 | else: |
|
1163 | else: | |
1164 | # log input history up to this point, optionally interleaving |
|
1164 | # log input history up to this point, optionally interleaving | |
1165 | # output if requested |
|
1165 | # output if requested | |
1166 |
|
1166 | |||
1167 | if timestamp: |
|
1167 | if timestamp: | |
1168 | # disable timestamping for the previous history, since we've |
|
1168 | # disable timestamping for the previous history, since we've | |
1169 | # lost those already (no time machine here). |
|
1169 | # lost those already (no time machine here). | |
1170 | logger.timestamp = False |
|
1170 | logger.timestamp = False | |
1171 |
|
1171 | |||
1172 | if log_raw_input: |
|
1172 | if log_raw_input: | |
1173 | input_hist = self.shell.history_manager.input_hist_raw |
|
1173 | input_hist = self.shell.history_manager.input_hist_raw | |
1174 | else: |
|
1174 | else: | |
1175 | input_hist = self.shell.history_manager.input_hist_parsed |
|
1175 | input_hist = self.shell.history_manager.input_hist_parsed | |
1176 |
|
1176 | |||
1177 | if log_output: |
|
1177 | if log_output: | |
1178 | log_write = logger.log_write |
|
1178 | log_write = logger.log_write | |
1179 | output_hist = self.shell.history_manager.output_hist |
|
1179 | output_hist = self.shell.history_manager.output_hist | |
1180 | for n in range(1,len(input_hist)-1): |
|
1180 | for n in range(1,len(input_hist)-1): | |
1181 | log_write(input_hist[n].rstrip() + '\n') |
|
1181 | log_write(input_hist[n].rstrip() + '\n') | |
1182 | if n in output_hist: |
|
1182 | if n in output_hist: | |
1183 | log_write(repr(output_hist[n]),'output') |
|
1183 | log_write(repr(output_hist[n]),'output') | |
1184 | else: |
|
1184 | else: | |
1185 | logger.log_write('\n'.join(input_hist[1:])) |
|
1185 | logger.log_write('\n'.join(input_hist[1:])) | |
1186 | logger.log_write('\n') |
|
1186 | logger.log_write('\n') | |
1187 | if timestamp: |
|
1187 | if timestamp: | |
1188 | # re-enable timestamping |
|
1188 | # re-enable timestamping | |
1189 | logger.timestamp = True |
|
1189 | logger.timestamp = True | |
1190 |
|
1190 | |||
1191 | print ('Activating auto-logging. ' |
|
1191 | print ('Activating auto-logging. ' | |
1192 | 'Current session state plus future input saved.') |
|
1192 | 'Current session state plus future input saved.') | |
1193 | logger.logstate() |
|
1193 | logger.logstate() | |
1194 |
|
1194 | |||
1195 | def magic_logstop(self,parameter_s=''): |
|
1195 | def magic_logstop(self,parameter_s=''): | |
1196 | """Fully stop logging and close log file. |
|
1196 | """Fully stop logging and close log file. | |
1197 |
|
1197 | |||
1198 | In order to start logging again, a new %logstart call needs to be made, |
|
1198 | In order to start logging again, a new %logstart call needs to be made, | |
1199 | possibly (though not necessarily) with a new filename, mode and other |
|
1199 | possibly (though not necessarily) with a new filename, mode and other | |
1200 | options.""" |
|
1200 | options.""" | |
1201 | self.logger.logstop() |
|
1201 | self.logger.logstop() | |
1202 |
|
1202 | |||
1203 | def magic_logoff(self,parameter_s=''): |
|
1203 | def magic_logoff(self,parameter_s=''): | |
1204 | """Temporarily stop logging. |
|
1204 | """Temporarily stop logging. | |
1205 |
|
1205 | |||
1206 | You must have previously started logging.""" |
|
1206 | You must have previously started logging.""" | |
1207 | self.shell.logger.switch_log(0) |
|
1207 | self.shell.logger.switch_log(0) | |
1208 |
|
1208 | |||
1209 | def magic_logon(self,parameter_s=''): |
|
1209 | def magic_logon(self,parameter_s=''): | |
1210 | """Restart logging. |
|
1210 | """Restart logging. | |
1211 |
|
1211 | |||
1212 | This function is for restarting logging which you've temporarily |
|
1212 | This function is for restarting logging which you've temporarily | |
1213 | stopped with %logoff. For starting logging for the first time, you |
|
1213 | stopped with %logoff. For starting logging for the first time, you | |
1214 | must use the %logstart function, which allows you to specify an |
|
1214 | must use the %logstart function, which allows you to specify an | |
1215 | optional log filename.""" |
|
1215 | optional log filename.""" | |
1216 |
|
1216 | |||
1217 | self.shell.logger.switch_log(1) |
|
1217 | self.shell.logger.switch_log(1) | |
1218 |
|
1218 | |||
1219 | def magic_logstate(self,parameter_s=''): |
|
1219 | def magic_logstate(self,parameter_s=''): | |
1220 | """Print the status of the logging system.""" |
|
1220 | """Print the status of the logging system.""" | |
1221 |
|
1221 | |||
1222 | self.shell.logger.logstate() |
|
1222 | self.shell.logger.logstate() | |
1223 |
|
1223 | |||
1224 | def magic_pdb(self, parameter_s=''): |
|
1224 | def magic_pdb(self, parameter_s=''): | |
1225 | """Control the automatic calling of the pdb interactive debugger. |
|
1225 | """Control the automatic calling of the pdb interactive debugger. | |
1226 |
|
1226 | |||
1227 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1227 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1228 | argument it works as a toggle. |
|
1228 | argument it works as a toggle. | |
1229 |
|
1229 | |||
1230 | When an exception is triggered, IPython can optionally call the |
|
1230 | When an exception is triggered, IPython can optionally call the | |
1231 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1231 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1232 | this feature on and off. |
|
1232 | this feature on and off. | |
1233 |
|
1233 | |||
1234 | The initial state of this feature is set in your ipythonrc |
|
1234 | The initial state of this feature is set in your ipythonrc | |
1235 | configuration file (the variable is called 'pdb'). |
|
1235 | configuration file (the variable is called 'pdb'). | |
1236 |
|
1236 | |||
1237 | If you want to just activate the debugger AFTER an exception has fired, |
|
1237 | If you want to just activate the debugger AFTER an exception has fired, | |
1238 | without having to type '%pdb on' and rerunning your code, you can use |
|
1238 | without having to type '%pdb on' and rerunning your code, you can use | |
1239 | the %debug magic.""" |
|
1239 | the %debug magic.""" | |
1240 |
|
1240 | |||
1241 | par = parameter_s.strip().lower() |
|
1241 | par = parameter_s.strip().lower() | |
1242 |
|
1242 | |||
1243 | if par: |
|
1243 | if par: | |
1244 | try: |
|
1244 | try: | |
1245 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1245 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1246 | except KeyError: |
|
1246 | except KeyError: | |
1247 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1247 | print ('Incorrect argument. Use on/1, off/0, ' | |
1248 | 'or nothing for a toggle.') |
|
1248 | 'or nothing for a toggle.') | |
1249 | return |
|
1249 | return | |
1250 | else: |
|
1250 | else: | |
1251 | # toggle |
|
1251 | # toggle | |
1252 | new_pdb = not self.shell.call_pdb |
|
1252 | new_pdb = not self.shell.call_pdb | |
1253 |
|
1253 | |||
1254 | # set on the shell |
|
1254 | # set on the shell | |
1255 | self.shell.call_pdb = new_pdb |
|
1255 | self.shell.call_pdb = new_pdb | |
1256 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1256 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1257 |
|
1257 | |||
1258 | def magic_debug(self, parameter_s=''): |
|
1258 | def magic_debug(self, parameter_s=''): | |
1259 | """Activate the interactive debugger in post-mortem mode. |
|
1259 | """Activate the interactive debugger in post-mortem mode. | |
1260 |
|
1260 | |||
1261 | If an exception has just occurred, this lets you inspect its stack |
|
1261 | If an exception has just occurred, this lets you inspect its stack | |
1262 | frames interactively. Note that this will always work only on the last |
|
1262 | frames interactively. Note that this will always work only on the last | |
1263 | traceback that occurred, so you must call this quickly after an |
|
1263 | traceback that occurred, so you must call this quickly after an | |
1264 | exception that you wish to inspect has fired, because if another one |
|
1264 | exception that you wish to inspect has fired, because if another one | |
1265 | occurs, it clobbers the previous one. |
|
1265 | occurs, it clobbers the previous one. | |
1266 |
|
1266 | |||
1267 | If you want IPython to automatically do this on every exception, see |
|
1267 | If you want IPython to automatically do this on every exception, see | |
1268 | the %pdb magic for more details. |
|
1268 | the %pdb magic for more details. | |
1269 | """ |
|
1269 | """ | |
1270 | self.shell.debugger(force=True) |
|
1270 | self.shell.debugger(force=True) | |
1271 |
|
1271 | |||
1272 | @skip_doctest |
|
1272 | @skip_doctest | |
1273 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1273 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1274 | opts=None,arg_lst=None,prog_ns=None): |
|
1274 | opts=None,arg_lst=None,prog_ns=None): | |
1275 |
|
1275 | |||
1276 | """Run a statement through the python code profiler. |
|
1276 | """Run a statement through the python code profiler. | |
1277 |
|
1277 | |||
1278 | Usage: |
|
1278 | Usage: | |
1279 | %prun [options] statement |
|
1279 | %prun [options] statement | |
1280 |
|
1280 | |||
1281 | The given statement (which doesn't require quote marks) is run via the |
|
1281 | The given statement (which doesn't require quote marks) is run via the | |
1282 | python profiler in a manner similar to the profile.run() function. |
|
1282 | python profiler in a manner similar to the profile.run() function. | |
1283 | Namespaces are internally managed to work correctly; profile.run |
|
1283 | Namespaces are internally managed to work correctly; profile.run | |
1284 | cannot be used in IPython because it makes certain assumptions about |
|
1284 | cannot be used in IPython because it makes certain assumptions about | |
1285 | namespaces which do not hold under IPython. |
|
1285 | namespaces which do not hold under IPython. | |
1286 |
|
1286 | |||
1287 | Options: |
|
1287 | Options: | |
1288 |
|
1288 | |||
1289 | -l <limit>: you can place restrictions on what or how much of the |
|
1289 | -l <limit>: you can place restrictions on what or how much of the | |
1290 | profile gets printed. The limit value can be: |
|
1290 | profile gets printed. The limit value can be: | |
1291 |
|
1291 | |||
1292 | * A string: only information for function names containing this string |
|
1292 | * A string: only information for function names containing this string | |
1293 | is printed. |
|
1293 | is printed. | |
1294 |
|
1294 | |||
1295 | * An integer: only these many lines are printed. |
|
1295 | * An integer: only these many lines are printed. | |
1296 |
|
1296 | |||
1297 | * A float (between 0 and 1): this fraction of the report is printed |
|
1297 | * A float (between 0 and 1): this fraction of the report is printed | |
1298 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1298 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1299 |
|
1299 | |||
1300 | You can combine several limits with repeated use of the option. For |
|
1300 | You can combine several limits with repeated use of the option. For | |
1301 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1301 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1302 | information about class constructors. |
|
1302 | information about class constructors. | |
1303 |
|
1303 | |||
1304 | -r: return the pstats.Stats object generated by the profiling. This |
|
1304 | -r: return the pstats.Stats object generated by the profiling. This | |
1305 | object has all the information about the profile in it, and you can |
|
1305 | object has all the information about the profile in it, and you can | |
1306 | later use it for further analysis or in other functions. |
|
1306 | later use it for further analysis or in other functions. | |
1307 |
|
1307 | |||
1308 | -s <key>: sort profile by given key. You can provide more than one key |
|
1308 | -s <key>: sort profile by given key. You can provide more than one key | |
1309 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1309 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1310 | default sorting key is 'time'. |
|
1310 | default sorting key is 'time'. | |
1311 |
|
1311 | |||
1312 | The following is copied verbatim from the profile documentation |
|
1312 | The following is copied verbatim from the profile documentation | |
1313 | referenced below: |
|
1313 | referenced below: | |
1314 |
|
1314 | |||
1315 | When more than one key is provided, additional keys are used as |
|
1315 | When more than one key is provided, additional keys are used as | |
1316 | secondary criteria when the there is equality in all keys selected |
|
1316 | secondary criteria when the there is equality in all keys selected | |
1317 | before them. |
|
1317 | before them. | |
1318 |
|
1318 | |||
1319 | Abbreviations can be used for any key names, as long as the |
|
1319 | Abbreviations can be used for any key names, as long as the | |
1320 | abbreviation is unambiguous. The following are the keys currently |
|
1320 | abbreviation is unambiguous. The following are the keys currently | |
1321 | defined: |
|
1321 | defined: | |
1322 |
|
1322 | |||
1323 | Valid Arg Meaning |
|
1323 | Valid Arg Meaning | |
1324 | "calls" call count |
|
1324 | "calls" call count | |
1325 | "cumulative" cumulative time |
|
1325 | "cumulative" cumulative time | |
1326 | "file" file name |
|
1326 | "file" file name | |
1327 | "module" file name |
|
1327 | "module" file name | |
1328 | "pcalls" primitive call count |
|
1328 | "pcalls" primitive call count | |
1329 | "line" line number |
|
1329 | "line" line number | |
1330 | "name" function name |
|
1330 | "name" function name | |
1331 | "nfl" name/file/line |
|
1331 | "nfl" name/file/line | |
1332 | "stdname" standard name |
|
1332 | "stdname" standard name | |
1333 | "time" internal time |
|
1333 | "time" internal time | |
1334 |
|
1334 | |||
1335 | Note that all sorts on statistics are in descending order (placing |
|
1335 | Note that all sorts on statistics are in descending order (placing | |
1336 | most time consuming items first), where as name, file, and line number |
|
1336 | most time consuming items first), where as name, file, and line number | |
1337 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1337 | searches are in ascending order (i.e., alphabetical). The subtle | |
1338 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1338 | distinction between "nfl" and "stdname" is that the standard name is a | |
1339 | sort of the name as printed, which means that the embedded line |
|
1339 | sort of the name as printed, which means that the embedded line | |
1340 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1340 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1341 | would (if the file names were the same) appear in the string order |
|
1341 | would (if the file names were the same) appear in the string order | |
1342 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1342 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1343 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1343 | line numbers. In fact, sort_stats("nfl") is the same as | |
1344 | sort_stats("name", "file", "line"). |
|
1344 | sort_stats("name", "file", "line"). | |
1345 |
|
1345 | |||
1346 | -T <filename>: save profile results as shown on screen to a text |
|
1346 | -T <filename>: save profile results as shown on screen to a text | |
1347 | file. The profile is still shown on screen. |
|
1347 | file. The profile is still shown on screen. | |
1348 |
|
1348 | |||
1349 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1349 | -D <filename>: save (via dump_stats) profile statistics to given | |
1350 | filename. This data is in a format understod by the pstats module, and |
|
1350 | filename. This data is in a format understod by the pstats module, and | |
1351 | is generated by a call to the dump_stats() method of profile |
|
1351 | is generated by a call to the dump_stats() method of profile | |
1352 | objects. The profile is still shown on screen. |
|
1352 | objects. The profile is still shown on screen. | |
1353 |
|
1353 | |||
1354 | If you want to run complete programs under the profiler's control, use |
|
1354 | If you want to run complete programs under the profiler's control, use | |
1355 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1355 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1356 | contains profiler specific options as described here. |
|
1356 | contains profiler specific options as described here. | |
1357 |
|
1357 | |||
1358 | You can read the complete documentation for the profile module with:: |
|
1358 | You can read the complete documentation for the profile module with:: | |
1359 |
|
1359 | |||
1360 | In [1]: import profile; profile.help() |
|
1360 | In [1]: import profile; profile.help() | |
1361 | """ |
|
1361 | """ | |
1362 |
|
1362 | |||
1363 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1363 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1364 | # protect user quote marks |
|
1364 | # protect user quote marks | |
1365 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1365 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1366 |
|
1366 | |||
1367 | if user_mode: # regular user call |
|
1367 | if user_mode: # regular user call | |
1368 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1368 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1369 | list_all=1) |
|
1369 | list_all=1) | |
1370 | namespace = self.shell.user_ns |
|
1370 | namespace = self.shell.user_ns | |
1371 | else: # called to run a program by %run -p |
|
1371 | else: # called to run a program by %run -p | |
1372 | try: |
|
1372 | try: | |
1373 | filename = get_py_filename(arg_lst[0]) |
|
1373 | filename = get_py_filename(arg_lst[0]) | |
1374 | except IOError,msg: |
|
1374 | except IOError,msg: | |
1375 | error(msg) |
|
1375 | error(msg) | |
1376 | return |
|
1376 | return | |
1377 |
|
1377 | |||
1378 | arg_str = 'execfile(filename,prog_ns)' |
|
1378 | arg_str = 'execfile(filename,prog_ns)' | |
1379 | namespace = locals() |
|
1379 | namespace = locals() | |
1380 |
|
1380 | |||
1381 | opts.merge(opts_def) |
|
1381 | opts.merge(opts_def) | |
1382 |
|
1382 | |||
1383 | prof = profile.Profile() |
|
1383 | prof = profile.Profile() | |
1384 | try: |
|
1384 | try: | |
1385 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1385 | prof = prof.runctx(arg_str,namespace,namespace) | |
1386 | sys_exit = '' |
|
1386 | sys_exit = '' | |
1387 | except SystemExit: |
|
1387 | except SystemExit: | |
1388 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1388 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1389 |
|
1389 | |||
1390 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1390 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1391 |
|
1391 | |||
1392 | lims = opts.l |
|
1392 | lims = opts.l | |
1393 | if lims: |
|
1393 | if lims: | |
1394 | lims = [] # rebuild lims with ints/floats/strings |
|
1394 | lims = [] # rebuild lims with ints/floats/strings | |
1395 | for lim in opts.l: |
|
1395 | for lim in opts.l: | |
1396 | try: |
|
1396 | try: | |
1397 | lims.append(int(lim)) |
|
1397 | lims.append(int(lim)) | |
1398 | except ValueError: |
|
1398 | except ValueError: | |
1399 | try: |
|
1399 | try: | |
1400 | lims.append(float(lim)) |
|
1400 | lims.append(float(lim)) | |
1401 | except ValueError: |
|
1401 | except ValueError: | |
1402 | lims.append(lim) |
|
1402 | lims.append(lim) | |
1403 |
|
1403 | |||
1404 | # Trap output. |
|
1404 | # Trap output. | |
1405 | stdout_trap = StringIO() |
|
1405 | stdout_trap = StringIO() | |
1406 |
|
1406 | |||
1407 | if hasattr(stats,'stream'): |
|
1407 | if hasattr(stats,'stream'): | |
1408 | # In newer versions of python, the stats object has a 'stream' |
|
1408 | # In newer versions of python, the stats object has a 'stream' | |
1409 | # attribute to write into. |
|
1409 | # attribute to write into. | |
1410 | stats.stream = stdout_trap |
|
1410 | stats.stream = stdout_trap | |
1411 | stats.print_stats(*lims) |
|
1411 | stats.print_stats(*lims) | |
1412 | else: |
|
1412 | else: | |
1413 | # For older versions, we manually redirect stdout during printing |
|
1413 | # For older versions, we manually redirect stdout during printing | |
1414 | sys_stdout = sys.stdout |
|
1414 | sys_stdout = sys.stdout | |
1415 | try: |
|
1415 | try: | |
1416 | sys.stdout = stdout_trap |
|
1416 | sys.stdout = stdout_trap | |
1417 | stats.print_stats(*lims) |
|
1417 | stats.print_stats(*lims) | |
1418 | finally: |
|
1418 | finally: | |
1419 | sys.stdout = sys_stdout |
|
1419 | sys.stdout = sys_stdout | |
1420 |
|
1420 | |||
1421 | output = stdout_trap.getvalue() |
|
1421 | output = stdout_trap.getvalue() | |
1422 | output = output.rstrip() |
|
1422 | output = output.rstrip() | |
1423 |
|
1423 | |||
1424 | page.page(output) |
|
1424 | page.page(output) | |
1425 | print sys_exit, |
|
1425 | print sys_exit, | |
1426 |
|
1426 | |||
1427 | dump_file = opts.D[0] |
|
1427 | dump_file = opts.D[0] | |
1428 | text_file = opts.T[0] |
|
1428 | text_file = opts.T[0] | |
1429 | if dump_file: |
|
1429 | if dump_file: | |
1430 | prof.dump_stats(dump_file) |
|
1430 | prof.dump_stats(dump_file) | |
1431 | print '\n*** Profile stats marshalled to file',\ |
|
1431 | print '\n*** Profile stats marshalled to file',\ | |
1432 | `dump_file`+'.',sys_exit |
|
1432 | `dump_file`+'.',sys_exit | |
1433 | if text_file: |
|
1433 | if text_file: | |
1434 | pfile = file(text_file,'w') |
|
1434 | pfile = file(text_file,'w') | |
1435 | pfile.write(output) |
|
1435 | pfile.write(output) | |
1436 | pfile.close() |
|
1436 | pfile.close() | |
1437 | print '\n*** Profile printout saved to text file',\ |
|
1437 | print '\n*** Profile printout saved to text file',\ | |
1438 | `text_file`+'.',sys_exit |
|
1438 | `text_file`+'.',sys_exit | |
1439 |
|
1439 | |||
1440 | if opts.has_key('r'): |
|
1440 | if opts.has_key('r'): | |
1441 | return stats |
|
1441 | return stats | |
1442 | else: |
|
1442 | else: | |
1443 | return None |
|
1443 | return None | |
1444 |
|
1444 | |||
1445 | @skip_doctest |
|
1445 | @skip_doctest | |
1446 | def magic_run(self, parameter_s ='',runner=None, |
|
1446 | def magic_run(self, parameter_s ='',runner=None, | |
1447 | file_finder=get_py_filename): |
|
1447 | file_finder=get_py_filename): | |
1448 | """Run the named file inside IPython as a program. |
|
1448 | """Run the named file inside IPython as a program. | |
1449 |
|
1449 | |||
1450 | Usage:\\ |
|
1450 | Usage:\\ | |
1451 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1451 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1452 |
|
1452 | |||
1453 | Parameters after the filename are passed as command-line arguments to |
|
1453 | Parameters after the filename are passed as command-line arguments to | |
1454 | the program (put in sys.argv). Then, control returns to IPython's |
|
1454 | the program (put in sys.argv). Then, control returns to IPython's | |
1455 | prompt. |
|
1455 | prompt. | |
1456 |
|
1456 | |||
1457 | This is similar to running at a system prompt:\\ |
|
1457 | This is similar to running at a system prompt:\\ | |
1458 | $ python file args\\ |
|
1458 | $ python file args\\ | |
1459 | but with the advantage of giving you IPython's tracebacks, and of |
|
1459 | but with the advantage of giving you IPython's tracebacks, and of | |
1460 | loading all variables into your interactive namespace for further use |
|
1460 | loading all variables into your interactive namespace for further use | |
1461 | (unless -p is used, see below). |
|
1461 | (unless -p is used, see below). | |
1462 |
|
1462 | |||
1463 | The file is executed in a namespace initially consisting only of |
|
1463 | The file is executed in a namespace initially consisting only of | |
1464 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1464 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1465 | sees its environment as if it were being run as a stand-alone program |
|
1465 | sees its environment as if it were being run as a stand-alone program | |
1466 | (except for sharing global objects such as previously imported |
|
1466 | (except for sharing global objects such as previously imported | |
1467 | modules). But after execution, the IPython interactive namespace gets |
|
1467 | modules). But after execution, the IPython interactive namespace gets | |
1468 | updated with all variables defined in the program (except for __name__ |
|
1468 | updated with all variables defined in the program (except for __name__ | |
1469 | and sys.argv). This allows for very convenient loading of code for |
|
1469 | and sys.argv). This allows for very convenient loading of code for | |
1470 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1470 | interactive work, while giving each program a 'clean sheet' to run in. | |
1471 |
|
1471 | |||
1472 | Options: |
|
1472 | Options: | |
1473 |
|
1473 | |||
1474 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1474 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1475 | without extension (as python does under import). This allows running |
|
1475 | without extension (as python does under import). This allows running | |
1476 | scripts and reloading the definitions in them without calling code |
|
1476 | scripts and reloading the definitions in them without calling code | |
1477 | protected by an ' if __name__ == "__main__" ' clause. |
|
1477 | protected by an ' if __name__ == "__main__" ' clause. | |
1478 |
|
1478 | |||
1479 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1479 | -i: run the file in IPython's namespace instead of an empty one. This | |
1480 | is useful if you are experimenting with code written in a text editor |
|
1480 | is useful if you are experimenting with code written in a text editor | |
1481 | which depends on variables defined interactively. |
|
1481 | which depends on variables defined interactively. | |
1482 |
|
1482 | |||
1483 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1483 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1484 | being run. This is particularly useful if IPython is being used to |
|
1484 | being run. This is particularly useful if IPython is being used to | |
1485 | run unittests, which always exit with a sys.exit() call. In such |
|
1485 | run unittests, which always exit with a sys.exit() call. In such | |
1486 | cases you are interested in the output of the test results, not in |
|
1486 | cases you are interested in the output of the test results, not in | |
1487 | seeing a traceback of the unittest module. |
|
1487 | seeing a traceback of the unittest module. | |
1488 |
|
1488 | |||
1489 | -t: print timing information at the end of the run. IPython will give |
|
1489 | -t: print timing information at the end of the run. IPython will give | |
1490 | you an estimated CPU time consumption for your script, which under |
|
1490 | you an estimated CPU time consumption for your script, which under | |
1491 | Unix uses the resource module to avoid the wraparound problems of |
|
1491 | Unix uses the resource module to avoid the wraparound problems of | |
1492 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1492 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1493 | is also given (for Windows platforms this is reported as 0.0). |
|
1493 | is also given (for Windows platforms this is reported as 0.0). | |
1494 |
|
1494 | |||
1495 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1495 | If -t is given, an additional -N<N> option can be given, where <N> | |
1496 | must be an integer indicating how many times you want the script to |
|
1496 | must be an integer indicating how many times you want the script to | |
1497 | run. The final timing report will include total and per run results. |
|
1497 | run. The final timing report will include total and per run results. | |
1498 |
|
1498 | |||
1499 | For example (testing the script uniq_stable.py): |
|
1499 | For example (testing the script uniq_stable.py): | |
1500 |
|
1500 | |||
1501 | In [1]: run -t uniq_stable |
|
1501 | In [1]: run -t uniq_stable | |
1502 |
|
1502 | |||
1503 | IPython CPU timings (estimated):\\ |
|
1503 | IPython CPU timings (estimated):\\ | |
1504 | User : 0.19597 s.\\ |
|
1504 | User : 0.19597 s.\\ | |
1505 | System: 0.0 s.\\ |
|
1505 | System: 0.0 s.\\ | |
1506 |
|
1506 | |||
1507 | In [2]: run -t -N5 uniq_stable |
|
1507 | In [2]: run -t -N5 uniq_stable | |
1508 |
|
1508 | |||
1509 | IPython CPU timings (estimated):\\ |
|
1509 | IPython CPU timings (estimated):\\ | |
1510 | Total runs performed: 5\\ |
|
1510 | Total runs performed: 5\\ | |
1511 | Times : Total Per run\\ |
|
1511 | Times : Total Per run\\ | |
1512 | User : 0.910862 s, 0.1821724 s.\\ |
|
1512 | User : 0.910862 s, 0.1821724 s.\\ | |
1513 | System: 0.0 s, 0.0 s. |
|
1513 | System: 0.0 s, 0.0 s. | |
1514 |
|
1514 | |||
1515 | -d: run your program under the control of pdb, the Python debugger. |
|
1515 | -d: run your program under the control of pdb, the Python debugger. | |
1516 | This allows you to execute your program step by step, watch variables, |
|
1516 | This allows you to execute your program step by step, watch variables, | |
1517 | etc. Internally, what IPython does is similar to calling: |
|
1517 | etc. Internally, what IPython does is similar to calling: | |
1518 |
|
1518 | |||
1519 | pdb.run('execfile("YOURFILENAME")') |
|
1519 | pdb.run('execfile("YOURFILENAME")') | |
1520 |
|
1520 | |||
1521 | with a breakpoint set on line 1 of your file. You can change the line |
|
1521 | with a breakpoint set on line 1 of your file. You can change the line | |
1522 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1522 | number for this automatic breakpoint to be <N> by using the -bN option | |
1523 | (where N must be an integer). For example: |
|
1523 | (where N must be an integer). For example: | |
1524 |
|
1524 | |||
1525 | %run -d -b40 myscript |
|
1525 | %run -d -b40 myscript | |
1526 |
|
1526 | |||
1527 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1527 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1528 | the first breakpoint must be set on a line which actually does |
|
1528 | the first breakpoint must be set on a line which actually does | |
1529 | something (not a comment or docstring) for it to stop execution. |
|
1529 | something (not a comment or docstring) for it to stop execution. | |
1530 |
|
1530 | |||
1531 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1531 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1532 | first enter 'c' (without qoutes) to start execution up to the first |
|
1532 | first enter 'c' (without qoutes) to start execution up to the first | |
1533 | breakpoint. |
|
1533 | breakpoint. | |
1534 |
|
1534 | |||
1535 | Entering 'help' gives information about the use of the debugger. You |
|
1535 | Entering 'help' gives information about the use of the debugger. You | |
1536 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1536 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1537 | at a prompt. |
|
1537 | at a prompt. | |
1538 |
|
1538 | |||
1539 | -p: run program under the control of the Python profiler module (which |
|
1539 | -p: run program under the control of the Python profiler module (which | |
1540 | prints a detailed report of execution times, function calls, etc). |
|
1540 | prints a detailed report of execution times, function calls, etc). | |
1541 |
|
1541 | |||
1542 | You can pass other options after -p which affect the behavior of the |
|
1542 | You can pass other options after -p which affect the behavior of the | |
1543 | profiler itself. See the docs for %prun for details. |
|
1543 | profiler itself. See the docs for %prun for details. | |
1544 |
|
1544 | |||
1545 | In this mode, the program's variables do NOT propagate back to the |
|
1545 | In this mode, the program's variables do NOT propagate back to the | |
1546 | IPython interactive namespace (because they remain in the namespace |
|
1546 | IPython interactive namespace (because they remain in the namespace | |
1547 | where the profiler executes them). |
|
1547 | where the profiler executes them). | |
1548 |
|
1548 | |||
1549 | Internally this triggers a call to %prun, see its documentation for |
|
1549 | Internally this triggers a call to %prun, see its documentation for | |
1550 | details on the options available specifically for profiling. |
|
1550 | details on the options available specifically for profiling. | |
1551 |
|
1551 | |||
1552 | There is one special usage for which the text above doesn't apply: |
|
1552 | There is one special usage for which the text above doesn't apply: | |
1553 | if the filename ends with .ipy, the file is run as ipython script, |
|
1553 | if the filename ends with .ipy, the file is run as ipython script, | |
1554 | just as if the commands were written on IPython prompt. |
|
1554 | just as if the commands were written on IPython prompt. | |
1555 | """ |
|
1555 | """ | |
1556 |
|
1556 | |||
1557 | # get arguments and set sys.argv for program to be run. |
|
1557 | # get arguments and set sys.argv for program to be run. | |
1558 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1558 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1559 | mode='list',list_all=1) |
|
1559 | mode='list',list_all=1) | |
1560 |
|
1560 | |||
1561 | try: |
|
1561 | try: | |
1562 | filename = file_finder(arg_lst[0]) |
|
1562 | filename = file_finder(arg_lst[0]) | |
1563 | except IndexError: |
|
1563 | except IndexError: | |
1564 | warn('you must provide at least a filename.') |
|
1564 | warn('you must provide at least a filename.') | |
1565 | print '\n%run:\n',oinspect.getdoc(self.magic_run) |
|
1565 | print '\n%run:\n',oinspect.getdoc(self.magic_run) | |
1566 | return |
|
1566 | return | |
1567 | except IOError,msg: |
|
1567 | except IOError,msg: | |
1568 | error(msg) |
|
1568 | error(msg) | |
1569 | return |
|
1569 | return | |
1570 |
|
1570 | |||
1571 | if filename.lower().endswith('.ipy'): |
|
1571 | if filename.lower().endswith('.ipy'): | |
1572 | self.shell.safe_execfile_ipy(filename) |
|
1572 | self.shell.safe_execfile_ipy(filename) | |
1573 | return |
|
1573 | return | |
1574 |
|
1574 | |||
1575 | # Control the response to exit() calls made by the script being run |
|
1575 | # Control the response to exit() calls made by the script being run | |
1576 | exit_ignore = opts.has_key('e') |
|
1576 | exit_ignore = opts.has_key('e') | |
1577 |
|
1577 | |||
1578 | # Make sure that the running script gets a proper sys.argv as if it |
|
1578 | # Make sure that the running script gets a proper sys.argv as if it | |
1579 | # were run from a system shell. |
|
1579 | # were run from a system shell. | |
1580 | save_argv = sys.argv # save it for later restoring |
|
1580 | save_argv = sys.argv # save it for later restoring | |
1581 |
|
1581 | |||
1582 | # simulate shell expansion on arguments, at least tilde expansion |
|
1582 | # simulate shell expansion on arguments, at least tilde expansion | |
1583 | args = [ os.path.expanduser(a) for a in arg_lst[1:] ] |
|
1583 | args = [ os.path.expanduser(a) for a in arg_lst[1:] ] | |
1584 |
|
1584 | |||
1585 | sys.argv = [filename]+ args # put in the proper filename |
|
1585 | sys.argv = [filename]+ args # put in the proper filename | |
1586 |
|
1586 | |||
1587 | if opts.has_key('i'): |
|
1587 | if opts.has_key('i'): | |
1588 | # Run in user's interactive namespace |
|
1588 | # Run in user's interactive namespace | |
1589 | prog_ns = self.shell.user_ns |
|
1589 | prog_ns = self.shell.user_ns | |
1590 | __name__save = self.shell.user_ns['__name__'] |
|
1590 | __name__save = self.shell.user_ns['__name__'] | |
1591 | prog_ns['__name__'] = '__main__' |
|
1591 | prog_ns['__name__'] = '__main__' | |
1592 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1592 | main_mod = self.shell.new_main_mod(prog_ns) | |
1593 | else: |
|
1593 | else: | |
1594 | # Run in a fresh, empty namespace |
|
1594 | # Run in a fresh, empty namespace | |
1595 | if opts.has_key('n'): |
|
1595 | if opts.has_key('n'): | |
1596 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1596 | name = os.path.splitext(os.path.basename(filename))[0] | |
1597 | else: |
|
1597 | else: | |
1598 | name = '__main__' |
|
1598 | name = '__main__' | |
1599 |
|
1599 | |||
1600 | main_mod = self.shell.new_main_mod() |
|
1600 | main_mod = self.shell.new_main_mod() | |
1601 | prog_ns = main_mod.__dict__ |
|
1601 | prog_ns = main_mod.__dict__ | |
1602 | prog_ns['__name__'] = name |
|
1602 | prog_ns['__name__'] = name | |
1603 |
|
1603 | |||
1604 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1604 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1605 | # set the __file__ global in the script's namespace |
|
1605 | # set the __file__ global in the script's namespace | |
1606 | prog_ns['__file__'] = filename |
|
1606 | prog_ns['__file__'] = filename | |
1607 |
|
1607 | |||
1608 | # pickle fix. See interactiveshell for an explanation. But we need to make sure |
|
1608 | # pickle fix. See interactiveshell for an explanation. But we need to make sure | |
1609 | # that, if we overwrite __main__, we replace it at the end |
|
1609 | # that, if we overwrite __main__, we replace it at the end | |
1610 | main_mod_name = prog_ns['__name__'] |
|
1610 | main_mod_name = prog_ns['__name__'] | |
1611 |
|
1611 | |||
1612 | if main_mod_name == '__main__': |
|
1612 | if main_mod_name == '__main__': | |
1613 | restore_main = sys.modules['__main__'] |
|
1613 | restore_main = sys.modules['__main__'] | |
1614 | else: |
|
1614 | else: | |
1615 | restore_main = False |
|
1615 | restore_main = False | |
1616 |
|
1616 | |||
1617 | # This needs to be undone at the end to prevent holding references to |
|
1617 | # This needs to be undone at the end to prevent holding references to | |
1618 | # every single object ever created. |
|
1618 | # every single object ever created. | |
1619 | sys.modules[main_mod_name] = main_mod |
|
1619 | sys.modules[main_mod_name] = main_mod | |
1620 |
|
1620 | |||
1621 | try: |
|
1621 | try: | |
1622 | stats = None |
|
1622 | stats = None | |
1623 | with self.readline_no_record: |
|
1623 | with self.readline_no_record: | |
1624 | if opts.has_key('p'): |
|
1624 | if opts.has_key('p'): | |
1625 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1625 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1626 | else: |
|
1626 | else: | |
1627 | if opts.has_key('d'): |
|
1627 | if opts.has_key('d'): | |
1628 | deb = debugger.Pdb(self.shell.colors) |
|
1628 | deb = debugger.Pdb(self.shell.colors) | |
1629 | # reset Breakpoint state, which is moronically kept |
|
1629 | # reset Breakpoint state, which is moronically kept | |
1630 | # in a class |
|
1630 | # in a class | |
1631 | bdb.Breakpoint.next = 1 |
|
1631 | bdb.Breakpoint.next = 1 | |
1632 | bdb.Breakpoint.bplist = {} |
|
1632 | bdb.Breakpoint.bplist = {} | |
1633 | bdb.Breakpoint.bpbynumber = [None] |
|
1633 | bdb.Breakpoint.bpbynumber = [None] | |
1634 | # Set an initial breakpoint to stop execution |
|
1634 | # Set an initial breakpoint to stop execution | |
1635 | maxtries = 10 |
|
1635 | maxtries = 10 | |
1636 | bp = int(opts.get('b',[1])[0]) |
|
1636 | bp = int(opts.get('b',[1])[0]) | |
1637 | checkline = deb.checkline(filename,bp) |
|
1637 | checkline = deb.checkline(filename,bp) | |
1638 | if not checkline: |
|
1638 | if not checkline: | |
1639 | for bp in range(bp+1,bp+maxtries+1): |
|
1639 | for bp in range(bp+1,bp+maxtries+1): | |
1640 | if deb.checkline(filename,bp): |
|
1640 | if deb.checkline(filename,bp): | |
1641 | break |
|
1641 | break | |
1642 | else: |
|
1642 | else: | |
1643 | msg = ("\nI failed to find a valid line to set " |
|
1643 | msg = ("\nI failed to find a valid line to set " | |
1644 | "a breakpoint\n" |
|
1644 | "a breakpoint\n" | |
1645 | "after trying up to line: %s.\n" |
|
1645 | "after trying up to line: %s.\n" | |
1646 | "Please set a valid breakpoint manually " |
|
1646 | "Please set a valid breakpoint manually " | |
1647 | "with the -b option." % bp) |
|
1647 | "with the -b option." % bp) | |
1648 | error(msg) |
|
1648 | error(msg) | |
1649 | return |
|
1649 | return | |
1650 | # if we find a good linenumber, set the breakpoint |
|
1650 | # if we find a good linenumber, set the breakpoint | |
1651 | deb.do_break('%s:%s' % (filename,bp)) |
|
1651 | deb.do_break('%s:%s' % (filename,bp)) | |
1652 | # Start file run |
|
1652 | # Start file run | |
1653 | print "NOTE: Enter 'c' at the", |
|
1653 | print "NOTE: Enter 'c' at the", | |
1654 | print "%s prompt to start your script." % deb.prompt |
|
1654 | print "%s prompt to start your script." % deb.prompt | |
1655 | try: |
|
1655 | try: | |
1656 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1656 | deb.run('execfile("%s")' % filename,prog_ns) | |
1657 |
|
1657 | |||
1658 | except: |
|
1658 | except: | |
1659 | etype, value, tb = sys.exc_info() |
|
1659 | etype, value, tb = sys.exc_info() | |
1660 | # Skip three frames in the traceback: the %run one, |
|
1660 | # Skip three frames in the traceback: the %run one, | |
1661 | # one inside bdb.py, and the command-line typed by the |
|
1661 | # one inside bdb.py, and the command-line typed by the | |
1662 | # user (run by exec in pdb itself). |
|
1662 | # user (run by exec in pdb itself). | |
1663 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1663 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) | |
1664 | else: |
|
1664 | else: | |
1665 | if runner is None: |
|
1665 | if runner is None: | |
1666 | runner = self.shell.safe_execfile |
|
1666 | runner = self.shell.safe_execfile | |
1667 | if opts.has_key('t'): |
|
1667 | if opts.has_key('t'): | |
1668 | # timed execution |
|
1668 | # timed execution | |
1669 | try: |
|
1669 | try: | |
1670 | nruns = int(opts['N'][0]) |
|
1670 | nruns = int(opts['N'][0]) | |
1671 | if nruns < 1: |
|
1671 | if nruns < 1: | |
1672 | error('Number of runs must be >=1') |
|
1672 | error('Number of runs must be >=1') | |
1673 | return |
|
1673 | return | |
1674 | except (KeyError): |
|
1674 | except (KeyError): | |
1675 | nruns = 1 |
|
1675 | nruns = 1 | |
1676 | twall0 = time.time() |
|
1676 | twall0 = time.time() | |
1677 | if nruns == 1: |
|
1677 | if nruns == 1: | |
1678 | t0 = clock2() |
|
1678 | t0 = clock2() | |
1679 | runner(filename,prog_ns,prog_ns, |
|
1679 | runner(filename,prog_ns,prog_ns, | |
1680 | exit_ignore=exit_ignore) |
|
1680 | exit_ignore=exit_ignore) | |
1681 | t1 = clock2() |
|
1681 | t1 = clock2() | |
1682 | t_usr = t1[0]-t0[0] |
|
1682 | t_usr = t1[0]-t0[0] | |
1683 | t_sys = t1[1]-t0[1] |
|
1683 | t_sys = t1[1]-t0[1] | |
1684 | print "\nIPython CPU timings (estimated):" |
|
1684 | print "\nIPython CPU timings (estimated):" | |
1685 | print " User : %10.2f s." % t_usr |
|
1685 | print " User : %10.2f s." % t_usr | |
1686 | print " System : %10.2f s." % t_sys |
|
1686 | print " System : %10.2f s." % t_sys | |
1687 | else: |
|
1687 | else: | |
1688 | runs = range(nruns) |
|
1688 | runs = range(nruns) | |
1689 | t0 = clock2() |
|
1689 | t0 = clock2() | |
1690 | for nr in runs: |
|
1690 | for nr in runs: | |
1691 | runner(filename,prog_ns,prog_ns, |
|
1691 | runner(filename,prog_ns,prog_ns, | |
1692 | exit_ignore=exit_ignore) |
|
1692 | exit_ignore=exit_ignore) | |
1693 | t1 = clock2() |
|
1693 | t1 = clock2() | |
1694 | t_usr = t1[0]-t0[0] |
|
1694 | t_usr = t1[0]-t0[0] | |
1695 | t_sys = t1[1]-t0[1] |
|
1695 | t_sys = t1[1]-t0[1] | |
1696 | print "\nIPython CPU timings (estimated):" |
|
1696 | print "\nIPython CPU timings (estimated):" | |
1697 | print "Total runs performed:",nruns |
|
1697 | print "Total runs performed:",nruns | |
1698 | print " Times : %10.2f %10.2f" % ('Total','Per run') |
|
1698 | print " Times : %10.2f %10.2f" % ('Total','Per run') | |
1699 | print " User : %10.2f s, %10.2f s." % (t_usr,t_usr/nruns) |
|
1699 | print " User : %10.2f s, %10.2f s." % (t_usr,t_usr/nruns) | |
1700 | print " System : %10.2f s, %10.2f s." % (t_sys,t_sys/nruns) |
|
1700 | print " System : %10.2f s, %10.2f s." % (t_sys,t_sys/nruns) | |
1701 | twall1 = time.time() |
|
1701 | twall1 = time.time() | |
1702 | print "Wall time: %10.2f s." % (twall1-twall0) |
|
1702 | print "Wall time: %10.2f s." % (twall1-twall0) | |
1703 |
|
1703 | |||
1704 | else: |
|
1704 | else: | |
1705 | # regular execution |
|
1705 | # regular execution | |
1706 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1706 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1707 |
|
1707 | |||
1708 | if opts.has_key('i'): |
|
1708 | if opts.has_key('i'): | |
1709 | self.shell.user_ns['__name__'] = __name__save |
|
1709 | self.shell.user_ns['__name__'] = __name__save | |
1710 | else: |
|
1710 | else: | |
1711 | # The shell MUST hold a reference to prog_ns so after %run |
|
1711 | # The shell MUST hold a reference to prog_ns so after %run | |
1712 | # exits, the python deletion mechanism doesn't zero it out |
|
1712 | # exits, the python deletion mechanism doesn't zero it out | |
1713 | # (leaving dangling references). |
|
1713 | # (leaving dangling references). | |
1714 | self.shell.cache_main_mod(prog_ns,filename) |
|
1714 | self.shell.cache_main_mod(prog_ns,filename) | |
1715 | # update IPython interactive namespace |
|
1715 | # update IPython interactive namespace | |
1716 |
|
1716 | |||
1717 | # Some forms of read errors on the file may mean the |
|
1717 | # Some forms of read errors on the file may mean the | |
1718 | # __name__ key was never set; using pop we don't have to |
|
1718 | # __name__ key was never set; using pop we don't have to | |
1719 | # worry about a possible KeyError. |
|
1719 | # worry about a possible KeyError. | |
1720 | prog_ns.pop('__name__', None) |
|
1720 | prog_ns.pop('__name__', None) | |
1721 |
|
1721 | |||
1722 | self.shell.user_ns.update(prog_ns) |
|
1722 | self.shell.user_ns.update(prog_ns) | |
1723 | finally: |
|
1723 | finally: | |
1724 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1724 | # It's a bit of a mystery why, but __builtins__ can change from | |
1725 | # being a module to becoming a dict missing some key data after |
|
1725 | # being a module to becoming a dict missing some key data after | |
1726 | # %run. As best I can see, this is NOT something IPython is doing |
|
1726 | # %run. As best I can see, this is NOT something IPython is doing | |
1727 | # at all, and similar problems have been reported before: |
|
1727 | # at all, and similar problems have been reported before: | |
1728 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1728 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html | |
1729 | # Since this seems to be done by the interpreter itself, the best |
|
1729 | # Since this seems to be done by the interpreter itself, the best | |
1730 | # we can do is to at least restore __builtins__ for the user on |
|
1730 | # we can do is to at least restore __builtins__ for the user on | |
1731 | # exit. |
|
1731 | # exit. | |
1732 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1732 | self.shell.user_ns['__builtins__'] = __builtin__ | |
1733 |
|
1733 | |||
1734 | # Ensure key global structures are restored |
|
1734 | # Ensure key global structures are restored | |
1735 | sys.argv = save_argv |
|
1735 | sys.argv = save_argv | |
1736 | if restore_main: |
|
1736 | if restore_main: | |
1737 | sys.modules['__main__'] = restore_main |
|
1737 | sys.modules['__main__'] = restore_main | |
1738 | else: |
|
1738 | else: | |
1739 | # Remove from sys.modules the reference to main_mod we'd |
|
1739 | # Remove from sys.modules the reference to main_mod we'd | |
1740 | # added. Otherwise it will trap references to objects |
|
1740 | # added. Otherwise it will trap references to objects | |
1741 | # contained therein. |
|
1741 | # contained therein. | |
1742 | del sys.modules[main_mod_name] |
|
1742 | del sys.modules[main_mod_name] | |
1743 |
|
1743 | |||
1744 | return stats |
|
1744 | return stats | |
1745 |
|
1745 | |||
1746 | @skip_doctest |
|
1746 | @skip_doctest | |
1747 | def magic_timeit(self, parameter_s =''): |
|
1747 | def magic_timeit(self, parameter_s =''): | |
1748 | """Time execution of a Python statement or expression |
|
1748 | """Time execution of a Python statement or expression | |
1749 |
|
1749 | |||
1750 | Usage:\\ |
|
1750 | Usage:\\ | |
1751 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1751 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1752 |
|
1752 | |||
1753 | Time execution of a Python statement or expression using the timeit |
|
1753 | Time execution of a Python statement or expression using the timeit | |
1754 | module. |
|
1754 | module. | |
1755 |
|
1755 | |||
1756 | Options: |
|
1756 | Options: | |
1757 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1757 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1758 | is not given, a fitting value is chosen. |
|
1758 | is not given, a fitting value is chosen. | |
1759 |
|
1759 | |||
1760 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1760 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1761 | Default: 3 |
|
1761 | Default: 3 | |
1762 |
|
1762 | |||
1763 | -t: use time.time to measure the time, which is the default on Unix. |
|
1763 | -t: use time.time to measure the time, which is the default on Unix. | |
1764 | This function measures wall time. |
|
1764 | This function measures wall time. | |
1765 |
|
1765 | |||
1766 | -c: use time.clock to measure the time, which is the default on |
|
1766 | -c: use time.clock to measure the time, which is the default on | |
1767 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1767 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1768 | instead and returns the CPU user time. |
|
1768 | instead and returns the CPU user time. | |
1769 |
|
1769 | |||
1770 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1770 | -p<P>: use a precision of <P> digits to display the timing result. | |
1771 | Default: 3 |
|
1771 | Default: 3 | |
1772 |
|
1772 | |||
1773 |
|
1773 | |||
1774 | Examples: |
|
1774 | Examples: | |
1775 |
|
1775 | |||
1776 | In [1]: %timeit pass |
|
1776 | In [1]: %timeit pass | |
1777 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1777 | 10000000 loops, best of 3: 53.3 ns per loop | |
1778 |
|
1778 | |||
1779 | In [2]: u = None |
|
1779 | In [2]: u = None | |
1780 |
|
1780 | |||
1781 | In [3]: %timeit u is None |
|
1781 | In [3]: %timeit u is None | |
1782 | 10000000 loops, best of 3: 184 ns per loop |
|
1782 | 10000000 loops, best of 3: 184 ns per loop | |
1783 |
|
1783 | |||
1784 | In [4]: %timeit -r 4 u == None |
|
1784 | In [4]: %timeit -r 4 u == None | |
1785 | 1000000 loops, best of 4: 242 ns per loop |
|
1785 | 1000000 loops, best of 4: 242 ns per loop | |
1786 |
|
1786 | |||
1787 | In [5]: import time |
|
1787 | In [5]: import time | |
1788 |
|
1788 | |||
1789 | In [6]: %timeit -n1 time.sleep(2) |
|
1789 | In [6]: %timeit -n1 time.sleep(2) | |
1790 | 1 loops, best of 3: 2 s per loop |
|
1790 | 1 loops, best of 3: 2 s per loop | |
1791 |
|
1791 | |||
1792 |
|
1792 | |||
1793 | The times reported by %timeit will be slightly higher than those |
|
1793 | The times reported by %timeit will be slightly higher than those | |
1794 | reported by the timeit.py script when variables are accessed. This is |
|
1794 | reported by the timeit.py script when variables are accessed. This is | |
1795 | due to the fact that %timeit executes the statement in the namespace |
|
1795 | due to the fact that %timeit executes the statement in the namespace | |
1796 | of the shell, compared with timeit.py, which uses a single setup |
|
1796 | of the shell, compared with timeit.py, which uses a single setup | |
1797 | statement to import function or create variables. Generally, the bias |
|
1797 | statement to import function or create variables. Generally, the bias | |
1798 | does not matter as long as results from timeit.py are not mixed with |
|
1798 | does not matter as long as results from timeit.py are not mixed with | |
1799 | those from %timeit.""" |
|
1799 | those from %timeit.""" | |
1800 |
|
1800 | |||
1801 | import timeit |
|
1801 | import timeit | |
1802 | import math |
|
1802 | import math | |
1803 |
|
1803 | |||
1804 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1804 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in | |
1805 | # certain terminals. Until we figure out a robust way of |
|
1805 | # certain terminals. Until we figure out a robust way of | |
1806 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1806 | # auto-detecting if the terminal can deal with it, use plain 'us' for | |
1807 | # microseconds. I am really NOT happy about disabling the proper |
|
1807 | # microseconds. I am really NOT happy about disabling the proper | |
1808 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1808 | # 'micro' prefix, but crashing is worse... If anyone knows what the | |
1809 | # right solution for this is, I'm all ears... |
|
1809 | # right solution for this is, I'm all ears... | |
1810 | # |
|
1810 | # | |
1811 | # Note: using |
|
1811 | # Note: using | |
1812 | # |
|
1812 | # | |
1813 | # s = u'\xb5' |
|
1813 | # s = u'\xb5' | |
1814 | # s.encode(sys.getdefaultencoding()) |
|
1814 | # s.encode(sys.getdefaultencoding()) | |
1815 | # |
|
1815 | # | |
1816 | # is not sufficient, as I've seen terminals where that fails but |
|
1816 | # is not sufficient, as I've seen terminals where that fails but | |
1817 | # print s |
|
1817 | # print s | |
1818 | # |
|
1818 | # | |
1819 | # succeeds |
|
1819 | # succeeds | |
1820 | # |
|
1820 | # | |
1821 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1821 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 | |
1822 |
|
1822 | |||
1823 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1823 | #units = [u"s", u"ms",u'\xb5',"ns"] | |
1824 | units = [u"s", u"ms",u'us',"ns"] |
|
1824 | units = [u"s", u"ms",u'us',"ns"] | |
1825 |
|
1825 | |||
1826 | scaling = [1, 1e3, 1e6, 1e9] |
|
1826 | scaling = [1, 1e3, 1e6, 1e9] | |
1827 |
|
1827 | |||
1828 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1828 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1829 | posix=False) |
|
1829 | posix=False) | |
1830 | if stmt == "": |
|
1830 | if stmt == "": | |
1831 | return |
|
1831 | return | |
1832 | timefunc = timeit.default_timer |
|
1832 | timefunc = timeit.default_timer | |
1833 | number = int(getattr(opts, "n", 0)) |
|
1833 | number = int(getattr(opts, "n", 0)) | |
1834 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1834 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1835 | precision = int(getattr(opts, "p", 3)) |
|
1835 | precision = int(getattr(opts, "p", 3)) | |
1836 | if hasattr(opts, "t"): |
|
1836 | if hasattr(opts, "t"): | |
1837 | timefunc = time.time |
|
1837 | timefunc = time.time | |
1838 | if hasattr(opts, "c"): |
|
1838 | if hasattr(opts, "c"): | |
1839 | timefunc = clock |
|
1839 | timefunc = clock | |
1840 |
|
1840 | |||
1841 | timer = timeit.Timer(timer=timefunc) |
|
1841 | timer = timeit.Timer(timer=timefunc) | |
1842 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1842 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1843 | # but is there a better way to achieve that the code stmt has access |
|
1843 | # but is there a better way to achieve that the code stmt has access | |
1844 | # to the shell namespace? |
|
1844 | # to the shell namespace? | |
1845 |
|
1845 | |||
1846 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1846 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1847 | 'setup': "pass"} |
|
1847 | 'setup': "pass"} | |
1848 | # Track compilation time so it can be reported if too long |
|
1848 | # Track compilation time so it can be reported if too long | |
1849 | # Minimum time above which compilation time will be reported |
|
1849 | # Minimum time above which compilation time will be reported | |
1850 | tc_min = 0.1 |
|
1850 | tc_min = 0.1 | |
1851 |
|
1851 | |||
1852 | t0 = clock() |
|
1852 | t0 = clock() | |
1853 | code = compile(src, "<magic-timeit>", "exec") |
|
1853 | code = compile(src, "<magic-timeit>", "exec") | |
1854 | tc = clock()-t0 |
|
1854 | tc = clock()-t0 | |
1855 |
|
1855 | |||
1856 | ns = {} |
|
1856 | ns = {} | |
1857 | exec code in self.shell.user_ns, ns |
|
1857 | exec code in self.shell.user_ns, ns | |
1858 | timer.inner = ns["inner"] |
|
1858 | timer.inner = ns["inner"] | |
1859 |
|
1859 | |||
1860 | if number == 0: |
|
1860 | if number == 0: | |
1861 | # determine number so that 0.2 <= total time < 2.0 |
|
1861 | # determine number so that 0.2 <= total time < 2.0 | |
1862 | number = 1 |
|
1862 | number = 1 | |
1863 | for i in range(1, 10): |
|
1863 | for i in range(1, 10): | |
1864 | if timer.timeit(number) >= 0.2: |
|
1864 | if timer.timeit(number) >= 0.2: | |
1865 | break |
|
1865 | break | |
1866 | number *= 10 |
|
1866 | number *= 10 | |
1867 |
|
1867 | |||
1868 | best = min(timer.repeat(repeat, number)) / number |
|
1868 | best = min(timer.repeat(repeat, number)) / number | |
1869 |
|
1869 | |||
1870 | if best > 0.0 and best < 1000.0: |
|
1870 | if best > 0.0 and best < 1000.0: | |
1871 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1871 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1872 | elif best >= 1000.0: |
|
1872 | elif best >= 1000.0: | |
1873 | order = 0 |
|
1873 | order = 0 | |
1874 | else: |
|
1874 | else: | |
1875 | order = 3 |
|
1875 | order = 3 | |
1876 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1876 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1877 | precision, |
|
1877 | precision, | |
1878 | best * scaling[order], |
|
1878 | best * scaling[order], | |
1879 | units[order]) |
|
1879 | units[order]) | |
1880 | if tc > tc_min: |
|
1880 | if tc > tc_min: | |
1881 | print "Compiler time: %.2f s" % tc |
|
1881 | print "Compiler time: %.2f s" % tc | |
1882 |
|
1882 | |||
1883 | @skip_doctest |
|
1883 | @skip_doctest | |
1884 | @needs_local_scope |
|
1884 | @needs_local_scope | |
1885 | def magic_time(self,parameter_s = ''): |
|
1885 | def magic_time(self,parameter_s = ''): | |
1886 | """Time execution of a Python statement or expression. |
|
1886 | """Time execution of a Python statement or expression. | |
1887 |
|
1887 | |||
1888 | The CPU and wall clock times are printed, and the value of the |
|
1888 | The CPU and wall clock times are printed, and the value of the | |
1889 | expression (if any) is returned. Note that under Win32, system time |
|
1889 | expression (if any) is returned. Note that under Win32, system time | |
1890 | is always reported as 0, since it can not be measured. |
|
1890 | is always reported as 0, since it can not be measured. | |
1891 |
|
1891 | |||
1892 | This function provides very basic timing functionality. In Python |
|
1892 | This function provides very basic timing functionality. In Python | |
1893 | 2.3, the timeit module offers more control and sophistication, so this |
|
1893 | 2.3, the timeit module offers more control and sophistication, so this | |
1894 | could be rewritten to use it (patches welcome). |
|
1894 | could be rewritten to use it (patches welcome). | |
1895 |
|
1895 | |||
1896 | Some examples: |
|
1896 | Some examples: | |
1897 |
|
1897 | |||
1898 | In [1]: time 2**128 |
|
1898 | In [1]: time 2**128 | |
1899 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1899 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1900 | Wall time: 0.00 |
|
1900 | Wall time: 0.00 | |
1901 | Out[1]: 340282366920938463463374607431768211456L |
|
1901 | Out[1]: 340282366920938463463374607431768211456L | |
1902 |
|
1902 | |||
1903 | In [2]: n = 1000000 |
|
1903 | In [2]: n = 1000000 | |
1904 |
|
1904 | |||
1905 | In [3]: time sum(range(n)) |
|
1905 | In [3]: time sum(range(n)) | |
1906 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1906 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1907 | Wall time: 1.37 |
|
1907 | Wall time: 1.37 | |
1908 | Out[3]: 499999500000L |
|
1908 | Out[3]: 499999500000L | |
1909 |
|
1909 | |||
1910 | In [4]: time print 'hello world' |
|
1910 | In [4]: time print 'hello world' | |
1911 | hello world |
|
1911 | hello world | |
1912 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1912 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1913 | Wall time: 0.00 |
|
1913 | Wall time: 0.00 | |
1914 |
|
1914 | |||
1915 | Note that the time needed by Python to compile the given expression |
|
1915 | Note that the time needed by Python to compile the given expression | |
1916 | will be reported if it is more than 0.1s. In this example, the |
|
1916 | will be reported if it is more than 0.1s. In this example, the | |
1917 | actual exponentiation is done by Python at compilation time, so while |
|
1917 | actual exponentiation is done by Python at compilation time, so while | |
1918 | the expression can take a noticeable amount of time to compute, that |
|
1918 | the expression can take a noticeable amount of time to compute, that | |
1919 | time is purely due to the compilation: |
|
1919 | time is purely due to the compilation: | |
1920 |
|
1920 | |||
1921 | In [5]: time 3**9999; |
|
1921 | In [5]: time 3**9999; | |
1922 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1922 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1923 | Wall time: 0.00 s |
|
1923 | Wall time: 0.00 s | |
1924 |
|
1924 | |||
1925 | In [6]: time 3**999999; |
|
1925 | In [6]: time 3**999999; | |
1926 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1926 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1927 | Wall time: 0.00 s |
|
1927 | Wall time: 0.00 s | |
1928 | Compiler : 0.78 s |
|
1928 | Compiler : 0.78 s | |
1929 | """ |
|
1929 | """ | |
1930 |
|
1930 | |||
1931 | # fail immediately if the given expression can't be compiled |
|
1931 | # fail immediately if the given expression can't be compiled | |
1932 |
|
1932 | |||
1933 | expr = self.shell.prefilter(parameter_s,False) |
|
1933 | expr = self.shell.prefilter(parameter_s,False) | |
1934 |
|
1934 | |||
1935 | # Minimum time above which compilation time will be reported |
|
1935 | # Minimum time above which compilation time will be reported | |
1936 | tc_min = 0.1 |
|
1936 | tc_min = 0.1 | |
1937 |
|
1937 | |||
1938 | try: |
|
1938 | try: | |
1939 | mode = 'eval' |
|
1939 | mode = 'eval' | |
1940 | t0 = clock() |
|
1940 | t0 = clock() | |
1941 | code = compile(expr,'<timed eval>',mode) |
|
1941 | code = compile(expr,'<timed eval>',mode) | |
1942 | tc = clock()-t0 |
|
1942 | tc = clock()-t0 | |
1943 | except SyntaxError: |
|
1943 | except SyntaxError: | |
1944 | mode = 'exec' |
|
1944 | mode = 'exec' | |
1945 | t0 = clock() |
|
1945 | t0 = clock() | |
1946 | code = compile(expr,'<timed exec>',mode) |
|
1946 | code = compile(expr,'<timed exec>',mode) | |
1947 | tc = clock()-t0 |
|
1947 | tc = clock()-t0 | |
1948 | # skew measurement as little as possible |
|
1948 | # skew measurement as little as possible | |
1949 | glob = self.shell.user_ns |
|
1949 | glob = self.shell.user_ns | |
1950 | locs = self._magic_locals |
|
1950 | locs = self._magic_locals | |
1951 | clk = clock2 |
|
1951 | clk = clock2 | |
1952 | wtime = time.time |
|
1952 | wtime = time.time | |
1953 | # time execution |
|
1953 | # time execution | |
1954 | wall_st = wtime() |
|
1954 | wall_st = wtime() | |
1955 | if mode=='eval': |
|
1955 | if mode=='eval': | |
1956 | st = clk() |
|
1956 | st = clk() | |
1957 | out = eval(code, glob, locs) |
|
1957 | out = eval(code, glob, locs) | |
1958 | end = clk() |
|
1958 | end = clk() | |
1959 | else: |
|
1959 | else: | |
1960 | st = clk() |
|
1960 | st = clk() | |
1961 | exec code in glob, locs |
|
1961 | exec code in glob, locs | |
1962 | end = clk() |
|
1962 | end = clk() | |
1963 | out = None |
|
1963 | out = None | |
1964 | wall_end = wtime() |
|
1964 | wall_end = wtime() | |
1965 | # Compute actual times and report |
|
1965 | # Compute actual times and report | |
1966 | wall_time = wall_end-wall_st |
|
1966 | wall_time = wall_end-wall_st | |
1967 | cpu_user = end[0]-st[0] |
|
1967 | cpu_user = end[0]-st[0] | |
1968 | cpu_sys = end[1]-st[1] |
|
1968 | cpu_sys = end[1]-st[1] | |
1969 | cpu_tot = cpu_user+cpu_sys |
|
1969 | cpu_tot = cpu_user+cpu_sys | |
1970 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1970 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1971 | (cpu_user,cpu_sys,cpu_tot) |
|
1971 | (cpu_user,cpu_sys,cpu_tot) | |
1972 | print "Wall time: %.2f s" % wall_time |
|
1972 | print "Wall time: %.2f s" % wall_time | |
1973 | if tc > tc_min: |
|
1973 | if tc > tc_min: | |
1974 | print "Compiler : %.2f s" % tc |
|
1974 | print "Compiler : %.2f s" % tc | |
1975 | return out |
|
1975 | return out | |
1976 |
|
1976 | |||
1977 | @skip_doctest |
|
1977 | @skip_doctest | |
1978 | def magic_macro(self,parameter_s = ''): |
|
1978 | def magic_macro(self,parameter_s = ''): | |
1979 | """Define a macro for future re-execution. It accepts ranges of history, |
|
1979 | """Define a macro for future re-execution. It accepts ranges of history, | |
1980 | filenames or string objects. |
|
1980 | filenames or string objects. | |
1981 |
|
1981 | |||
1982 | Usage:\\ |
|
1982 | Usage:\\ | |
1983 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1983 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1984 |
|
1984 | |||
1985 | Options: |
|
1985 | Options: | |
1986 |
|
1986 | |||
1987 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1987 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1988 | so that magics are loaded in their transformed version to valid |
|
1988 | so that magics are loaded in their transformed version to valid | |
1989 | Python. If this option is given, the raw input as typed as the |
|
1989 | Python. If this option is given, the raw input as typed as the | |
1990 | command line is used instead. |
|
1990 | command line is used instead. | |
1991 |
|
1991 | |||
1992 | This will define a global variable called `name` which is a string |
|
1992 | This will define a global variable called `name` which is a string | |
1993 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1993 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1994 | above) from your input history into a single string. This variable |
|
1994 | above) from your input history into a single string. This variable | |
1995 | acts like an automatic function which re-executes those lines as if |
|
1995 | acts like an automatic function which re-executes those lines as if | |
1996 | you had typed them. You just type 'name' at the prompt and the code |
|
1996 | you had typed them. You just type 'name' at the prompt and the code | |
1997 | executes. |
|
1997 | executes. | |
1998 |
|
1998 | |||
1999 | The syntax for indicating input ranges is described in %history. |
|
1999 | The syntax for indicating input ranges is described in %history. | |
2000 |
|
2000 | |||
2001 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
2001 | Note: as a 'hidden' feature, you can also use traditional python slice | |
2002 | notation, where N:M means numbers N through M-1. |
|
2002 | notation, where N:M means numbers N through M-1. | |
2003 |
|
2003 | |||
2004 | For example, if your history contains (%hist prints it): |
|
2004 | For example, if your history contains (%hist prints it): | |
2005 |
|
2005 | |||
2006 | 44: x=1 |
|
2006 | 44: x=1 | |
2007 | 45: y=3 |
|
2007 | 45: y=3 | |
2008 | 46: z=x+y |
|
2008 | 46: z=x+y | |
2009 | 47: print x |
|
2009 | 47: print x | |
2010 | 48: a=5 |
|
2010 | 48: a=5 | |
2011 | 49: print 'x',x,'y',y |
|
2011 | 49: print 'x',x,'y',y | |
2012 |
|
2012 | |||
2013 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
2013 | you can create a macro with lines 44 through 47 (included) and line 49 | |
2014 | called my_macro with: |
|
2014 | called my_macro with: | |
2015 |
|
2015 | |||
2016 | In [55]: %macro my_macro 44-47 49 |
|
2016 | In [55]: %macro my_macro 44-47 49 | |
2017 |
|
2017 | |||
2018 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
2018 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
2019 | in one pass. |
|
2019 | in one pass. | |
2020 |
|
2020 | |||
2021 | You don't need to give the line-numbers in order, and any given line |
|
2021 | You don't need to give the line-numbers in order, and any given line | |
2022 | number can appear multiple times. You can assemble macros with any |
|
2022 | number can appear multiple times. You can assemble macros with any | |
2023 | lines from your input history in any order. |
|
2023 | lines from your input history in any order. | |
2024 |
|
2024 | |||
2025 | The macro is a simple object which holds its value in an attribute, |
|
2025 | The macro is a simple object which holds its value in an attribute, | |
2026 | but IPython's display system checks for macros and executes them as |
|
2026 | but IPython's display system checks for macros and executes them as | |
2027 | code instead of printing them when you type their name. |
|
2027 | code instead of printing them when you type their name. | |
2028 |
|
2028 | |||
2029 | You can view a macro's contents by explicitly printing it with: |
|
2029 | You can view a macro's contents by explicitly printing it with: | |
2030 |
|
2030 | |||
2031 | 'print macro_name'. |
|
2031 | 'print macro_name'. | |
2032 |
|
2032 | |||
2033 | """ |
|
2033 | """ | |
2034 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2034 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2035 | if not args: # List existing macros |
|
2035 | if not args: # List existing macros | |
2036 | return sorted(k for k,v in self.shell.user_ns.iteritems() if\ |
|
2036 | return sorted(k for k,v in self.shell.user_ns.iteritems() if\ | |
2037 | isinstance(v, Macro)) |
|
2037 | isinstance(v, Macro)) | |
2038 | if len(args) == 1: |
|
2038 | if len(args) == 1: | |
2039 | raise UsageError( |
|
2039 | raise UsageError( | |
2040 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2040 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
2041 | name, codefrom = args[0], " ".join(args[1:]) |
|
2041 | name, codefrom = args[0], " ".join(args[1:]) | |
2042 |
|
2042 | |||
2043 | #print 'rng',ranges # dbg |
|
2043 | #print 'rng',ranges # dbg | |
2044 | try: |
|
2044 | try: | |
2045 | lines = self.shell.find_user_code(codefrom, 'r' in opts) |
|
2045 | lines = self.shell.find_user_code(codefrom, 'r' in opts) | |
2046 | except (ValueError, TypeError) as e: |
|
2046 | except (ValueError, TypeError) as e: | |
2047 | print e.args[0] |
|
2047 | print e.args[0] | |
2048 | return |
|
2048 | return | |
2049 | macro = Macro(lines) |
|
2049 | macro = Macro(lines) | |
2050 | self.shell.define_macro(name, macro) |
|
2050 | self.shell.define_macro(name, macro) | |
2051 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2051 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
2052 | print '=== Macro contents: ===' |
|
2052 | print '=== Macro contents: ===' | |
2053 | print macro, |
|
2053 | print macro, | |
2054 |
|
2054 | |||
2055 | def magic_save(self,parameter_s = ''): |
|
2055 | def magic_save(self,parameter_s = ''): | |
2056 | """Save a set of lines or a macro to a given filename. |
|
2056 | """Save a set of lines or a macro to a given filename. | |
2057 |
|
2057 | |||
2058 | Usage:\\ |
|
2058 | Usage:\\ | |
2059 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
2059 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
2060 |
|
2060 | |||
2061 | Options: |
|
2061 | Options: | |
2062 |
|
2062 | |||
2063 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2063 | -r: use 'raw' input. By default, the 'processed' history is used, | |
2064 | so that magics are loaded in their transformed version to valid |
|
2064 | so that magics are loaded in their transformed version to valid | |
2065 | Python. If this option is given, the raw input as typed as the |
|
2065 | Python. If this option is given, the raw input as typed as the | |
2066 | command line is used instead. |
|
2066 | command line is used instead. | |
2067 |
|
2067 | |||
2068 | This function uses the same syntax as %history for input ranges, |
|
2068 | This function uses the same syntax as %history for input ranges, | |
2069 | then saves the lines to the filename you specify. |
|
2069 | then saves the lines to the filename you specify. | |
2070 |
|
2070 | |||
2071 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2071 | It adds a '.py' extension to the file if you don't do so yourself, and | |
2072 | it asks for confirmation before overwriting existing files.""" |
|
2072 | it asks for confirmation before overwriting existing files.""" | |
2073 |
|
2073 | |||
2074 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2074 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2075 | fname, codefrom = args[0], " ".join(args[1:]) |
|
2075 | fname, codefrom = args[0], " ".join(args[1:]) | |
2076 | if not fname.endswith('.py'): |
|
2076 | if not fname.endswith('.py'): | |
2077 | fname += '.py' |
|
2077 | fname += '.py' | |
2078 | if os.path.isfile(fname): |
|
2078 | if os.path.isfile(fname): | |
2079 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2079 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
2080 | if ans.lower() not in ['y','yes']: |
|
2080 | if ans.lower() not in ['y','yes']: | |
2081 | print 'Operation cancelled.' |
|
2081 | print 'Operation cancelled.' | |
2082 | return |
|
2082 | return | |
2083 | try: |
|
2083 | try: | |
2084 | cmds = self.shell.find_user_code(codefrom, 'r' in opts) |
|
2084 | cmds = self.shell.find_user_code(codefrom, 'r' in opts) | |
2085 | except (TypeError, ValueError) as e: |
|
2085 | except (TypeError, ValueError) as e: | |
2086 | print e.args[0] |
|
2086 | print e.args[0] | |
2087 | return |
|
2087 | return | |
2088 | if isinstance(cmds, unicode): |
|
2088 | if isinstance(cmds, unicode): | |
2089 | cmds = cmds.encode("utf-8") |
|
2089 | cmds = cmds.encode("utf-8") | |
2090 | with open(fname,'w') as f: |
|
2090 | with open(fname,'w') as f: | |
2091 | f.write("# coding: utf-8\n") |
|
2091 | f.write("# coding: utf-8\n") | |
2092 | f.write(cmds) |
|
2092 | f.write(cmds) | |
2093 | print 'The following commands were written to file `%s`:' % fname |
|
2093 | print 'The following commands were written to file `%s`:' % fname | |
2094 | print cmds |
|
2094 | print cmds | |
2095 |
|
2095 | |||
2096 | def magic_pastebin(self, parameter_s = ''): |
|
2096 | def magic_pastebin(self, parameter_s = ''): | |
2097 | """Upload code to the 'Lodge it' paste bin, returning the URL.""" |
|
2097 | """Upload code to the 'Lodge it' paste bin, returning the URL.""" | |
2098 | try: |
|
2098 | try: | |
2099 | code = self.shell.find_user_code(parameter_s) |
|
2099 | code = self.shell.find_user_code(parameter_s) | |
2100 | except (ValueError, TypeError) as e: |
|
2100 | except (ValueError, TypeError) as e: | |
2101 | print e.args[0] |
|
2101 | print e.args[0] | |
2102 | return |
|
2102 | return | |
2103 | pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/') |
|
2103 | pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/') | |
2104 | id = pbserver.pastes.newPaste("python", code) |
|
2104 | id = pbserver.pastes.newPaste("python", code) | |
2105 | return "http://paste.pocoo.org/show/" + id |
|
2105 | return "http://paste.pocoo.org/show/" + id | |
2106 |
|
2106 | |||
2107 | def magic_loadpy(self, arg_s): |
|
2107 | def magic_loadpy(self, arg_s): | |
2108 | """Load a .py python script into the GUI console. |
|
2108 | """Load a .py python script into the GUI console. | |
2109 |
|
2109 | |||
2110 | This magic command can either take a local filename or a url:: |
|
2110 | This magic command can either take a local filename or a url:: | |
2111 |
|
2111 | |||
2112 | %loadpy myscript.py |
|
2112 | %loadpy myscript.py | |
2113 | %loadpy http://www.example.com/myscript.py |
|
2113 | %loadpy http://www.example.com/myscript.py | |
2114 | """ |
|
2114 | """ | |
2115 | if not arg_s.endswith('.py'): |
|
2115 | if not arg_s.endswith('.py'): | |
2116 | raise ValueError('%%load only works with .py files: %s' % arg_s) |
|
2116 | raise ValueError('%%load only works with .py files: %s' % arg_s) | |
2117 | if arg_s.startswith('http'): |
|
2117 | if arg_s.startswith('http'): | |
2118 | import urllib2 |
|
2118 | import urllib2 | |
2119 | response = urllib2.urlopen(arg_s) |
|
2119 | response = urllib2.urlopen(arg_s) | |
2120 | content = response.read() |
|
2120 | content = response.read() | |
2121 | else: |
|
2121 | else: | |
2122 |
|
|
2122 | with open(arg_s) as f: | |
|
2123 | content = f.read() | |||
2123 | self.set_next_input(content) |
|
2124 | self.set_next_input(content) | |
2124 |
|
2125 | |||
2125 | def _find_edit_target(self, args, opts, last_call): |
|
2126 | def _find_edit_target(self, args, opts, last_call): | |
2126 | """Utility method used by magic_edit to find what to edit.""" |
|
2127 | """Utility method used by magic_edit to find what to edit.""" | |
2127 |
|
2128 | |||
2128 | def make_filename(arg): |
|
2129 | def make_filename(arg): | |
2129 | "Make a filename from the given args" |
|
2130 | "Make a filename from the given args" | |
2130 | try: |
|
2131 | try: | |
2131 | filename = get_py_filename(arg) |
|
2132 | filename = get_py_filename(arg) | |
2132 | except IOError: |
|
2133 | except IOError: | |
2133 | # If it ends with .py but doesn't already exist, assume we want |
|
2134 | # If it ends with .py but doesn't already exist, assume we want | |
2134 | # a new file. |
|
2135 | # a new file. | |
2135 | if args.endswith('.py'): |
|
2136 | if args.endswith('.py'): | |
2136 | filename = arg |
|
2137 | filename = arg | |
2137 | else: |
|
2138 | else: | |
2138 | filename = None |
|
2139 | filename = None | |
2139 | return filename |
|
2140 | return filename | |
2140 |
|
2141 | |||
2141 | # Set a few locals from the options for convenience: |
|
2142 | # Set a few locals from the options for convenience: | |
2142 | opts_prev = 'p' in opts |
|
2143 | opts_prev = 'p' in opts | |
2143 | opts_raw = 'r' in opts |
|
2144 | opts_raw = 'r' in opts | |
2144 |
|
2145 | |||
2145 | # custom exceptions |
|
2146 | # custom exceptions | |
2146 | class DataIsObject(Exception): pass |
|
2147 | class DataIsObject(Exception): pass | |
2147 |
|
2148 | |||
2148 | # Default line number value |
|
2149 | # Default line number value | |
2149 | lineno = opts.get('n',None) |
|
2150 | lineno = opts.get('n',None) | |
2150 |
|
2151 | |||
2151 | if opts_prev: |
|
2152 | if opts_prev: | |
2152 | args = '_%s' % last_call[0] |
|
2153 | args = '_%s' % last_call[0] | |
2153 | if not self.shell.user_ns.has_key(args): |
|
2154 | if not self.shell.user_ns.has_key(args): | |
2154 | args = last_call[1] |
|
2155 | args = last_call[1] | |
2155 |
|
2156 | |||
2156 | # use last_call to remember the state of the previous call, but don't |
|
2157 | # use last_call to remember the state of the previous call, but don't | |
2157 | # let it be clobbered by successive '-p' calls. |
|
2158 | # let it be clobbered by successive '-p' calls. | |
2158 | try: |
|
2159 | try: | |
2159 | last_call[0] = self.shell.displayhook.prompt_count |
|
2160 | last_call[0] = self.shell.displayhook.prompt_count | |
2160 | if not opts_prev: |
|
2161 | if not opts_prev: | |
2161 | last_call[1] = parameter_s |
|
2162 | last_call[1] = parameter_s | |
2162 | except: |
|
2163 | except: | |
2163 | pass |
|
2164 | pass | |
2164 |
|
2165 | |||
2165 | # by default this is done with temp files, except when the given |
|
2166 | # by default this is done with temp files, except when the given | |
2166 | # arg is a filename |
|
2167 | # arg is a filename | |
2167 | use_temp = True |
|
2168 | use_temp = True | |
2168 |
|
2169 | |||
2169 | data = '' |
|
2170 | data = '' | |
2170 |
|
2171 | |||
2171 | # First, see if the arguments should be a filename. |
|
2172 | # First, see if the arguments should be a filename. | |
2172 | filename = make_filename(args) |
|
2173 | filename = make_filename(args) | |
2173 | if filename: |
|
2174 | if filename: | |
2174 | use_temp = False |
|
2175 | use_temp = False | |
2175 | elif args: |
|
2176 | elif args: | |
2176 | # Mode where user specifies ranges of lines, like in %macro. |
|
2177 | # Mode where user specifies ranges of lines, like in %macro. | |
2177 | data = self.extract_input_lines(args, opts_raw) |
|
2178 | data = self.extract_input_lines(args, opts_raw) | |
2178 | if not data: |
|
2179 | if not data: | |
2179 | try: |
|
2180 | try: | |
2180 | # Load the parameter given as a variable. If not a string, |
|
2181 | # Load the parameter given as a variable. If not a string, | |
2181 | # process it as an object instead (below) |
|
2182 | # process it as an object instead (below) | |
2182 |
|
2183 | |||
2183 | #print '*** args',args,'type',type(args) # dbg |
|
2184 | #print '*** args',args,'type',type(args) # dbg | |
2184 | data = eval(args, self.shell.user_ns) |
|
2185 | data = eval(args, self.shell.user_ns) | |
2185 | if not isinstance(data, basestring): |
|
2186 | if not isinstance(data, basestring): | |
2186 | raise DataIsObject |
|
2187 | raise DataIsObject | |
2187 |
|
2188 | |||
2188 | except (NameError,SyntaxError): |
|
2189 | except (NameError,SyntaxError): | |
2189 | # given argument is not a variable, try as a filename |
|
2190 | # given argument is not a variable, try as a filename | |
2190 | filename = make_filename(args) |
|
2191 | filename = make_filename(args) | |
2191 | if filename is None: |
|
2192 | if filename is None: | |
2192 | warn("Argument given (%s) can't be found as a variable " |
|
2193 | warn("Argument given (%s) can't be found as a variable " | |
2193 | "or as a filename." % args) |
|
2194 | "or as a filename." % args) | |
2194 | return |
|
2195 | return | |
2195 | use_temp = False |
|
2196 | use_temp = False | |
2196 |
|
2197 | |||
2197 | except DataIsObject: |
|
2198 | except DataIsObject: | |
2198 | # macros have a special edit function |
|
2199 | # macros have a special edit function | |
2199 | if isinstance(data, Macro): |
|
2200 | if isinstance(data, Macro): | |
2200 | raise MacroToEdit(data) |
|
2201 | raise MacroToEdit(data) | |
2201 |
|
2202 | |||
2202 | # For objects, try to edit the file where they are defined |
|
2203 | # For objects, try to edit the file where they are defined | |
2203 | try: |
|
2204 | try: | |
2204 | filename = inspect.getabsfile(data) |
|
2205 | filename = inspect.getabsfile(data) | |
2205 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2206 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
2206 | # class created by %edit? Try to find source |
|
2207 | # class created by %edit? Try to find source | |
2207 | # by looking for method definitions instead, the |
|
2208 | # by looking for method definitions instead, the | |
2208 | # __module__ in those classes is FakeModule. |
|
2209 | # __module__ in those classes is FakeModule. | |
2209 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2210 | attrs = [getattr(data, aname) for aname in dir(data)] | |
2210 | for attr in attrs: |
|
2211 | for attr in attrs: | |
2211 | if not inspect.ismethod(attr): |
|
2212 | if not inspect.ismethod(attr): | |
2212 | continue |
|
2213 | continue | |
2213 | filename = inspect.getabsfile(attr) |
|
2214 | filename = inspect.getabsfile(attr) | |
2214 | if filename and 'fakemodule' not in filename.lower(): |
|
2215 | if filename and 'fakemodule' not in filename.lower(): | |
2215 | # change the attribute to be the edit target instead |
|
2216 | # change the attribute to be the edit target instead | |
2216 | data = attr |
|
2217 | data = attr | |
2217 | break |
|
2218 | break | |
2218 |
|
2219 | |||
2219 | datafile = 1 |
|
2220 | datafile = 1 | |
2220 | except TypeError: |
|
2221 | except TypeError: | |
2221 | filename = make_filename(args) |
|
2222 | filename = make_filename(args) | |
2222 | datafile = 1 |
|
2223 | datafile = 1 | |
2223 | warn('Could not find file where `%s` is defined.\n' |
|
2224 | warn('Could not find file where `%s` is defined.\n' | |
2224 | 'Opening a file named `%s`' % (args,filename)) |
|
2225 | 'Opening a file named `%s`' % (args,filename)) | |
2225 | # Now, make sure we can actually read the source (if it was in |
|
2226 | # Now, make sure we can actually read the source (if it was in | |
2226 | # a temp file it's gone by now). |
|
2227 | # a temp file it's gone by now). | |
2227 | if datafile: |
|
2228 | if datafile: | |
2228 | try: |
|
2229 | try: | |
2229 | if lineno is None: |
|
2230 | if lineno is None: | |
2230 | lineno = inspect.getsourcelines(data)[1] |
|
2231 | lineno = inspect.getsourcelines(data)[1] | |
2231 | except IOError: |
|
2232 | except IOError: | |
2232 | filename = make_filename(args) |
|
2233 | filename = make_filename(args) | |
2233 | if filename is None: |
|
2234 | if filename is None: | |
2234 | warn('The file `%s` where `%s` was defined cannot ' |
|
2235 | warn('The file `%s` where `%s` was defined cannot ' | |
2235 | 'be read.' % (filename,data)) |
|
2236 | 'be read.' % (filename,data)) | |
2236 | return |
|
2237 | return | |
2237 | use_temp = False |
|
2238 | use_temp = False | |
2238 |
|
2239 | |||
2239 | if use_temp: |
|
2240 | if use_temp: | |
2240 | filename = self.shell.mktempfile(data) |
|
2241 | filename = self.shell.mktempfile(data) | |
2241 | print 'IPython will make a temporary file named:',filename |
|
2242 | print 'IPython will make a temporary file named:',filename | |
2242 |
|
2243 | |||
2243 | return filename, lineno, use_temp |
|
2244 | return filename, lineno, use_temp | |
2244 |
|
2245 | |||
2245 | def _edit_macro(self,mname,macro): |
|
2246 | def _edit_macro(self,mname,macro): | |
2246 | """open an editor with the macro data in a file""" |
|
2247 | """open an editor with the macro data in a file""" | |
2247 | filename = self.shell.mktempfile(macro.value) |
|
2248 | filename = self.shell.mktempfile(macro.value) | |
2248 | self.shell.hooks.editor(filename) |
|
2249 | self.shell.hooks.editor(filename) | |
2249 |
|
2250 | |||
2250 | # and make a new macro object, to replace the old one |
|
2251 | # and make a new macro object, to replace the old one | |
2251 | mfile = open(filename) |
|
2252 | mfile = open(filename) | |
2252 | mvalue = mfile.read() |
|
2253 | mvalue = mfile.read() | |
2253 | mfile.close() |
|
2254 | mfile.close() | |
2254 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2255 | self.shell.user_ns[mname] = Macro(mvalue) | |
2255 |
|
2256 | |||
2256 | def magic_ed(self,parameter_s=''): |
|
2257 | def magic_ed(self,parameter_s=''): | |
2257 | """Alias to %edit.""" |
|
2258 | """Alias to %edit.""" | |
2258 | return self.magic_edit(parameter_s) |
|
2259 | return self.magic_edit(parameter_s) | |
2259 |
|
2260 | |||
2260 | @skip_doctest |
|
2261 | @skip_doctest | |
2261 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2262 | def magic_edit(self,parameter_s='',last_call=['','']): | |
2262 | """Bring up an editor and execute the resulting code. |
|
2263 | """Bring up an editor and execute the resulting code. | |
2263 |
|
2264 | |||
2264 | Usage: |
|
2265 | Usage: | |
2265 | %edit [options] [args] |
|
2266 | %edit [options] [args] | |
2266 |
|
2267 | |||
2267 | %edit runs IPython's editor hook. The default version of this hook is |
|
2268 | %edit runs IPython's editor hook. The default version of this hook is | |
2268 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2269 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
2269 | environment variable $EDITOR. If this isn't found, it will default to |
|
2270 | environment variable $EDITOR. If this isn't found, it will default to | |
2270 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2271 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
2271 | docstring for how to change the editor hook. |
|
2272 | docstring for how to change the editor hook. | |
2272 |
|
2273 | |||
2273 | You can also set the value of this editor via the command line option |
|
2274 | You can also set the value of this editor via the command line option | |
2274 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2275 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
2275 | specifically for IPython an editor different from your typical default |
|
2276 | specifically for IPython an editor different from your typical default | |
2276 | (and for Windows users who typically don't set environment variables). |
|
2277 | (and for Windows users who typically don't set environment variables). | |
2277 |
|
2278 | |||
2278 | This command allows you to conveniently edit multi-line code right in |
|
2279 | This command allows you to conveniently edit multi-line code right in | |
2279 | your IPython session. |
|
2280 | your IPython session. | |
2280 |
|
2281 | |||
2281 | If called without arguments, %edit opens up an empty editor with a |
|
2282 | If called without arguments, %edit opens up an empty editor with a | |
2282 | temporary file and will execute the contents of this file when you |
|
2283 | temporary file and will execute the contents of this file when you | |
2283 | close it (don't forget to save it!). |
|
2284 | close it (don't forget to save it!). | |
2284 |
|
2285 | |||
2285 |
|
2286 | |||
2286 | Options: |
|
2287 | Options: | |
2287 |
|
2288 | |||
2288 | -n <number>: open the editor at a specified line number. By default, |
|
2289 | -n <number>: open the editor at a specified line number. By default, | |
2289 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2290 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
2290 | you can configure this by providing your own modified hook if your |
|
2291 | you can configure this by providing your own modified hook if your | |
2291 | favorite editor supports line-number specifications with a different |
|
2292 | favorite editor supports line-number specifications with a different | |
2292 | syntax. |
|
2293 | syntax. | |
2293 |
|
2294 | |||
2294 | -p: this will call the editor with the same data as the previous time |
|
2295 | -p: this will call the editor with the same data as the previous time | |
2295 | it was used, regardless of how long ago (in your current session) it |
|
2296 | it was used, regardless of how long ago (in your current session) it | |
2296 | was. |
|
2297 | was. | |
2297 |
|
2298 | |||
2298 | -r: use 'raw' input. This option only applies to input taken from the |
|
2299 | -r: use 'raw' input. This option only applies to input taken from the | |
2299 | user's history. By default, the 'processed' history is used, so that |
|
2300 | user's history. By default, the 'processed' history is used, so that | |
2300 | magics are loaded in their transformed version to valid Python. If |
|
2301 | magics are loaded in their transformed version to valid Python. If | |
2301 | this option is given, the raw input as typed as the command line is |
|
2302 | this option is given, the raw input as typed as the command line is | |
2302 | used instead. When you exit the editor, it will be executed by |
|
2303 | used instead. When you exit the editor, it will be executed by | |
2303 | IPython's own processor. |
|
2304 | IPython's own processor. | |
2304 |
|
2305 | |||
2305 | -x: do not execute the edited code immediately upon exit. This is |
|
2306 | -x: do not execute the edited code immediately upon exit. This is | |
2306 | mainly useful if you are editing programs which need to be called with |
|
2307 | mainly useful if you are editing programs which need to be called with | |
2307 | command line arguments, which you can then do using %run. |
|
2308 | command line arguments, which you can then do using %run. | |
2308 |
|
2309 | |||
2309 |
|
2310 | |||
2310 | Arguments: |
|
2311 | Arguments: | |
2311 |
|
2312 | |||
2312 | If arguments are given, the following possibilites exist: |
|
2313 | If arguments are given, the following possibilites exist: | |
2313 |
|
2314 | |||
2314 | - If the argument is a filename, IPython will load that into the |
|
2315 | - If the argument is a filename, IPython will load that into the | |
2315 | editor. It will execute its contents with execfile() when you exit, |
|
2316 | editor. It will execute its contents with execfile() when you exit, | |
2316 | loading any code in the file into your interactive namespace. |
|
2317 | loading any code in the file into your interactive namespace. | |
2317 |
|
2318 | |||
2318 | - The arguments are ranges of input history, e.g. "7 ~1/4-6". |
|
2319 | - The arguments are ranges of input history, e.g. "7 ~1/4-6". | |
2319 | The syntax is the same as in the %history magic. |
|
2320 | The syntax is the same as in the %history magic. | |
2320 |
|
2321 | |||
2321 | - If the argument is a string variable, its contents are loaded |
|
2322 | - If the argument is a string variable, its contents are loaded | |
2322 | into the editor. You can thus edit any string which contains |
|
2323 | into the editor. You can thus edit any string which contains | |
2323 | python code (including the result of previous edits). |
|
2324 | python code (including the result of previous edits). | |
2324 |
|
2325 | |||
2325 | - If the argument is the name of an object (other than a string), |
|
2326 | - If the argument is the name of an object (other than a string), | |
2326 | IPython will try to locate the file where it was defined and open the |
|
2327 | IPython will try to locate the file where it was defined and open the | |
2327 | editor at the point where it is defined. You can use `%edit function` |
|
2328 | editor at the point where it is defined. You can use `%edit function` | |
2328 | to load an editor exactly at the point where 'function' is defined, |
|
2329 | to load an editor exactly at the point where 'function' is defined, | |
2329 | edit it and have the file be executed automatically. |
|
2330 | edit it and have the file be executed automatically. | |
2330 |
|
2331 | |||
2331 | If the object is a macro (see %macro for details), this opens up your |
|
2332 | If the object is a macro (see %macro for details), this opens up your | |
2332 | specified editor with a temporary file containing the macro's data. |
|
2333 | specified editor with a temporary file containing the macro's data. | |
2333 | Upon exit, the macro is reloaded with the contents of the file. |
|
2334 | Upon exit, the macro is reloaded with the contents of the file. | |
2334 |
|
2335 | |||
2335 | Note: opening at an exact line is only supported under Unix, and some |
|
2336 | Note: opening at an exact line is only supported under Unix, and some | |
2336 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2337 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
2337 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2338 | '+NUMBER' parameter necessary for this feature. Good editors like | |
2338 | (X)Emacs, vi, jed, pico and joe all do. |
|
2339 | (X)Emacs, vi, jed, pico and joe all do. | |
2339 |
|
2340 | |||
2340 | After executing your code, %edit will return as output the code you |
|
2341 | After executing your code, %edit will return as output the code you | |
2341 | typed in the editor (except when it was an existing file). This way |
|
2342 | typed in the editor (except when it was an existing file). This way | |
2342 | you can reload the code in further invocations of %edit as a variable, |
|
2343 | you can reload the code in further invocations of %edit as a variable, | |
2343 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2344 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
2344 | the output. |
|
2345 | the output. | |
2345 |
|
2346 | |||
2346 | Note that %edit is also available through the alias %ed. |
|
2347 | Note that %edit is also available through the alias %ed. | |
2347 |
|
2348 | |||
2348 | This is an example of creating a simple function inside the editor and |
|
2349 | This is an example of creating a simple function inside the editor and | |
2349 | then modifying it. First, start up the editor: |
|
2350 | then modifying it. First, start up the editor: | |
2350 |
|
2351 | |||
2351 | In [1]: ed |
|
2352 | In [1]: ed | |
2352 | Editing... done. Executing edited code... |
|
2353 | Editing... done. Executing edited code... | |
2353 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2354 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
2354 |
|
2355 | |||
2355 | We can then call the function foo(): |
|
2356 | We can then call the function foo(): | |
2356 |
|
2357 | |||
2357 | In [2]: foo() |
|
2358 | In [2]: foo() | |
2358 | foo() was defined in an editing session |
|
2359 | foo() was defined in an editing session | |
2359 |
|
2360 | |||
2360 | Now we edit foo. IPython automatically loads the editor with the |
|
2361 | Now we edit foo. IPython automatically loads the editor with the | |
2361 | (temporary) file where foo() was previously defined: |
|
2362 | (temporary) file where foo() was previously defined: | |
2362 |
|
2363 | |||
2363 | In [3]: ed foo |
|
2364 | In [3]: ed foo | |
2364 | Editing... done. Executing edited code... |
|
2365 | Editing... done. Executing edited code... | |
2365 |
|
2366 | |||
2366 | And if we call foo() again we get the modified version: |
|
2367 | And if we call foo() again we get the modified version: | |
2367 |
|
2368 | |||
2368 | In [4]: foo() |
|
2369 | In [4]: foo() | |
2369 | foo() has now been changed! |
|
2370 | foo() has now been changed! | |
2370 |
|
2371 | |||
2371 | Here is an example of how to edit a code snippet successive |
|
2372 | Here is an example of how to edit a code snippet successive | |
2372 | times. First we call the editor: |
|
2373 | times. First we call the editor: | |
2373 |
|
2374 | |||
2374 | In [5]: ed |
|
2375 | In [5]: ed | |
2375 | Editing... done. Executing edited code... |
|
2376 | Editing... done. Executing edited code... | |
2376 | hello |
|
2377 | hello | |
2377 | Out[5]: "print 'hello'n" |
|
2378 | Out[5]: "print 'hello'n" | |
2378 |
|
2379 | |||
2379 | Now we call it again with the previous output (stored in _): |
|
2380 | Now we call it again with the previous output (stored in _): | |
2380 |
|
2381 | |||
2381 | In [6]: ed _ |
|
2382 | In [6]: ed _ | |
2382 | Editing... done. Executing edited code... |
|
2383 | Editing... done. Executing edited code... | |
2383 | hello world |
|
2384 | hello world | |
2384 | Out[6]: "print 'hello world'n" |
|
2385 | Out[6]: "print 'hello world'n" | |
2385 |
|
2386 | |||
2386 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2387 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
2387 |
|
2388 | |||
2388 | In [7]: ed _8 |
|
2389 | In [7]: ed _8 | |
2389 | Editing... done. Executing edited code... |
|
2390 | Editing... done. Executing edited code... | |
2390 | hello again |
|
2391 | hello again | |
2391 | Out[7]: "print 'hello again'n" |
|
2392 | Out[7]: "print 'hello again'n" | |
2392 |
|
2393 | |||
2393 |
|
2394 | |||
2394 | Changing the default editor hook: |
|
2395 | Changing the default editor hook: | |
2395 |
|
2396 | |||
2396 | If you wish to write your own editor hook, you can put it in a |
|
2397 | If you wish to write your own editor hook, you can put it in a | |
2397 | configuration file which you load at startup time. The default hook |
|
2398 | configuration file which you load at startup time. The default hook | |
2398 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2399 | is defined in the IPython.core.hooks module, and you can use that as a | |
2399 | starting example for further modifications. That file also has |
|
2400 | starting example for further modifications. That file also has | |
2400 | general instructions on how to set a new hook for use once you've |
|
2401 | general instructions on how to set a new hook for use once you've | |
2401 | defined it.""" |
|
2402 | defined it.""" | |
2402 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2403 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2403 |
|
2404 | |||
2404 | try: |
|
2405 | try: | |
2405 | filename, lineno, is_temp = self._find_edit_target(args, opts, last_call) |
|
2406 | filename, lineno, is_temp = self._find_edit_target(args, opts, last_call) | |
2406 | except MacroToEdit as e: |
|
2407 | except MacroToEdit as e: | |
2407 | self._edit_macro(args, e.args[0]) |
|
2408 | self._edit_macro(args, e.args[0]) | |
2408 | return |
|
2409 | return | |
2409 |
|
2410 | |||
2410 | # do actual editing here |
|
2411 | # do actual editing here | |
2411 | print 'Editing...', |
|
2412 | print 'Editing...', | |
2412 | sys.stdout.flush() |
|
2413 | sys.stdout.flush() | |
2413 | try: |
|
2414 | try: | |
2414 | # Quote filenames that may have spaces in them |
|
2415 | # Quote filenames that may have spaces in them | |
2415 | if ' ' in filename: |
|
2416 | if ' ' in filename: | |
2416 | filename = "'%s'" % filename |
|
2417 | filename = "'%s'" % filename | |
2417 | self.shell.hooks.editor(filename,lineno) |
|
2418 | self.shell.hooks.editor(filename,lineno) | |
2418 | except TryNext: |
|
2419 | except TryNext: | |
2419 | warn('Could not open editor') |
|
2420 | warn('Could not open editor') | |
2420 | return |
|
2421 | return | |
2421 |
|
2422 | |||
2422 | # XXX TODO: should this be generalized for all string vars? |
|
2423 | # XXX TODO: should this be generalized for all string vars? | |
2423 | # For now, this is special-cased to blocks created by cpaste |
|
2424 | # For now, this is special-cased to blocks created by cpaste | |
2424 | if args.strip() == 'pasted_block': |
|
2425 | if args.strip() == 'pasted_block': | |
2425 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2426 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
2426 |
|
2427 | |||
2427 | if 'x' in opts: # -x prevents actual execution |
|
2428 | if 'x' in opts: # -x prevents actual execution | |
2428 |
|
2429 | |||
2429 | else: |
|
2430 | else: | |
2430 | print 'done. Executing edited code...' |
|
2431 | print 'done. Executing edited code...' | |
2431 | if 'r' in opts: # Untranslated IPython code |
|
2432 | if 'r' in opts: # Untranslated IPython code | |
2432 | self.shell.run_cell(file_read(filename), |
|
2433 | self.shell.run_cell(file_read(filename), | |
2433 | store_history=False) |
|
2434 | store_history=False) | |
2434 | else: |
|
2435 | else: | |
2435 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2436 | self.shell.safe_execfile(filename,self.shell.user_ns, | |
2436 | self.shell.user_ns) |
|
2437 | self.shell.user_ns) | |
2437 |
|
2438 | |||
2438 | if is_temp: |
|
2439 | if is_temp: | |
2439 | try: |
|
2440 | try: | |
2440 | return open(filename).read() |
|
2441 | return open(filename).read() | |
2441 | except IOError,msg: |
|
2442 | except IOError,msg: | |
2442 | if msg.filename == filename: |
|
2443 | if msg.filename == filename: | |
2443 | warn('File not found. Did you forget to save?') |
|
2444 | warn('File not found. Did you forget to save?') | |
2444 | return |
|
2445 | return | |
2445 | else: |
|
2446 | else: | |
2446 | self.shell.showtraceback() |
|
2447 | self.shell.showtraceback() | |
2447 |
|
2448 | |||
2448 | def magic_xmode(self,parameter_s = ''): |
|
2449 | def magic_xmode(self,parameter_s = ''): | |
2449 | """Switch modes for the exception handlers. |
|
2450 | """Switch modes for the exception handlers. | |
2450 |
|
2451 | |||
2451 | Valid modes: Plain, Context and Verbose. |
|
2452 | Valid modes: Plain, Context and Verbose. | |
2452 |
|
2453 | |||
2453 | If called without arguments, acts as a toggle.""" |
|
2454 | If called without arguments, acts as a toggle.""" | |
2454 |
|
2455 | |||
2455 | def xmode_switch_err(name): |
|
2456 | def xmode_switch_err(name): | |
2456 | warn('Error changing %s exception modes.\n%s' % |
|
2457 | warn('Error changing %s exception modes.\n%s' % | |
2457 | (name,sys.exc_info()[1])) |
|
2458 | (name,sys.exc_info()[1])) | |
2458 |
|
2459 | |||
2459 | shell = self.shell |
|
2460 | shell = self.shell | |
2460 | new_mode = parameter_s.strip().capitalize() |
|
2461 | new_mode = parameter_s.strip().capitalize() | |
2461 | try: |
|
2462 | try: | |
2462 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2463 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2463 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2464 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2464 | except: |
|
2465 | except: | |
2465 | xmode_switch_err('user') |
|
2466 | xmode_switch_err('user') | |
2466 |
|
2467 | |||
2467 | def magic_colors(self,parameter_s = ''): |
|
2468 | def magic_colors(self,parameter_s = ''): | |
2468 | """Switch color scheme for prompts, info system and exception handlers. |
|
2469 | """Switch color scheme for prompts, info system and exception handlers. | |
2469 |
|
2470 | |||
2470 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2471 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2471 |
|
2472 | |||
2472 | Color scheme names are not case-sensitive. |
|
2473 | Color scheme names are not case-sensitive. | |
2473 |
|
2474 | |||
2474 | Examples |
|
2475 | Examples | |
2475 | -------- |
|
2476 | -------- | |
2476 | To get a plain black and white terminal:: |
|
2477 | To get a plain black and white terminal:: | |
2477 |
|
2478 | |||
2478 | %colors nocolor |
|
2479 | %colors nocolor | |
2479 | """ |
|
2480 | """ | |
2480 |
|
2481 | |||
2481 | def color_switch_err(name): |
|
2482 | def color_switch_err(name): | |
2482 | warn('Error changing %s color schemes.\n%s' % |
|
2483 | warn('Error changing %s color schemes.\n%s' % | |
2483 | (name,sys.exc_info()[1])) |
|
2484 | (name,sys.exc_info()[1])) | |
2484 |
|
2485 | |||
2485 |
|
2486 | |||
2486 | new_scheme = parameter_s.strip() |
|
2487 | new_scheme = parameter_s.strip() | |
2487 | if not new_scheme: |
|
2488 | if not new_scheme: | |
2488 | raise UsageError( |
|
2489 | raise UsageError( | |
2489 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2490 | "%colors: you must specify a color scheme. See '%colors?'") | |
2490 | return |
|
2491 | return | |
2491 | # local shortcut |
|
2492 | # local shortcut | |
2492 | shell = self.shell |
|
2493 | shell = self.shell | |
2493 |
|
2494 | |||
2494 | import IPython.utils.rlineimpl as readline |
|
2495 | import IPython.utils.rlineimpl as readline | |
2495 |
|
2496 | |||
2496 | if not readline.have_readline and sys.platform == "win32": |
|
2497 | if not readline.have_readline and sys.platform == "win32": | |
2497 | msg = """\ |
|
2498 | msg = """\ | |
2498 | Proper color support under MS Windows requires the pyreadline library. |
|
2499 | Proper color support under MS Windows requires the pyreadline library. | |
2499 | You can find it at: |
|
2500 | You can find it at: | |
2500 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2501 | http://ipython.scipy.org/moin/PyReadline/Intro | |
2501 | Gary's readline needs the ctypes module, from: |
|
2502 | Gary's readline needs the ctypes module, from: | |
2502 | http://starship.python.net/crew/theller/ctypes |
|
2503 | http://starship.python.net/crew/theller/ctypes | |
2503 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2504 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2504 |
|
2505 | |||
2505 | Defaulting color scheme to 'NoColor'""" |
|
2506 | Defaulting color scheme to 'NoColor'""" | |
2506 | new_scheme = 'NoColor' |
|
2507 | new_scheme = 'NoColor' | |
2507 | warn(msg) |
|
2508 | warn(msg) | |
2508 |
|
2509 | |||
2509 | # readline option is 0 |
|
2510 | # readline option is 0 | |
2510 | if not shell.has_readline: |
|
2511 | if not shell.has_readline: | |
2511 | new_scheme = 'NoColor' |
|
2512 | new_scheme = 'NoColor' | |
2512 |
|
2513 | |||
2513 | # Set prompt colors |
|
2514 | # Set prompt colors | |
2514 | try: |
|
2515 | try: | |
2515 | shell.displayhook.set_colors(new_scheme) |
|
2516 | shell.displayhook.set_colors(new_scheme) | |
2516 | except: |
|
2517 | except: | |
2517 | color_switch_err('prompt') |
|
2518 | color_switch_err('prompt') | |
2518 | else: |
|
2519 | else: | |
2519 | shell.colors = \ |
|
2520 | shell.colors = \ | |
2520 | shell.displayhook.color_table.active_scheme_name |
|
2521 | shell.displayhook.color_table.active_scheme_name | |
2521 | # Set exception colors |
|
2522 | # Set exception colors | |
2522 | try: |
|
2523 | try: | |
2523 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2524 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2524 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2525 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2525 | except: |
|
2526 | except: | |
2526 | color_switch_err('exception') |
|
2527 | color_switch_err('exception') | |
2527 |
|
2528 | |||
2528 | # Set info (for 'object?') colors |
|
2529 | # Set info (for 'object?') colors | |
2529 | if shell.color_info: |
|
2530 | if shell.color_info: | |
2530 | try: |
|
2531 | try: | |
2531 | shell.inspector.set_active_scheme(new_scheme) |
|
2532 | shell.inspector.set_active_scheme(new_scheme) | |
2532 | except: |
|
2533 | except: | |
2533 | color_switch_err('object inspector') |
|
2534 | color_switch_err('object inspector') | |
2534 | else: |
|
2535 | else: | |
2535 | shell.inspector.set_active_scheme('NoColor') |
|
2536 | shell.inspector.set_active_scheme('NoColor') | |
2536 |
|
2537 | |||
2537 | def magic_pprint(self, parameter_s=''): |
|
2538 | def magic_pprint(self, parameter_s=''): | |
2538 | """Toggle pretty printing on/off.""" |
|
2539 | """Toggle pretty printing on/off.""" | |
2539 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
2540 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
2540 | ptformatter.pprint = bool(1 - ptformatter.pprint) |
|
2541 | ptformatter.pprint = bool(1 - ptformatter.pprint) | |
2541 | print 'Pretty printing has been turned', \ |
|
2542 | print 'Pretty printing has been turned', \ | |
2542 | ['OFF','ON'][ptformatter.pprint] |
|
2543 | ['OFF','ON'][ptformatter.pprint] | |
2543 |
|
2544 | |||
2544 | #...................................................................... |
|
2545 | #...................................................................... | |
2545 | # Functions to implement unix shell-type things |
|
2546 | # Functions to implement unix shell-type things | |
2546 |
|
2547 | |||
2547 | @skip_doctest |
|
2548 | @skip_doctest | |
2548 | def magic_alias(self, parameter_s = ''): |
|
2549 | def magic_alias(self, parameter_s = ''): | |
2549 | """Define an alias for a system command. |
|
2550 | """Define an alias for a system command. | |
2550 |
|
2551 | |||
2551 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2552 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2552 |
|
2553 | |||
2553 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2554 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2554 | params' (from your underlying operating system). |
|
2555 | params' (from your underlying operating system). | |
2555 |
|
2556 | |||
2556 | Aliases have lower precedence than magic functions and Python normal |
|
2557 | Aliases have lower precedence than magic functions and Python normal | |
2557 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2558 | variables, so if 'foo' is both a Python variable and an alias, the | |
2558 | alias can not be executed until 'del foo' removes the Python variable. |
|
2559 | alias can not be executed until 'del foo' removes the Python variable. | |
2559 |
|
2560 | |||
2560 | You can use the %l specifier in an alias definition to represent the |
|
2561 | You can use the %l specifier in an alias definition to represent the | |
2561 | whole line when the alias is called. For example: |
|
2562 | whole line when the alias is called. For example: | |
2562 |
|
2563 | |||
2563 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
2564 | In [2]: alias bracket echo "Input in brackets: <%l>" | |
2564 | In [3]: bracket hello world |
|
2565 | In [3]: bracket hello world | |
2565 | Input in brackets: <hello world> |
|
2566 | Input in brackets: <hello world> | |
2566 |
|
2567 | |||
2567 | You can also define aliases with parameters using %s specifiers (one |
|
2568 | You can also define aliases with parameters using %s specifiers (one | |
2568 | per parameter): |
|
2569 | per parameter): | |
2569 |
|
2570 | |||
2570 | In [1]: alias parts echo first %s second %s |
|
2571 | In [1]: alias parts echo first %s second %s | |
2571 | In [2]: %parts A B |
|
2572 | In [2]: %parts A B | |
2572 | first A second B |
|
2573 | first A second B | |
2573 | In [3]: %parts A |
|
2574 | In [3]: %parts A | |
2574 | Incorrect number of arguments: 2 expected. |
|
2575 | Incorrect number of arguments: 2 expected. | |
2575 | parts is an alias to: 'echo first %s second %s' |
|
2576 | parts is an alias to: 'echo first %s second %s' | |
2576 |
|
2577 | |||
2577 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2578 | Note that %l and %s are mutually exclusive. You can only use one or | |
2578 | the other in your aliases. |
|
2579 | the other in your aliases. | |
2579 |
|
2580 | |||
2580 | Aliases expand Python variables just like system calls using ! or !! |
|
2581 | Aliases expand Python variables just like system calls using ! or !! | |
2581 | do: all expressions prefixed with '$' get expanded. For details of |
|
2582 | do: all expressions prefixed with '$' get expanded. For details of | |
2582 | the semantic rules, see PEP-215: |
|
2583 | the semantic rules, see PEP-215: | |
2583 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2584 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2584 | IPython for variable expansion. If you want to access a true shell |
|
2585 | IPython for variable expansion. If you want to access a true shell | |
2585 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2586 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2586 |
|
2587 | |||
2587 | In [6]: alias show echo |
|
2588 | In [6]: alias show echo | |
2588 | In [7]: PATH='A Python string' |
|
2589 | In [7]: PATH='A Python string' | |
2589 | In [8]: show $PATH |
|
2590 | In [8]: show $PATH | |
2590 | A Python string |
|
2591 | A Python string | |
2591 | In [9]: show $$PATH |
|
2592 | In [9]: show $$PATH | |
2592 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2593 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2593 |
|
2594 | |||
2594 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2595 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2595 | and %rehashx functions, which automatically create aliases for the |
|
2596 | and %rehashx functions, which automatically create aliases for the | |
2596 | contents of your $PATH. |
|
2597 | contents of your $PATH. | |
2597 |
|
2598 | |||
2598 | If called with no parameters, %alias prints the current alias table.""" |
|
2599 | If called with no parameters, %alias prints the current alias table.""" | |
2599 |
|
2600 | |||
2600 | par = parameter_s.strip() |
|
2601 | par = parameter_s.strip() | |
2601 | if not par: |
|
2602 | if not par: | |
2602 | stored = self.db.get('stored_aliases', {} ) |
|
2603 | stored = self.db.get('stored_aliases', {} ) | |
2603 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2604 | aliases = sorted(self.shell.alias_manager.aliases) | |
2604 | # for k, v in stored: |
|
2605 | # for k, v in stored: | |
2605 | # atab.append(k, v[0]) |
|
2606 | # atab.append(k, v[0]) | |
2606 |
|
2607 | |||
2607 | print "Total number of aliases:", len(aliases) |
|
2608 | print "Total number of aliases:", len(aliases) | |
2608 | sys.stdout.flush() |
|
2609 | sys.stdout.flush() | |
2609 | return aliases |
|
2610 | return aliases | |
2610 |
|
2611 | |||
2611 | # Now try to define a new one |
|
2612 | # Now try to define a new one | |
2612 | try: |
|
2613 | try: | |
2613 | alias,cmd = par.split(None, 1) |
|
2614 | alias,cmd = par.split(None, 1) | |
2614 | except: |
|
2615 | except: | |
2615 | print oinspect.getdoc(self.magic_alias) |
|
2616 | print oinspect.getdoc(self.magic_alias) | |
2616 | else: |
|
2617 | else: | |
2617 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2618 | self.shell.alias_manager.soft_define_alias(alias, cmd) | |
2618 | # end magic_alias |
|
2619 | # end magic_alias | |
2619 |
|
2620 | |||
2620 | def magic_unalias(self, parameter_s = ''): |
|
2621 | def magic_unalias(self, parameter_s = ''): | |
2621 | """Remove an alias""" |
|
2622 | """Remove an alias""" | |
2622 |
|
2623 | |||
2623 | aname = parameter_s.strip() |
|
2624 | aname = parameter_s.strip() | |
2624 | self.shell.alias_manager.undefine_alias(aname) |
|
2625 | self.shell.alias_manager.undefine_alias(aname) | |
2625 | stored = self.db.get('stored_aliases', {} ) |
|
2626 | stored = self.db.get('stored_aliases', {} ) | |
2626 | if aname in stored: |
|
2627 | if aname in stored: | |
2627 | print "Removing %stored alias",aname |
|
2628 | print "Removing %stored alias",aname | |
2628 | del stored[aname] |
|
2629 | del stored[aname] | |
2629 | self.db['stored_aliases'] = stored |
|
2630 | self.db['stored_aliases'] = stored | |
2630 |
|
2631 | |||
2631 | def magic_rehashx(self, parameter_s = ''): |
|
2632 | def magic_rehashx(self, parameter_s = ''): | |
2632 | """Update the alias table with all executable files in $PATH. |
|
2633 | """Update the alias table with all executable files in $PATH. | |
2633 |
|
2634 | |||
2634 | This version explicitly checks that every entry in $PATH is a file |
|
2635 | This version explicitly checks that every entry in $PATH is a file | |
2635 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2636 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2636 |
|
2637 | |||
2637 | Under Windows, it checks executability as a match agains a |
|
2638 | Under Windows, it checks executability as a match agains a | |
2638 | '|'-separated string of extensions, stored in the IPython config |
|
2639 | '|'-separated string of extensions, stored in the IPython config | |
2639 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2640 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2640 |
|
2641 | |||
2641 | This function also resets the root module cache of module completer, |
|
2642 | This function also resets the root module cache of module completer, | |
2642 | used on slow filesystems. |
|
2643 | used on slow filesystems. | |
2643 | """ |
|
2644 | """ | |
2644 | from IPython.core.alias import InvalidAliasError |
|
2645 | from IPython.core.alias import InvalidAliasError | |
2645 |
|
2646 | |||
2646 | # for the benefit of module completer in ipy_completers.py |
|
2647 | # for the benefit of module completer in ipy_completers.py | |
2647 | del self.db['rootmodules'] |
|
2648 | del self.db['rootmodules'] | |
2648 |
|
2649 | |||
2649 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2650 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2650 | os.environ.get('PATH','').split(os.pathsep)] |
|
2651 | os.environ.get('PATH','').split(os.pathsep)] | |
2651 | path = filter(os.path.isdir,path) |
|
2652 | path = filter(os.path.isdir,path) | |
2652 |
|
2653 | |||
2653 | syscmdlist = [] |
|
2654 | syscmdlist = [] | |
2654 | # Now define isexec in a cross platform manner. |
|
2655 | # Now define isexec in a cross platform manner. | |
2655 | if os.name == 'posix': |
|
2656 | if os.name == 'posix': | |
2656 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2657 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2657 | os.access(fname,os.X_OK) |
|
2658 | os.access(fname,os.X_OK) | |
2658 | else: |
|
2659 | else: | |
2659 | try: |
|
2660 | try: | |
2660 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2661 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2661 | except KeyError: |
|
2662 | except KeyError: | |
2662 | winext = 'exe|com|bat|py' |
|
2663 | winext = 'exe|com|bat|py' | |
2663 | if 'py' not in winext: |
|
2664 | if 'py' not in winext: | |
2664 | winext += '|py' |
|
2665 | winext += '|py' | |
2665 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2666 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2666 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2667 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2667 | savedir = os.getcwdu() |
|
2668 | savedir = os.getcwdu() | |
2668 |
|
2669 | |||
2669 | # Now walk the paths looking for executables to alias. |
|
2670 | # Now walk the paths looking for executables to alias. | |
2670 | try: |
|
2671 | try: | |
2671 | # write the whole loop for posix/Windows so we don't have an if in |
|
2672 | # write the whole loop for posix/Windows so we don't have an if in | |
2672 | # the innermost part |
|
2673 | # the innermost part | |
2673 | if os.name == 'posix': |
|
2674 | if os.name == 'posix': | |
2674 | for pdir in path: |
|
2675 | for pdir in path: | |
2675 | os.chdir(pdir) |
|
2676 | os.chdir(pdir) | |
2676 | for ff in os.listdir(pdir): |
|
2677 | for ff in os.listdir(pdir): | |
2677 | if isexec(ff): |
|
2678 | if isexec(ff): | |
2678 | try: |
|
2679 | try: | |
2679 | # Removes dots from the name since ipython |
|
2680 | # Removes dots from the name since ipython | |
2680 | # will assume names with dots to be python. |
|
2681 | # will assume names with dots to be python. | |
2681 | self.shell.alias_manager.define_alias( |
|
2682 | self.shell.alias_manager.define_alias( | |
2682 | ff.replace('.',''), ff) |
|
2683 | ff.replace('.',''), ff) | |
2683 | except InvalidAliasError: |
|
2684 | except InvalidAliasError: | |
2684 | pass |
|
2685 | pass | |
2685 | else: |
|
2686 | else: | |
2686 | syscmdlist.append(ff) |
|
2687 | syscmdlist.append(ff) | |
2687 | else: |
|
2688 | else: | |
2688 | no_alias = self.shell.alias_manager.no_alias |
|
2689 | no_alias = self.shell.alias_manager.no_alias | |
2689 | for pdir in path: |
|
2690 | for pdir in path: | |
2690 | os.chdir(pdir) |
|
2691 | os.chdir(pdir) | |
2691 | for ff in os.listdir(pdir): |
|
2692 | for ff in os.listdir(pdir): | |
2692 | base, ext = os.path.splitext(ff) |
|
2693 | base, ext = os.path.splitext(ff) | |
2693 | if isexec(ff) and base.lower() not in no_alias: |
|
2694 | if isexec(ff) and base.lower() not in no_alias: | |
2694 | if ext.lower() == '.exe': |
|
2695 | if ext.lower() == '.exe': | |
2695 | ff = base |
|
2696 | ff = base | |
2696 | try: |
|
2697 | try: | |
2697 | # Removes dots from the name since ipython |
|
2698 | # Removes dots from the name since ipython | |
2698 | # will assume names with dots to be python. |
|
2699 | # will assume names with dots to be python. | |
2699 | self.shell.alias_manager.define_alias( |
|
2700 | self.shell.alias_manager.define_alias( | |
2700 | base.lower().replace('.',''), ff) |
|
2701 | base.lower().replace('.',''), ff) | |
2701 | except InvalidAliasError: |
|
2702 | except InvalidAliasError: | |
2702 | pass |
|
2703 | pass | |
2703 | syscmdlist.append(ff) |
|
2704 | syscmdlist.append(ff) | |
2704 | db = self.db |
|
2705 | db = self.db | |
2705 | db['syscmdlist'] = syscmdlist |
|
2706 | db['syscmdlist'] = syscmdlist | |
2706 | finally: |
|
2707 | finally: | |
2707 | os.chdir(savedir) |
|
2708 | os.chdir(savedir) | |
2708 |
|
2709 | |||
2709 | @skip_doctest |
|
2710 | @skip_doctest | |
2710 | def magic_pwd(self, parameter_s = ''): |
|
2711 | def magic_pwd(self, parameter_s = ''): | |
2711 | """Return the current working directory path. |
|
2712 | """Return the current working directory path. | |
2712 |
|
2713 | |||
2713 | Examples |
|
2714 | Examples | |
2714 | -------- |
|
2715 | -------- | |
2715 | :: |
|
2716 | :: | |
2716 |
|
2717 | |||
2717 | In [9]: pwd |
|
2718 | In [9]: pwd | |
2718 | Out[9]: '/home/tsuser/sprint/ipython' |
|
2719 | Out[9]: '/home/tsuser/sprint/ipython' | |
2719 | """ |
|
2720 | """ | |
2720 | return os.getcwdu() |
|
2721 | return os.getcwdu() | |
2721 |
|
2722 | |||
2722 | @skip_doctest |
|
2723 | @skip_doctest | |
2723 | def magic_cd(self, parameter_s=''): |
|
2724 | def magic_cd(self, parameter_s=''): | |
2724 | """Change the current working directory. |
|
2725 | """Change the current working directory. | |
2725 |
|
2726 | |||
2726 | This command automatically maintains an internal list of directories |
|
2727 | This command automatically maintains an internal list of directories | |
2727 | you visit during your IPython session, in the variable _dh. The |
|
2728 | you visit during your IPython session, in the variable _dh. The | |
2728 | command %dhist shows this history nicely formatted. You can also |
|
2729 | command %dhist shows this history nicely formatted. You can also | |
2729 | do 'cd -<tab>' to see directory history conveniently. |
|
2730 | do 'cd -<tab>' to see directory history conveniently. | |
2730 |
|
2731 | |||
2731 | Usage: |
|
2732 | Usage: | |
2732 |
|
2733 | |||
2733 | cd 'dir': changes to directory 'dir'. |
|
2734 | cd 'dir': changes to directory 'dir'. | |
2734 |
|
2735 | |||
2735 | cd -: changes to the last visited directory. |
|
2736 | cd -: changes to the last visited directory. | |
2736 |
|
2737 | |||
2737 | cd -<n>: changes to the n-th directory in the directory history. |
|
2738 | cd -<n>: changes to the n-th directory in the directory history. | |
2738 |
|
2739 | |||
2739 | cd --foo: change to directory that matches 'foo' in history |
|
2740 | cd --foo: change to directory that matches 'foo' in history | |
2740 |
|
2741 | |||
2741 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2742 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2742 | (note: cd <bookmark_name> is enough if there is no |
|
2743 | (note: cd <bookmark_name> is enough if there is no | |
2743 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2744 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2744 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2745 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
2745 |
|
2746 | |||
2746 | Options: |
|
2747 | Options: | |
2747 |
|
2748 | |||
2748 | -q: quiet. Do not print the working directory after the cd command is |
|
2749 | -q: quiet. Do not print the working directory after the cd command is | |
2749 | executed. By default IPython's cd command does print this directory, |
|
2750 | executed. By default IPython's cd command does print this directory, | |
2750 | since the default prompts do not display path information. |
|
2751 | since the default prompts do not display path information. | |
2751 |
|
2752 | |||
2752 | Note that !cd doesn't work for this purpose because the shell where |
|
2753 | Note that !cd doesn't work for this purpose because the shell where | |
2753 | !command runs is immediately discarded after executing 'command'. |
|
2754 | !command runs is immediately discarded after executing 'command'. | |
2754 |
|
2755 | |||
2755 | Examples |
|
2756 | Examples | |
2756 | -------- |
|
2757 | -------- | |
2757 | :: |
|
2758 | :: | |
2758 |
|
2759 | |||
2759 | In [10]: cd parent/child |
|
2760 | In [10]: cd parent/child | |
2760 | /home/tsuser/parent/child |
|
2761 | /home/tsuser/parent/child | |
2761 | """ |
|
2762 | """ | |
2762 |
|
2763 | |||
2763 | parameter_s = parameter_s.strip() |
|
2764 | parameter_s = parameter_s.strip() | |
2764 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2765 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2765 |
|
2766 | |||
2766 | oldcwd = os.getcwdu() |
|
2767 | oldcwd = os.getcwdu() | |
2767 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2768 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2768 | # jump in directory history by number |
|
2769 | # jump in directory history by number | |
2769 | if numcd: |
|
2770 | if numcd: | |
2770 | nn = int(numcd.group(2)) |
|
2771 | nn = int(numcd.group(2)) | |
2771 | try: |
|
2772 | try: | |
2772 | ps = self.shell.user_ns['_dh'][nn] |
|
2773 | ps = self.shell.user_ns['_dh'][nn] | |
2773 | except IndexError: |
|
2774 | except IndexError: | |
2774 | print 'The requested directory does not exist in history.' |
|
2775 | print 'The requested directory does not exist in history.' | |
2775 | return |
|
2776 | return | |
2776 | else: |
|
2777 | else: | |
2777 | opts = {} |
|
2778 | opts = {} | |
2778 | elif parameter_s.startswith('--'): |
|
2779 | elif parameter_s.startswith('--'): | |
2779 | ps = None |
|
2780 | ps = None | |
2780 | fallback = None |
|
2781 | fallback = None | |
2781 | pat = parameter_s[2:] |
|
2782 | pat = parameter_s[2:] | |
2782 | dh = self.shell.user_ns['_dh'] |
|
2783 | dh = self.shell.user_ns['_dh'] | |
2783 | # first search only by basename (last component) |
|
2784 | # first search only by basename (last component) | |
2784 | for ent in reversed(dh): |
|
2785 | for ent in reversed(dh): | |
2785 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2786 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
2786 | ps = ent |
|
2787 | ps = ent | |
2787 | break |
|
2788 | break | |
2788 |
|
2789 | |||
2789 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2790 | if fallback is None and pat in ent and os.path.isdir(ent): | |
2790 | fallback = ent |
|
2791 | fallback = ent | |
2791 |
|
2792 | |||
2792 | # if we have no last part match, pick the first full path match |
|
2793 | # if we have no last part match, pick the first full path match | |
2793 | if ps is None: |
|
2794 | if ps is None: | |
2794 | ps = fallback |
|
2795 | ps = fallback | |
2795 |
|
2796 | |||
2796 | if ps is None: |
|
2797 | if ps is None: | |
2797 | print "No matching entry in directory history" |
|
2798 | print "No matching entry in directory history" | |
2798 | return |
|
2799 | return | |
2799 | else: |
|
2800 | else: | |
2800 | opts = {} |
|
2801 | opts = {} | |
2801 |
|
2802 | |||
2802 |
|
2803 | |||
2803 | else: |
|
2804 | else: | |
2804 | #turn all non-space-escaping backslashes to slashes, |
|
2805 | #turn all non-space-escaping backslashes to slashes, | |
2805 | # for c:\windows\directory\names\ |
|
2806 | # for c:\windows\directory\names\ | |
2806 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2807 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2807 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2808 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2808 | # jump to previous |
|
2809 | # jump to previous | |
2809 | if ps == '-': |
|
2810 | if ps == '-': | |
2810 | try: |
|
2811 | try: | |
2811 | ps = self.shell.user_ns['_dh'][-2] |
|
2812 | ps = self.shell.user_ns['_dh'][-2] | |
2812 | except IndexError: |
|
2813 | except IndexError: | |
2813 | raise UsageError('%cd -: No previous directory to change to.') |
|
2814 | raise UsageError('%cd -: No previous directory to change to.') | |
2814 | # jump to bookmark if needed |
|
2815 | # jump to bookmark if needed | |
2815 | else: |
|
2816 | else: | |
2816 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2817 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2817 | bkms = self.db.get('bookmarks', {}) |
|
2818 | bkms = self.db.get('bookmarks', {}) | |
2818 |
|
2819 | |||
2819 | if bkms.has_key(ps): |
|
2820 | if bkms.has_key(ps): | |
2820 | target = bkms[ps] |
|
2821 | target = bkms[ps] | |
2821 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2822 | print '(bookmark:%s) -> %s' % (ps,target) | |
2822 | ps = target |
|
2823 | ps = target | |
2823 | else: |
|
2824 | else: | |
2824 | if opts.has_key('b'): |
|
2825 | if opts.has_key('b'): | |
2825 | raise UsageError("Bookmark '%s' not found. " |
|
2826 | raise UsageError("Bookmark '%s' not found. " | |
2826 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2827 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2827 |
|
2828 | |||
2828 | # strip extra quotes on Windows, because os.chdir doesn't like them |
|
2829 | # strip extra quotes on Windows, because os.chdir doesn't like them | |
2829 | if sys.platform == 'win32': |
|
2830 | if sys.platform == 'win32': | |
2830 | ps = ps.strip('\'"') |
|
2831 | ps = ps.strip('\'"') | |
2831 | # at this point ps should point to the target dir |
|
2832 | # at this point ps should point to the target dir | |
2832 | if ps: |
|
2833 | if ps: | |
2833 | try: |
|
2834 | try: | |
2834 | os.chdir(os.path.expanduser(ps)) |
|
2835 | os.chdir(os.path.expanduser(ps)) | |
2835 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2836 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2836 | set_term_title('IPython: ' + abbrev_cwd()) |
|
2837 | set_term_title('IPython: ' + abbrev_cwd()) | |
2837 | except OSError: |
|
2838 | except OSError: | |
2838 | print sys.exc_info()[1] |
|
2839 | print sys.exc_info()[1] | |
2839 | else: |
|
2840 | else: | |
2840 | cwd = os.getcwdu() |
|
2841 | cwd = os.getcwdu() | |
2841 | dhist = self.shell.user_ns['_dh'] |
|
2842 | dhist = self.shell.user_ns['_dh'] | |
2842 | if oldcwd != cwd: |
|
2843 | if oldcwd != cwd: | |
2843 | dhist.append(cwd) |
|
2844 | dhist.append(cwd) | |
2844 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2845 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2845 |
|
2846 | |||
2846 | else: |
|
2847 | else: | |
2847 | os.chdir(self.shell.home_dir) |
|
2848 | os.chdir(self.shell.home_dir) | |
2848 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2849 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2849 | set_term_title('IPython: ' + '~') |
|
2850 | set_term_title('IPython: ' + '~') | |
2850 | cwd = os.getcwdu() |
|
2851 | cwd = os.getcwdu() | |
2851 | dhist = self.shell.user_ns['_dh'] |
|
2852 | dhist = self.shell.user_ns['_dh'] | |
2852 |
|
2853 | |||
2853 | if oldcwd != cwd: |
|
2854 | if oldcwd != cwd: | |
2854 | dhist.append(cwd) |
|
2855 | dhist.append(cwd) | |
2855 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2856 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2856 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2857 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
2857 | print self.shell.user_ns['_dh'][-1] |
|
2858 | print self.shell.user_ns['_dh'][-1] | |
2858 |
|
2859 | |||
2859 |
|
2860 | |||
2860 | def magic_env(self, parameter_s=''): |
|
2861 | def magic_env(self, parameter_s=''): | |
2861 | """List environment variables.""" |
|
2862 | """List environment variables.""" | |
2862 |
|
2863 | |||
2863 | return os.environ.data |
|
2864 | return os.environ.data | |
2864 |
|
2865 | |||
2865 | def magic_pushd(self, parameter_s=''): |
|
2866 | def magic_pushd(self, parameter_s=''): | |
2866 | """Place the current dir on stack and change directory. |
|
2867 | """Place the current dir on stack and change directory. | |
2867 |
|
2868 | |||
2868 | Usage:\\ |
|
2869 | Usage:\\ | |
2869 | %pushd ['dirname'] |
|
2870 | %pushd ['dirname'] | |
2870 | """ |
|
2871 | """ | |
2871 |
|
2872 | |||
2872 | dir_s = self.shell.dir_stack |
|
2873 | dir_s = self.shell.dir_stack | |
2873 | tgt = os.path.expanduser(parameter_s) |
|
2874 | tgt = os.path.expanduser(parameter_s) | |
2874 | cwd = os.getcwdu().replace(self.home_dir,'~') |
|
2875 | cwd = os.getcwdu().replace(self.home_dir,'~') | |
2875 | if tgt: |
|
2876 | if tgt: | |
2876 | self.magic_cd(parameter_s) |
|
2877 | self.magic_cd(parameter_s) | |
2877 | dir_s.insert(0,cwd) |
|
2878 | dir_s.insert(0,cwd) | |
2878 | return self.magic_dirs() |
|
2879 | return self.magic_dirs() | |
2879 |
|
2880 | |||
2880 | def magic_popd(self, parameter_s=''): |
|
2881 | def magic_popd(self, parameter_s=''): | |
2881 | """Change to directory popped off the top of the stack. |
|
2882 | """Change to directory popped off the top of the stack. | |
2882 | """ |
|
2883 | """ | |
2883 | if not self.shell.dir_stack: |
|
2884 | if not self.shell.dir_stack: | |
2884 | raise UsageError("%popd on empty stack") |
|
2885 | raise UsageError("%popd on empty stack") | |
2885 | top = self.shell.dir_stack.pop(0) |
|
2886 | top = self.shell.dir_stack.pop(0) | |
2886 | self.magic_cd(top) |
|
2887 | self.magic_cd(top) | |
2887 | print "popd ->",top |
|
2888 | print "popd ->",top | |
2888 |
|
2889 | |||
2889 | def magic_dirs(self, parameter_s=''): |
|
2890 | def magic_dirs(self, parameter_s=''): | |
2890 | """Return the current directory stack.""" |
|
2891 | """Return the current directory stack.""" | |
2891 |
|
2892 | |||
2892 | return self.shell.dir_stack |
|
2893 | return self.shell.dir_stack | |
2893 |
|
2894 | |||
2894 | def magic_dhist(self, parameter_s=''): |
|
2895 | def magic_dhist(self, parameter_s=''): | |
2895 | """Print your history of visited directories. |
|
2896 | """Print your history of visited directories. | |
2896 |
|
2897 | |||
2897 | %dhist -> print full history\\ |
|
2898 | %dhist -> print full history\\ | |
2898 | %dhist n -> print last n entries only\\ |
|
2899 | %dhist n -> print last n entries only\\ | |
2899 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2900 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2900 |
|
2901 | |||
2901 | This history is automatically maintained by the %cd command, and |
|
2902 | This history is automatically maintained by the %cd command, and | |
2902 | always available as the global list variable _dh. You can use %cd -<n> |
|
2903 | always available as the global list variable _dh. You can use %cd -<n> | |
2903 | to go to directory number <n>. |
|
2904 | to go to directory number <n>. | |
2904 |
|
2905 | |||
2905 | Note that most of time, you should view directory history by entering |
|
2906 | Note that most of time, you should view directory history by entering | |
2906 | cd -<TAB>. |
|
2907 | cd -<TAB>. | |
2907 |
|
2908 | |||
2908 | """ |
|
2909 | """ | |
2909 |
|
2910 | |||
2910 | dh = self.shell.user_ns['_dh'] |
|
2911 | dh = self.shell.user_ns['_dh'] | |
2911 | if parameter_s: |
|
2912 | if parameter_s: | |
2912 | try: |
|
2913 | try: | |
2913 | args = map(int,parameter_s.split()) |
|
2914 | args = map(int,parameter_s.split()) | |
2914 | except: |
|
2915 | except: | |
2915 | self.arg_err(Magic.magic_dhist) |
|
2916 | self.arg_err(Magic.magic_dhist) | |
2916 | return |
|
2917 | return | |
2917 | if len(args) == 1: |
|
2918 | if len(args) == 1: | |
2918 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2919 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2919 | elif len(args) == 2: |
|
2920 | elif len(args) == 2: | |
2920 | ini,fin = args |
|
2921 | ini,fin = args | |
2921 | else: |
|
2922 | else: | |
2922 | self.arg_err(Magic.magic_dhist) |
|
2923 | self.arg_err(Magic.magic_dhist) | |
2923 | return |
|
2924 | return | |
2924 | else: |
|
2925 | else: | |
2925 | ini,fin = 0,len(dh) |
|
2926 | ini,fin = 0,len(dh) | |
2926 | nlprint(dh, |
|
2927 | nlprint(dh, | |
2927 | header = 'Directory history (kept in _dh)', |
|
2928 | header = 'Directory history (kept in _dh)', | |
2928 | start=ini,stop=fin) |
|
2929 | start=ini,stop=fin) | |
2929 |
|
2930 | |||
2930 | @skip_doctest |
|
2931 | @skip_doctest | |
2931 | def magic_sc(self, parameter_s=''): |
|
2932 | def magic_sc(self, parameter_s=''): | |
2932 | """Shell capture - execute a shell command and capture its output. |
|
2933 | """Shell capture - execute a shell command and capture its output. | |
2933 |
|
2934 | |||
2934 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2935 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2935 |
|
2936 | |||
2936 | You should use the form 'var = !command' instead. Example: |
|
2937 | You should use the form 'var = !command' instead. Example: | |
2937 |
|
2938 | |||
2938 | "%sc -l myfiles = ls ~" should now be written as |
|
2939 | "%sc -l myfiles = ls ~" should now be written as | |
2939 |
|
2940 | |||
2940 | "myfiles = !ls ~" |
|
2941 | "myfiles = !ls ~" | |
2941 |
|
2942 | |||
2942 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2943 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2943 | below. |
|
2944 | below. | |
2944 |
|
2945 | |||
2945 | -- |
|
2946 | -- | |
2946 | %sc [options] varname=command |
|
2947 | %sc [options] varname=command | |
2947 |
|
2948 | |||
2948 | IPython will run the given command using commands.getoutput(), and |
|
2949 | IPython will run the given command using commands.getoutput(), and | |
2949 | will then update the user's interactive namespace with a variable |
|
2950 | will then update the user's interactive namespace with a variable | |
2950 | called varname, containing the value of the call. Your command can |
|
2951 | called varname, containing the value of the call. Your command can | |
2951 | contain shell wildcards, pipes, etc. |
|
2952 | contain shell wildcards, pipes, etc. | |
2952 |
|
2953 | |||
2953 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2954 | The '=' sign in the syntax is mandatory, and the variable name you | |
2954 | supply must follow Python's standard conventions for valid names. |
|
2955 | supply must follow Python's standard conventions for valid names. | |
2955 |
|
2956 | |||
2956 | (A special format without variable name exists for internal use) |
|
2957 | (A special format without variable name exists for internal use) | |
2957 |
|
2958 | |||
2958 | Options: |
|
2959 | Options: | |
2959 |
|
2960 | |||
2960 | -l: list output. Split the output on newlines into a list before |
|
2961 | -l: list output. Split the output on newlines into a list before | |
2961 | assigning it to the given variable. By default the output is stored |
|
2962 | assigning it to the given variable. By default the output is stored | |
2962 | as a single string. |
|
2963 | as a single string. | |
2963 |
|
2964 | |||
2964 | -v: verbose. Print the contents of the variable. |
|
2965 | -v: verbose. Print the contents of the variable. | |
2965 |
|
2966 | |||
2966 | In most cases you should not need to split as a list, because the |
|
2967 | In most cases you should not need to split as a list, because the | |
2967 | returned value is a special type of string which can automatically |
|
2968 | returned value is a special type of string which can automatically | |
2968 | provide its contents either as a list (split on newlines) or as a |
|
2969 | provide its contents either as a list (split on newlines) or as a | |
2969 | space-separated string. These are convenient, respectively, either |
|
2970 | space-separated string. These are convenient, respectively, either | |
2970 | for sequential processing or to be passed to a shell command. |
|
2971 | for sequential processing or to be passed to a shell command. | |
2971 |
|
2972 | |||
2972 | For example: |
|
2973 | For example: | |
2973 |
|
2974 | |||
2974 | # all-random |
|
2975 | # all-random | |
2975 |
|
2976 | |||
2976 | # Capture into variable a |
|
2977 | # Capture into variable a | |
2977 | In [1]: sc a=ls *py |
|
2978 | In [1]: sc a=ls *py | |
2978 |
|
2979 | |||
2979 | # a is a string with embedded newlines |
|
2980 | # a is a string with embedded newlines | |
2980 | In [2]: a |
|
2981 | In [2]: a | |
2981 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
2982 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
2982 |
|
2983 | |||
2983 | # which can be seen as a list: |
|
2984 | # which can be seen as a list: | |
2984 | In [3]: a.l |
|
2985 | In [3]: a.l | |
2985 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
2986 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
2986 |
|
2987 | |||
2987 | # or as a whitespace-separated string: |
|
2988 | # or as a whitespace-separated string: | |
2988 | In [4]: a.s |
|
2989 | In [4]: a.s | |
2989 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
2990 | Out[4]: 'setup.py win32_manual_post_install.py' | |
2990 |
|
2991 | |||
2991 | # a.s is useful to pass as a single command line: |
|
2992 | # a.s is useful to pass as a single command line: | |
2992 | In [5]: !wc -l $a.s |
|
2993 | In [5]: !wc -l $a.s | |
2993 | 146 setup.py |
|
2994 | 146 setup.py | |
2994 | 130 win32_manual_post_install.py |
|
2995 | 130 win32_manual_post_install.py | |
2995 | 276 total |
|
2996 | 276 total | |
2996 |
|
2997 | |||
2997 | # while the list form is useful to loop over: |
|
2998 | # while the list form is useful to loop over: | |
2998 | In [6]: for f in a.l: |
|
2999 | In [6]: for f in a.l: | |
2999 | ...: !wc -l $f |
|
3000 | ...: !wc -l $f | |
3000 | ...: |
|
3001 | ...: | |
3001 | 146 setup.py |
|
3002 | 146 setup.py | |
3002 | 130 win32_manual_post_install.py |
|
3003 | 130 win32_manual_post_install.py | |
3003 |
|
3004 | |||
3004 | Similiarly, the lists returned by the -l option are also special, in |
|
3005 | Similiarly, the lists returned by the -l option are also special, in | |
3005 | the sense that you can equally invoke the .s attribute on them to |
|
3006 | the sense that you can equally invoke the .s attribute on them to | |
3006 | automatically get a whitespace-separated string from their contents: |
|
3007 | automatically get a whitespace-separated string from their contents: | |
3007 |
|
3008 | |||
3008 | In [7]: sc -l b=ls *py |
|
3009 | In [7]: sc -l b=ls *py | |
3009 |
|
3010 | |||
3010 | In [8]: b |
|
3011 | In [8]: b | |
3011 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
3012 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
3012 |
|
3013 | |||
3013 | In [9]: b.s |
|
3014 | In [9]: b.s | |
3014 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
3015 | Out[9]: 'setup.py win32_manual_post_install.py' | |
3015 |
|
3016 | |||
3016 | In summary, both the lists and strings used for ouptut capture have |
|
3017 | In summary, both the lists and strings used for ouptut capture have | |
3017 | the following special attributes: |
|
3018 | the following special attributes: | |
3018 |
|
3019 | |||
3019 | .l (or .list) : value as list. |
|
3020 | .l (or .list) : value as list. | |
3020 | .n (or .nlstr): value as newline-separated string. |
|
3021 | .n (or .nlstr): value as newline-separated string. | |
3021 | .s (or .spstr): value as space-separated string. |
|
3022 | .s (or .spstr): value as space-separated string. | |
3022 | """ |
|
3023 | """ | |
3023 |
|
3024 | |||
3024 | opts,args = self.parse_options(parameter_s,'lv') |
|
3025 | opts,args = self.parse_options(parameter_s,'lv') | |
3025 | # Try to get a variable name and command to run |
|
3026 | # Try to get a variable name and command to run | |
3026 | try: |
|
3027 | try: | |
3027 | # the variable name must be obtained from the parse_options |
|
3028 | # the variable name must be obtained from the parse_options | |
3028 | # output, which uses shlex.split to strip options out. |
|
3029 | # output, which uses shlex.split to strip options out. | |
3029 | var,_ = args.split('=',1) |
|
3030 | var,_ = args.split('=',1) | |
3030 | var = var.strip() |
|
3031 | var = var.strip() | |
3031 | # But the the command has to be extracted from the original input |
|
3032 | # But the the command has to be extracted from the original input | |
3032 | # parameter_s, not on what parse_options returns, to avoid the |
|
3033 | # parameter_s, not on what parse_options returns, to avoid the | |
3033 | # quote stripping which shlex.split performs on it. |
|
3034 | # quote stripping which shlex.split performs on it. | |
3034 | _,cmd = parameter_s.split('=',1) |
|
3035 | _,cmd = parameter_s.split('=',1) | |
3035 | except ValueError: |
|
3036 | except ValueError: | |
3036 | var,cmd = '','' |
|
3037 | var,cmd = '','' | |
3037 | # If all looks ok, proceed |
|
3038 | # If all looks ok, proceed | |
3038 | split = 'l' in opts |
|
3039 | split = 'l' in opts | |
3039 | out = self.shell.getoutput(cmd, split=split) |
|
3040 | out = self.shell.getoutput(cmd, split=split) | |
3040 | if opts.has_key('v'): |
|
3041 | if opts.has_key('v'): | |
3041 | print '%s ==\n%s' % (var,pformat(out)) |
|
3042 | print '%s ==\n%s' % (var,pformat(out)) | |
3042 | if var: |
|
3043 | if var: | |
3043 | self.shell.user_ns.update({var:out}) |
|
3044 | self.shell.user_ns.update({var:out}) | |
3044 | else: |
|
3045 | else: | |
3045 | return out |
|
3046 | return out | |
3046 |
|
3047 | |||
3047 | def magic_sx(self, parameter_s=''): |
|
3048 | def magic_sx(self, parameter_s=''): | |
3048 | """Shell execute - run a shell command and capture its output. |
|
3049 | """Shell execute - run a shell command and capture its output. | |
3049 |
|
3050 | |||
3050 | %sx command |
|
3051 | %sx command | |
3051 |
|
3052 | |||
3052 | IPython will run the given command using commands.getoutput(), and |
|
3053 | IPython will run the given command using commands.getoutput(), and | |
3053 | return the result formatted as a list (split on '\\n'). Since the |
|
3054 | return the result formatted as a list (split on '\\n'). Since the | |
3054 | output is _returned_, it will be stored in ipython's regular output |
|
3055 | output is _returned_, it will be stored in ipython's regular output | |
3055 | cache Out[N] and in the '_N' automatic variables. |
|
3056 | cache Out[N] and in the '_N' automatic variables. | |
3056 |
|
3057 | |||
3057 | Notes: |
|
3058 | Notes: | |
3058 |
|
3059 | |||
3059 | 1) If an input line begins with '!!', then %sx is automatically |
|
3060 | 1) If an input line begins with '!!', then %sx is automatically | |
3060 | invoked. That is, while: |
|
3061 | invoked. That is, while: | |
3061 | !ls |
|
3062 | !ls | |
3062 | causes ipython to simply issue system('ls'), typing |
|
3063 | causes ipython to simply issue system('ls'), typing | |
3063 | !!ls |
|
3064 | !!ls | |
3064 | is a shorthand equivalent to: |
|
3065 | is a shorthand equivalent to: | |
3065 | %sx ls |
|
3066 | %sx ls | |
3066 |
|
3067 | |||
3067 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3068 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
3068 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3069 | like '%sc -l'. The reason for this is to make it as easy as possible | |
3069 | to process line-oriented shell output via further python commands. |
|
3070 | to process line-oriented shell output via further python commands. | |
3070 | %sc is meant to provide much finer control, but requires more |
|
3071 | %sc is meant to provide much finer control, but requires more | |
3071 | typing. |
|
3072 | typing. | |
3072 |
|
3073 | |||
3073 | 3) Just like %sc -l, this is a list with special attributes: |
|
3074 | 3) Just like %sc -l, this is a list with special attributes: | |
3074 |
|
3075 | |||
3075 | .l (or .list) : value as list. |
|
3076 | .l (or .list) : value as list. | |
3076 | .n (or .nlstr): value as newline-separated string. |
|
3077 | .n (or .nlstr): value as newline-separated string. | |
3077 | .s (or .spstr): value as whitespace-separated string. |
|
3078 | .s (or .spstr): value as whitespace-separated string. | |
3078 |
|
3079 | |||
3079 | This is very useful when trying to use such lists as arguments to |
|
3080 | This is very useful when trying to use such lists as arguments to | |
3080 | system commands.""" |
|
3081 | system commands.""" | |
3081 |
|
3082 | |||
3082 | if parameter_s: |
|
3083 | if parameter_s: | |
3083 | return self.shell.getoutput(parameter_s) |
|
3084 | return self.shell.getoutput(parameter_s) | |
3084 |
|
3085 | |||
3085 |
|
3086 | |||
3086 | def magic_bookmark(self, parameter_s=''): |
|
3087 | def magic_bookmark(self, parameter_s=''): | |
3087 | """Manage IPython's bookmark system. |
|
3088 | """Manage IPython's bookmark system. | |
3088 |
|
3089 | |||
3089 | %bookmark <name> - set bookmark to current dir |
|
3090 | %bookmark <name> - set bookmark to current dir | |
3090 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3091 | %bookmark <name> <dir> - set bookmark to <dir> | |
3091 | %bookmark -l - list all bookmarks |
|
3092 | %bookmark -l - list all bookmarks | |
3092 | %bookmark -d <name> - remove bookmark |
|
3093 | %bookmark -d <name> - remove bookmark | |
3093 | %bookmark -r - remove all bookmarks |
|
3094 | %bookmark -r - remove all bookmarks | |
3094 |
|
3095 | |||
3095 | You can later on access a bookmarked folder with: |
|
3096 | You can later on access a bookmarked folder with: | |
3096 | %cd -b <name> |
|
3097 | %cd -b <name> | |
3097 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3098 | or simply '%cd <name>' if there is no directory called <name> AND | |
3098 | there is such a bookmark defined. |
|
3099 | there is such a bookmark defined. | |
3099 |
|
3100 | |||
3100 | Your bookmarks persist through IPython sessions, but they are |
|
3101 | Your bookmarks persist through IPython sessions, but they are | |
3101 | associated with each profile.""" |
|
3102 | associated with each profile.""" | |
3102 |
|
3103 | |||
3103 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3104 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
3104 | if len(args) > 2: |
|
3105 | if len(args) > 2: | |
3105 | raise UsageError("%bookmark: too many arguments") |
|
3106 | raise UsageError("%bookmark: too many arguments") | |
3106 |
|
3107 | |||
3107 | bkms = self.db.get('bookmarks',{}) |
|
3108 | bkms = self.db.get('bookmarks',{}) | |
3108 |
|
3109 | |||
3109 | if opts.has_key('d'): |
|
3110 | if opts.has_key('d'): | |
3110 | try: |
|
3111 | try: | |
3111 | todel = args[0] |
|
3112 | todel = args[0] | |
3112 | except IndexError: |
|
3113 | except IndexError: | |
3113 | raise UsageError( |
|
3114 | raise UsageError( | |
3114 | "%bookmark -d: must provide a bookmark to delete") |
|
3115 | "%bookmark -d: must provide a bookmark to delete") | |
3115 | else: |
|
3116 | else: | |
3116 | try: |
|
3117 | try: | |
3117 | del bkms[todel] |
|
3118 | del bkms[todel] | |
3118 | except KeyError: |
|
3119 | except KeyError: | |
3119 | raise UsageError( |
|
3120 | raise UsageError( | |
3120 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3121 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
3121 |
|
3122 | |||
3122 | elif opts.has_key('r'): |
|
3123 | elif opts.has_key('r'): | |
3123 | bkms = {} |
|
3124 | bkms = {} | |
3124 | elif opts.has_key('l'): |
|
3125 | elif opts.has_key('l'): | |
3125 | bks = bkms.keys() |
|
3126 | bks = bkms.keys() | |
3126 | bks.sort() |
|
3127 | bks.sort() | |
3127 | if bks: |
|
3128 | if bks: | |
3128 | size = max(map(len,bks)) |
|
3129 | size = max(map(len,bks)) | |
3129 | else: |
|
3130 | else: | |
3130 | size = 0 |
|
3131 | size = 0 | |
3131 | fmt = '%-'+str(size)+'s -> %s' |
|
3132 | fmt = '%-'+str(size)+'s -> %s' | |
3132 | print 'Current bookmarks:' |
|
3133 | print 'Current bookmarks:' | |
3133 | for bk in bks: |
|
3134 | for bk in bks: | |
3134 | print fmt % (bk,bkms[bk]) |
|
3135 | print fmt % (bk,bkms[bk]) | |
3135 | else: |
|
3136 | else: | |
3136 | if not args: |
|
3137 | if not args: | |
3137 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3138 | raise UsageError("%bookmark: You must specify the bookmark name") | |
3138 | elif len(args)==1: |
|
3139 | elif len(args)==1: | |
3139 | bkms[args[0]] = os.getcwdu() |
|
3140 | bkms[args[0]] = os.getcwdu() | |
3140 | elif len(args)==2: |
|
3141 | elif len(args)==2: | |
3141 | bkms[args[0]] = args[1] |
|
3142 | bkms[args[0]] = args[1] | |
3142 | self.db['bookmarks'] = bkms |
|
3143 | self.db['bookmarks'] = bkms | |
3143 |
|
3144 | |||
3144 | def magic_pycat(self, parameter_s=''): |
|
3145 | def magic_pycat(self, parameter_s=''): | |
3145 | """Show a syntax-highlighted file through a pager. |
|
3146 | """Show a syntax-highlighted file through a pager. | |
3146 |
|
3147 | |||
3147 | This magic is similar to the cat utility, but it will assume the file |
|
3148 | This magic is similar to the cat utility, but it will assume the file | |
3148 | to be Python source and will show it with syntax highlighting. """ |
|
3149 | to be Python source and will show it with syntax highlighting. """ | |
3149 |
|
3150 | |||
3150 | try: |
|
3151 | try: | |
3151 | filename = get_py_filename(parameter_s) |
|
3152 | filename = get_py_filename(parameter_s) | |
3152 | cont = file_read(filename) |
|
3153 | cont = file_read(filename) | |
3153 | except IOError: |
|
3154 | except IOError: | |
3154 | try: |
|
3155 | try: | |
3155 | cont = eval(parameter_s,self.user_ns) |
|
3156 | cont = eval(parameter_s,self.user_ns) | |
3156 | except NameError: |
|
3157 | except NameError: | |
3157 | cont = None |
|
3158 | cont = None | |
3158 | if cont is None: |
|
3159 | if cont is None: | |
3159 | print "Error: no such file or variable" |
|
3160 | print "Error: no such file or variable" | |
3160 | return |
|
3161 | return | |
3161 |
|
3162 | |||
3162 | page.page(self.shell.pycolorize(cont)) |
|
3163 | page.page(self.shell.pycolorize(cont)) | |
3163 |
|
3164 | |||
3164 | def _rerun_pasted(self): |
|
3165 | def _rerun_pasted(self): | |
3165 | """ Rerun a previously pasted command. |
|
3166 | """ Rerun a previously pasted command. | |
3166 | """ |
|
3167 | """ | |
3167 | b = self.user_ns.get('pasted_block', None) |
|
3168 | b = self.user_ns.get('pasted_block', None) | |
3168 | if b is None: |
|
3169 | if b is None: | |
3169 | raise UsageError('No previous pasted block available') |
|
3170 | raise UsageError('No previous pasted block available') | |
3170 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3171 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) | |
3171 | exec b in self.user_ns |
|
3172 | exec b in self.user_ns | |
3172 |
|
3173 | |||
3173 | def _get_pasted_lines(self, sentinel): |
|
3174 | def _get_pasted_lines(self, sentinel): | |
3174 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3175 | """ Yield pasted lines until the user enters the given sentinel value. | |
3175 | """ |
|
3176 | """ | |
3176 | from IPython.core import interactiveshell |
|
3177 | from IPython.core import interactiveshell | |
3177 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3178 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
3178 | while True: |
|
3179 | while True: | |
3179 | l = interactiveshell.raw_input_original(':') |
|
3180 | l = interactiveshell.raw_input_original(':') | |
3180 | if l == sentinel: |
|
3181 | if l == sentinel: | |
3181 | return |
|
3182 | return | |
3182 | else: |
|
3183 | else: | |
3183 | yield l |
|
3184 | yield l | |
3184 |
|
3185 | |||
3185 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3186 | def _strip_pasted_lines_for_code(self, raw_lines): | |
3186 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3187 | """ Strip non-code parts of a sequence of lines to return a block of | |
3187 | code. |
|
3188 | code. | |
3188 | """ |
|
3189 | """ | |
3189 | # Regular expressions that declare text we strip from the input: |
|
3190 | # Regular expressions that declare text we strip from the input: | |
3190 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3191 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt | |
3191 | r'^\s*(\s?>)+', # Python input prompt |
|
3192 | r'^\s*(\s?>)+', # Python input prompt | |
3192 | r'^\s*\.{3,}', # Continuation prompts |
|
3193 | r'^\s*\.{3,}', # Continuation prompts | |
3193 | r'^\++', |
|
3194 | r'^\++', | |
3194 | ] |
|
3195 | ] | |
3195 |
|
3196 | |||
3196 | strip_from_start = map(re.compile,strip_re) |
|
3197 | strip_from_start = map(re.compile,strip_re) | |
3197 |
|
3198 | |||
3198 | lines = [] |
|
3199 | lines = [] | |
3199 | for l in raw_lines: |
|
3200 | for l in raw_lines: | |
3200 | for pat in strip_from_start: |
|
3201 | for pat in strip_from_start: | |
3201 | l = pat.sub('',l) |
|
3202 | l = pat.sub('',l) | |
3202 | lines.append(l) |
|
3203 | lines.append(l) | |
3203 |
|
3204 | |||
3204 | block = "\n".join(lines) + '\n' |
|
3205 | block = "\n".join(lines) + '\n' | |
3205 | #print "block:\n",block |
|
3206 | #print "block:\n",block | |
3206 | return block |
|
3207 | return block | |
3207 |
|
3208 | |||
3208 | def _execute_block(self, block, par): |
|
3209 | def _execute_block(self, block, par): | |
3209 | """ Execute a block, or store it in a variable, per the user's request. |
|
3210 | """ Execute a block, or store it in a variable, per the user's request. | |
3210 | """ |
|
3211 | """ | |
3211 | if not par: |
|
3212 | if not par: | |
3212 | b = textwrap.dedent(block) |
|
3213 | b = textwrap.dedent(block) | |
3213 | self.user_ns['pasted_block'] = b |
|
3214 | self.user_ns['pasted_block'] = b | |
3214 | exec b in self.user_ns |
|
3215 | exec b in self.user_ns | |
3215 | else: |
|
3216 | else: | |
3216 | self.user_ns[par] = SList(block.splitlines()) |
|
3217 | self.user_ns[par] = SList(block.splitlines()) | |
3217 | print "Block assigned to '%s'" % par |
|
3218 | print "Block assigned to '%s'" % par | |
3218 |
|
3219 | |||
3219 | def magic_quickref(self,arg): |
|
3220 | def magic_quickref(self,arg): | |
3220 | """ Show a quick reference sheet """ |
|
3221 | """ Show a quick reference sheet """ | |
3221 | import IPython.core.usage |
|
3222 | import IPython.core.usage | |
3222 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3223 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') | |
3223 |
|
3224 | |||
3224 | page.page(qr) |
|
3225 | page.page(qr) | |
3225 |
|
3226 | |||
3226 | def magic_doctest_mode(self,parameter_s=''): |
|
3227 | def magic_doctest_mode(self,parameter_s=''): | |
3227 | """Toggle doctest mode on and off. |
|
3228 | """Toggle doctest mode on and off. | |
3228 |
|
3229 | |||
3229 | This mode is intended to make IPython behave as much as possible like a |
|
3230 | This mode is intended to make IPython behave as much as possible like a | |
3230 | plain Python shell, from the perspective of how its prompts, exceptions |
|
3231 | plain Python shell, from the perspective of how its prompts, exceptions | |
3231 | and output look. This makes it easy to copy and paste parts of a |
|
3232 | and output look. This makes it easy to copy and paste parts of a | |
3232 | session into doctests. It does so by: |
|
3233 | session into doctests. It does so by: | |
3233 |
|
3234 | |||
3234 | - Changing the prompts to the classic ``>>>`` ones. |
|
3235 | - Changing the prompts to the classic ``>>>`` ones. | |
3235 | - Changing the exception reporting mode to 'Plain'. |
|
3236 | - Changing the exception reporting mode to 'Plain'. | |
3236 | - Disabling pretty-printing of output. |
|
3237 | - Disabling pretty-printing of output. | |
3237 |
|
3238 | |||
3238 | Note that IPython also supports the pasting of code snippets that have |
|
3239 | Note that IPython also supports the pasting of code snippets that have | |
3239 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
3240 | leading '>>>' and '...' prompts in them. This means that you can paste | |
3240 | doctests from files or docstrings (even if they have leading |
|
3241 | doctests from files or docstrings (even if they have leading | |
3241 | whitespace), and the code will execute correctly. You can then use |
|
3242 | whitespace), and the code will execute correctly. You can then use | |
3242 | '%history -t' to see the translated history; this will give you the |
|
3243 | '%history -t' to see the translated history; this will give you the | |
3243 | input after removal of all the leading prompts and whitespace, which |
|
3244 | input after removal of all the leading prompts and whitespace, which | |
3244 | can be pasted back into an editor. |
|
3245 | can be pasted back into an editor. | |
3245 |
|
3246 | |||
3246 | With these features, you can switch into this mode easily whenever you |
|
3247 | With these features, you can switch into this mode easily whenever you | |
3247 | need to do testing and changes to doctests, without having to leave |
|
3248 | need to do testing and changes to doctests, without having to leave | |
3248 | your existing IPython session. |
|
3249 | your existing IPython session. | |
3249 | """ |
|
3250 | """ | |
3250 |
|
3251 | |||
3251 | from IPython.utils.ipstruct import Struct |
|
3252 | from IPython.utils.ipstruct import Struct | |
3252 |
|
3253 | |||
3253 | # Shorthands |
|
3254 | # Shorthands | |
3254 | shell = self.shell |
|
3255 | shell = self.shell | |
3255 | oc = shell.displayhook |
|
3256 | oc = shell.displayhook | |
3256 | meta = shell.meta |
|
3257 | meta = shell.meta | |
3257 | disp_formatter = self.shell.display_formatter |
|
3258 | disp_formatter = self.shell.display_formatter | |
3258 | ptformatter = disp_formatter.formatters['text/plain'] |
|
3259 | ptformatter = disp_formatter.formatters['text/plain'] | |
3259 | # dstore is a data store kept in the instance metadata bag to track any |
|
3260 | # dstore is a data store kept in the instance metadata bag to track any | |
3260 | # changes we make, so we can undo them later. |
|
3261 | # changes we make, so we can undo them later. | |
3261 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3262 | dstore = meta.setdefault('doctest_mode',Struct()) | |
3262 | save_dstore = dstore.setdefault |
|
3263 | save_dstore = dstore.setdefault | |
3263 |
|
3264 | |||
3264 | # save a few values we'll need to recover later |
|
3265 | # save a few values we'll need to recover later | |
3265 | mode = save_dstore('mode',False) |
|
3266 | mode = save_dstore('mode',False) | |
3266 | save_dstore('rc_pprint',ptformatter.pprint) |
|
3267 | save_dstore('rc_pprint',ptformatter.pprint) | |
3267 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3268 | save_dstore('xmode',shell.InteractiveTB.mode) | |
3268 | save_dstore('rc_separate_out',shell.separate_out) |
|
3269 | save_dstore('rc_separate_out',shell.separate_out) | |
3269 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3270 | save_dstore('rc_separate_out2',shell.separate_out2) | |
3270 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) |
|
3271 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) | |
3271 | save_dstore('rc_separate_in',shell.separate_in) |
|
3272 | save_dstore('rc_separate_in',shell.separate_in) | |
3272 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) |
|
3273 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) | |
3273 |
|
3274 | |||
3274 | if mode == False: |
|
3275 | if mode == False: | |
3275 | # turn on |
|
3276 | # turn on | |
3276 | oc.prompt1.p_template = '>>> ' |
|
3277 | oc.prompt1.p_template = '>>> ' | |
3277 | oc.prompt2.p_template = '... ' |
|
3278 | oc.prompt2.p_template = '... ' | |
3278 | oc.prompt_out.p_template = '' |
|
3279 | oc.prompt_out.p_template = '' | |
3279 |
|
3280 | |||
3280 | # Prompt separators like plain python |
|
3281 | # Prompt separators like plain python | |
3281 | oc.input_sep = oc.prompt1.sep = '' |
|
3282 | oc.input_sep = oc.prompt1.sep = '' | |
3282 | oc.output_sep = '' |
|
3283 | oc.output_sep = '' | |
3283 | oc.output_sep2 = '' |
|
3284 | oc.output_sep2 = '' | |
3284 |
|
3285 | |||
3285 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3286 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3286 | oc.prompt_out.pad_left = False |
|
3287 | oc.prompt_out.pad_left = False | |
3287 |
|
3288 | |||
3288 | ptformatter.pprint = False |
|
3289 | ptformatter.pprint = False | |
3289 | disp_formatter.plain_text_only = True |
|
3290 | disp_formatter.plain_text_only = True | |
3290 |
|
3291 | |||
3291 | shell.magic_xmode('Plain') |
|
3292 | shell.magic_xmode('Plain') | |
3292 | else: |
|
3293 | else: | |
3293 | # turn off |
|
3294 | # turn off | |
3294 | oc.prompt1.p_template = shell.prompt_in1 |
|
3295 | oc.prompt1.p_template = shell.prompt_in1 | |
3295 | oc.prompt2.p_template = shell.prompt_in2 |
|
3296 | oc.prompt2.p_template = shell.prompt_in2 | |
3296 | oc.prompt_out.p_template = shell.prompt_out |
|
3297 | oc.prompt_out.p_template = shell.prompt_out | |
3297 |
|
3298 | |||
3298 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3299 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in | |
3299 |
|
3300 | |||
3300 | oc.output_sep = dstore.rc_separate_out |
|
3301 | oc.output_sep = dstore.rc_separate_out | |
3301 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3302 | oc.output_sep2 = dstore.rc_separate_out2 | |
3302 |
|
3303 | |||
3303 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3304 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3304 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3305 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left | |
3305 |
|
3306 | |||
3306 | ptformatter.pprint = dstore.rc_pprint |
|
3307 | ptformatter.pprint = dstore.rc_pprint | |
3307 | disp_formatter.plain_text_only = dstore.rc_plain_text_only |
|
3308 | disp_formatter.plain_text_only = dstore.rc_plain_text_only | |
3308 |
|
3309 | |||
3309 | shell.magic_xmode(dstore.xmode) |
|
3310 | shell.magic_xmode(dstore.xmode) | |
3310 |
|
3311 | |||
3311 | # Store new mode and inform |
|
3312 | # Store new mode and inform | |
3312 | dstore.mode = bool(1-int(mode)) |
|
3313 | dstore.mode = bool(1-int(mode)) | |
3313 | mode_label = ['OFF','ON'][dstore.mode] |
|
3314 | mode_label = ['OFF','ON'][dstore.mode] | |
3314 | print 'Doctest mode is:', mode_label |
|
3315 | print 'Doctest mode is:', mode_label | |
3315 |
|
3316 | |||
3316 | def magic_gui(self, parameter_s=''): |
|
3317 | def magic_gui(self, parameter_s=''): | |
3317 | """Enable or disable IPython GUI event loop integration. |
|
3318 | """Enable or disable IPython GUI event loop integration. | |
3318 |
|
3319 | |||
3319 | %gui [GUINAME] |
|
3320 | %gui [GUINAME] | |
3320 |
|
3321 | |||
3321 | This magic replaces IPython's threaded shells that were activated |
|
3322 | This magic replaces IPython's threaded shells that were activated | |
3322 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3323 | using the (pylab/wthread/etc.) command line flags. GUI toolkits | |
3323 | can now be enabled, disabled and changed at runtime and keyboard |
|
3324 | can now be enabled, disabled and changed at runtime and keyboard | |
3324 | interrupts should work without any problems. The following toolkits |
|
3325 | interrupts should work without any problems. The following toolkits | |
3325 | are supported: wxPython, PyQt4, PyGTK, and Tk:: |
|
3326 | are supported: wxPython, PyQt4, PyGTK, and Tk:: | |
3326 |
|
3327 | |||
3327 | %gui wx # enable wxPython event loop integration |
|
3328 | %gui wx # enable wxPython event loop integration | |
3328 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3329 | %gui qt4|qt # enable PyQt4 event loop integration | |
3329 | %gui gtk # enable PyGTK event loop integration |
|
3330 | %gui gtk # enable PyGTK event loop integration | |
3330 | %gui tk # enable Tk event loop integration |
|
3331 | %gui tk # enable Tk event loop integration | |
3331 | %gui # disable all event loop integration |
|
3332 | %gui # disable all event loop integration | |
3332 |
|
3333 | |||
3333 | WARNING: after any of these has been called you can simply create |
|
3334 | WARNING: after any of these has been called you can simply create | |
3334 | an application object, but DO NOT start the event loop yourself, as |
|
3335 | an application object, but DO NOT start the event loop yourself, as | |
3335 | we have already handled that. |
|
3336 | we have already handled that. | |
3336 | """ |
|
3337 | """ | |
3337 | from IPython.lib.inputhook import enable_gui |
|
3338 | from IPython.lib.inputhook import enable_gui | |
3338 | opts, arg = self.parse_options(parameter_s, '') |
|
3339 | opts, arg = self.parse_options(parameter_s, '') | |
3339 | if arg=='': arg = None |
|
3340 | if arg=='': arg = None | |
3340 | return enable_gui(arg) |
|
3341 | return enable_gui(arg) | |
3341 |
|
3342 | |||
3342 | def magic_load_ext(self, module_str): |
|
3343 | def magic_load_ext(self, module_str): | |
3343 | """Load an IPython extension by its module name.""" |
|
3344 | """Load an IPython extension by its module name.""" | |
3344 | return self.extension_manager.load_extension(module_str) |
|
3345 | return self.extension_manager.load_extension(module_str) | |
3345 |
|
3346 | |||
3346 | def magic_unload_ext(self, module_str): |
|
3347 | def magic_unload_ext(self, module_str): | |
3347 | """Unload an IPython extension by its module name.""" |
|
3348 | """Unload an IPython extension by its module name.""" | |
3348 | self.extension_manager.unload_extension(module_str) |
|
3349 | self.extension_manager.unload_extension(module_str) | |
3349 |
|
3350 | |||
3350 | def magic_reload_ext(self, module_str): |
|
3351 | def magic_reload_ext(self, module_str): | |
3351 | """Reload an IPython extension by its module name.""" |
|
3352 | """Reload an IPython extension by its module name.""" | |
3352 | self.extension_manager.reload_extension(module_str) |
|
3353 | self.extension_manager.reload_extension(module_str) | |
3353 |
|
3354 | |||
3354 | @skip_doctest |
|
3355 | @skip_doctest | |
3355 | def magic_install_profiles(self, s): |
|
3356 | def magic_install_profiles(self, s): | |
3356 | """Install the default IPython profiles into the .ipython dir. |
|
3357 | """Install the default IPython profiles into the .ipython dir. | |
3357 |
|
3358 | |||
3358 | If the default profiles have already been installed, they will not |
|
3359 | If the default profiles have already been installed, they will not | |
3359 | be overwritten. You can force overwriting them by using the ``-o`` |
|
3360 | be overwritten. You can force overwriting them by using the ``-o`` | |
3360 | option:: |
|
3361 | option:: | |
3361 |
|
3362 | |||
3362 | In [1]: %install_profiles -o |
|
3363 | In [1]: %install_profiles -o | |
3363 | """ |
|
3364 | """ | |
3364 | if '-o' in s: |
|
3365 | if '-o' in s: | |
3365 | overwrite = True |
|
3366 | overwrite = True | |
3366 | else: |
|
3367 | else: | |
3367 | overwrite = False |
|
3368 | overwrite = False | |
3368 | from IPython.config import profile |
|
3369 | from IPython.config import profile | |
3369 | profile_dir = os.path.dirname(profile.__file__) |
|
3370 | profile_dir = os.path.dirname(profile.__file__) | |
3370 | ipython_dir = self.ipython_dir |
|
3371 | ipython_dir = self.ipython_dir | |
3371 | print "Installing profiles to: %s [overwrite=%s]"%(ipython_dir,overwrite) |
|
3372 | print "Installing profiles to: %s [overwrite=%s]"%(ipython_dir,overwrite) | |
3372 | for src in os.listdir(profile_dir): |
|
3373 | for src in os.listdir(profile_dir): | |
3373 | if src.startswith('profile_'): |
|
3374 | if src.startswith('profile_'): | |
3374 | name = src.replace('profile_', '') |
|
3375 | name = src.replace('profile_', '') | |
3375 | print " %s"%name |
|
3376 | print " %s"%name | |
3376 | pd = ProfileDir.create_profile_dir_by_name(ipython_dir, name) |
|
3377 | pd = ProfileDir.create_profile_dir_by_name(ipython_dir, name) | |
3377 | pd.copy_config_file('ipython_config.py', path=src, |
|
3378 | pd.copy_config_file('ipython_config.py', path=src, | |
3378 | overwrite=overwrite) |
|
3379 | overwrite=overwrite) | |
3379 |
|
3380 | |||
3380 | @skip_doctest |
|
3381 | @skip_doctest | |
3381 | def magic_install_default_config(self, s): |
|
3382 | def magic_install_default_config(self, s): | |
3382 | """Install IPython's default config file into the .ipython dir. |
|
3383 | """Install IPython's default config file into the .ipython dir. | |
3383 |
|
3384 | |||
3384 | If the default config file (:file:`ipython_config.py`) is already |
|
3385 | If the default config file (:file:`ipython_config.py`) is already | |
3385 | installed, it will not be overwritten. You can force overwriting |
|
3386 | installed, it will not be overwritten. You can force overwriting | |
3386 | by using the ``-o`` option:: |
|
3387 | by using the ``-o`` option:: | |
3387 |
|
3388 | |||
3388 | In [1]: %install_default_config |
|
3389 | In [1]: %install_default_config | |
3389 | """ |
|
3390 | """ | |
3390 | if '-o' in s: |
|
3391 | if '-o' in s: | |
3391 | overwrite = True |
|
3392 | overwrite = True | |
3392 | else: |
|
3393 | else: | |
3393 | overwrite = False |
|
3394 | overwrite = False | |
3394 | pd = self.shell.profile_dir |
|
3395 | pd = self.shell.profile_dir | |
3395 | print "Installing default config file in: %s" % pd.location |
|
3396 | print "Installing default config file in: %s" % pd.location | |
3396 | pd.copy_config_file('ipython_config.py', overwrite=overwrite) |
|
3397 | pd.copy_config_file('ipython_config.py', overwrite=overwrite) | |
3397 |
|
3398 | |||
3398 | # Pylab support: simple wrappers that activate pylab, load gui input |
|
3399 | # Pylab support: simple wrappers that activate pylab, load gui input | |
3399 | # handling and modify slightly %run |
|
3400 | # handling and modify slightly %run | |
3400 |
|
3401 | |||
3401 | @skip_doctest |
|
3402 | @skip_doctest | |
3402 | def _pylab_magic_run(self, parameter_s=''): |
|
3403 | def _pylab_magic_run(self, parameter_s=''): | |
3403 | Magic.magic_run(self, parameter_s, |
|
3404 | Magic.magic_run(self, parameter_s, | |
3404 | runner=mpl_runner(self.shell.safe_execfile)) |
|
3405 | runner=mpl_runner(self.shell.safe_execfile)) | |
3405 |
|
3406 | |||
3406 | _pylab_magic_run.__doc__ = magic_run.__doc__ |
|
3407 | _pylab_magic_run.__doc__ = magic_run.__doc__ | |
3407 |
|
3408 | |||
3408 | @skip_doctest |
|
3409 | @skip_doctest | |
3409 | def magic_pylab(self, s): |
|
3410 | def magic_pylab(self, s): | |
3410 | """Load numpy and matplotlib to work interactively. |
|
3411 | """Load numpy and matplotlib to work interactively. | |
3411 |
|
3412 | |||
3412 | %pylab [GUINAME] |
|
3413 | %pylab [GUINAME] | |
3413 |
|
3414 | |||
3414 | This function lets you activate pylab (matplotlib, numpy and |
|
3415 | This function lets you activate pylab (matplotlib, numpy and | |
3415 | interactive support) at any point during an IPython session. |
|
3416 | interactive support) at any point during an IPython session. | |
3416 |
|
3417 | |||
3417 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3418 | It will import at the top level numpy as np, pyplot as plt, matplotlib, | |
3418 | pylab and mlab, as well as all names from numpy and pylab. |
|
3419 | pylab and mlab, as well as all names from numpy and pylab. | |
3419 |
|
3420 | |||
3420 | Parameters |
|
3421 | Parameters | |
3421 | ---------- |
|
3422 | ---------- | |
3422 | guiname : optional |
|
3423 | guiname : optional | |
3423 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or |
|
3424 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or | |
3424 | 'tk'). If given, the corresponding Matplotlib backend is used, |
|
3425 | 'tk'). If given, the corresponding Matplotlib backend is used, | |
3425 | otherwise matplotlib's default (which you can override in your |
|
3426 | otherwise matplotlib's default (which you can override in your | |
3426 | matplotlib config file) is used. |
|
3427 | matplotlib config file) is used. | |
3427 |
|
3428 | |||
3428 | Examples |
|
3429 | Examples | |
3429 | -------- |
|
3430 | -------- | |
3430 | In this case, where the MPL default is TkAgg: |
|
3431 | In this case, where the MPL default is TkAgg: | |
3431 | In [2]: %pylab |
|
3432 | In [2]: %pylab | |
3432 |
|
3433 | |||
3433 | Welcome to pylab, a matplotlib-based Python environment. |
|
3434 | Welcome to pylab, a matplotlib-based Python environment. | |
3434 | Backend in use: TkAgg |
|
3435 | Backend in use: TkAgg | |
3435 | For more information, type 'help(pylab)'. |
|
3436 | For more information, type 'help(pylab)'. | |
3436 |
|
3437 | |||
3437 | But you can explicitly request a different backend: |
|
3438 | But you can explicitly request a different backend: | |
3438 | In [3]: %pylab qt |
|
3439 | In [3]: %pylab qt | |
3439 |
|
3440 | |||
3440 | Welcome to pylab, a matplotlib-based Python environment. |
|
3441 | Welcome to pylab, a matplotlib-based Python environment. | |
3441 | Backend in use: Qt4Agg |
|
3442 | Backend in use: Qt4Agg | |
3442 | For more information, type 'help(pylab)'. |
|
3443 | For more information, type 'help(pylab)'. | |
3443 | """ |
|
3444 | """ | |
3444 | self.shell.enable_pylab(s) |
|
3445 | self.shell.enable_pylab(s) | |
3445 |
|
3446 | |||
3446 | def magic_tb(self, s): |
|
3447 | def magic_tb(self, s): | |
3447 | """Print the last traceback with the currently active exception mode. |
|
3448 | """Print the last traceback with the currently active exception mode. | |
3448 |
|
3449 | |||
3449 | See %xmode for changing exception reporting modes.""" |
|
3450 | See %xmode for changing exception reporting modes.""" | |
3450 | self.shell.showtraceback() |
|
3451 | self.shell.showtraceback() | |
3451 |
|
3452 | |||
3452 | @skip_doctest |
|
3453 | @skip_doctest | |
3453 | def magic_precision(self, s=''): |
|
3454 | def magic_precision(self, s=''): | |
3454 | """Set floating point precision for pretty printing. |
|
3455 | """Set floating point precision for pretty printing. | |
3455 |
|
3456 | |||
3456 | Can set either integer precision or a format string. |
|
3457 | Can set either integer precision or a format string. | |
3457 |
|
3458 | |||
3458 | If numpy has been imported and precision is an int, |
|
3459 | If numpy has been imported and precision is an int, | |
3459 | numpy display precision will also be set, via ``numpy.set_printoptions``. |
|
3460 | numpy display precision will also be set, via ``numpy.set_printoptions``. | |
3460 |
|
3461 | |||
3461 | If no argument is given, defaults will be restored. |
|
3462 | If no argument is given, defaults will be restored. | |
3462 |
|
3463 | |||
3463 | Examples |
|
3464 | Examples | |
3464 | -------- |
|
3465 | -------- | |
3465 | :: |
|
3466 | :: | |
3466 |
|
3467 | |||
3467 | In [1]: from math import pi |
|
3468 | In [1]: from math import pi | |
3468 |
|
3469 | |||
3469 | In [2]: %precision 3 |
|
3470 | In [2]: %precision 3 | |
3470 | Out[2]: u'%.3f' |
|
3471 | Out[2]: u'%.3f' | |
3471 |
|
3472 | |||
3472 | In [3]: pi |
|
3473 | In [3]: pi | |
3473 | Out[3]: 3.142 |
|
3474 | Out[3]: 3.142 | |
3474 |
|
3475 | |||
3475 | In [4]: %precision %i |
|
3476 | In [4]: %precision %i | |
3476 | Out[4]: u'%i' |
|
3477 | Out[4]: u'%i' | |
3477 |
|
3478 | |||
3478 | In [5]: pi |
|
3479 | In [5]: pi | |
3479 | Out[5]: 3 |
|
3480 | Out[5]: 3 | |
3480 |
|
3481 | |||
3481 | In [6]: %precision %e |
|
3482 | In [6]: %precision %e | |
3482 | Out[6]: u'%e' |
|
3483 | Out[6]: u'%e' | |
3483 |
|
3484 | |||
3484 | In [7]: pi**10 |
|
3485 | In [7]: pi**10 | |
3485 | Out[7]: 9.364805e+04 |
|
3486 | Out[7]: 9.364805e+04 | |
3486 |
|
3487 | |||
3487 | In [8]: %precision |
|
3488 | In [8]: %precision | |
3488 | Out[8]: u'%r' |
|
3489 | Out[8]: u'%r' | |
3489 |
|
3490 | |||
3490 | In [9]: pi**10 |
|
3491 | In [9]: pi**10 | |
3491 | Out[9]: 93648.047476082982 |
|
3492 | Out[9]: 93648.047476082982 | |
3492 |
|
3493 | |||
3493 | """ |
|
3494 | """ | |
3494 |
|
3495 | |||
3495 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
3496 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
3496 | ptformatter.float_precision = s |
|
3497 | ptformatter.float_precision = s | |
3497 | return ptformatter.float_format |
|
3498 | return ptformatter.float_format | |
3498 |
|
3499 | |||
3499 |
|
3500 | |||
3500 | @magic_arguments.magic_arguments() |
|
3501 | @magic_arguments.magic_arguments() | |
3501 | @magic_arguments.argument( |
|
3502 | @magic_arguments.argument( | |
3502 | '-e', '--export', action='store_true', default=False, |
|
3503 | '-e', '--export', action='store_true', default=False, | |
3503 | help='Export IPython history as a notebook. The filename argument ' |
|
3504 | help='Export IPython history as a notebook. The filename argument ' | |
3504 | 'is used to specify the notebook name and format. For example ' |
|
3505 | 'is used to specify the notebook name and format. For example ' | |
3505 | 'a filename of notebook.ipynb will result in a notebook name ' |
|
3506 | 'a filename of notebook.ipynb will result in a notebook name ' | |
3506 | 'of "notebook" and a format of "xml". Likewise using a ".json" ' |
|
3507 | 'of "notebook" and a format of "xml". Likewise using a ".json" ' | |
3507 | 'or ".py" file extension will write the notebook in the json ' |
|
3508 | 'or ".py" file extension will write the notebook in the json ' | |
3508 | 'or py formats.' |
|
3509 | 'or py formats.' | |
3509 | ) |
|
3510 | ) | |
3510 | @magic_arguments.argument( |
|
3511 | @magic_arguments.argument( | |
3511 | '-f', '--format', |
|
3512 | '-f', '--format', | |
3512 | help='Convert an existing IPython notebook to a new format. This option ' |
|
3513 | help='Convert an existing IPython notebook to a new format. This option ' | |
3513 | 'specifies the new format and can have the values: xml, json, py. ' |
|
3514 | 'specifies the new format and can have the values: xml, json, py. ' | |
3514 | 'The target filename is choosen automatically based on the new ' |
|
3515 | 'The target filename is choosen automatically based on the new ' | |
3515 | 'format. The filename argument gives the name of the source file.' |
|
3516 | 'format. The filename argument gives the name of the source file.' | |
3516 | ) |
|
3517 | ) | |
3517 | @magic_arguments.argument( |
|
3518 | @magic_arguments.argument( | |
3518 | 'filename', type=unicode, |
|
3519 | 'filename', type=unicode, | |
3519 | help='Notebook name or filename' |
|
3520 | help='Notebook name or filename' | |
3520 | ) |
|
3521 | ) | |
3521 | def magic_notebook(self, s): |
|
3522 | def magic_notebook(self, s): | |
3522 | """Export and convert IPython notebooks. |
|
3523 | """Export and convert IPython notebooks. | |
3523 |
|
3524 | |||
3524 | This function can export the current IPython history to a notebook file |
|
3525 | This function can export the current IPython history to a notebook file | |
3525 | or can convert an existing notebook file into a different format. For |
|
3526 | or can convert an existing notebook file into a different format. For | |
3526 | example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb". |
|
3527 | example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb". | |
3527 | To export the history to "foo.py" do "%notebook -e foo.py". To convert |
|
3528 | To export the history to "foo.py" do "%notebook -e foo.py". To convert | |
3528 | "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible |
|
3529 | "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible | |
3529 | formats include (xml/ipynb, json, py). |
|
3530 | formats include (xml/ipynb, json, py). | |
3530 | """ |
|
3531 | """ | |
3531 | args = magic_arguments.parse_argstring(self.magic_notebook, s) |
|
3532 | args = magic_arguments.parse_argstring(self.magic_notebook, s) | |
3532 | print args |
|
3533 | print args | |
3533 |
|
3534 | |||
3534 | from IPython.nbformat import current |
|
3535 | from IPython.nbformat import current | |
3535 | if args.export: |
|
3536 | if args.export: | |
3536 | fname, name, format = current.parse_filename(args.filename) |
|
3537 | fname, name, format = current.parse_filename(args.filename) | |
3537 | cells = [] |
|
3538 | cells = [] | |
3538 | hist = list(self.history_manager.get_range()) |
|
3539 | hist = list(self.history_manager.get_range()) | |
3539 | for session, prompt_number, input in hist[:-1]: |
|
3540 | for session, prompt_number, input in hist[:-1]: | |
3540 | cells.append(current.new_code_cell(prompt_number=prompt_number, input=input)) |
|
3541 | cells.append(current.new_code_cell(prompt_number=prompt_number, input=input)) | |
3541 | worksheet = current.new_worksheet(cells=cells) |
|
3542 | worksheet = current.new_worksheet(cells=cells) | |
3542 | nb = current.new_notebook(name=name,worksheets=[worksheet]) |
|
3543 | nb = current.new_notebook(name=name,worksheets=[worksheet]) | |
3543 | with open(fname, 'w') as f: |
|
3544 | with open(fname, 'w') as f: | |
3544 | current.write(nb, f, format); |
|
3545 | current.write(nb, f, format); | |
3545 | elif args.format is not None: |
|
3546 | elif args.format is not None: | |
3546 | old_fname, old_name, old_format = current.parse_filename(args.filename) |
|
3547 | old_fname, old_name, old_format = current.parse_filename(args.filename) | |
3547 | new_format = args.format |
|
3548 | new_format = args.format | |
3548 | if new_format == u'xml' or new_format == u'ipynb': |
|
3549 | if new_format == u'xml' or new_format == u'ipynb': | |
3549 | new_fname = old_name + u'.ipynb' |
|
3550 | new_fname = old_name + u'.ipynb' | |
3550 | new_format = u'xml' |
|
3551 | new_format = u'xml' | |
3551 | elif new_format == u'py': |
|
3552 | elif new_format == u'py': | |
3552 | new_fname = old_name + u'.py' |
|
3553 | new_fname = old_name + u'.py' | |
3553 | elif new_format == u'json': |
|
3554 | elif new_format == u'json': | |
3554 | new_fname = old_name + u'.json' |
|
3555 | new_fname = old_name + u'.json' | |
3555 | else: |
|
3556 | else: | |
3556 | raise ValueError('Invalid notebook format: %s' % newformat) |
|
3557 | raise ValueError('Invalid notebook format: %s' % newformat) | |
3557 | with open(old_fname, 'r') as f: |
|
3558 | with open(old_fname, 'r') as f: | |
3558 | nb = current.read(f, old_format) |
|
3559 | nb = current.read(f, old_format) | |
3559 | with open(new_fname, 'w') as f: |
|
3560 | with open(new_fname, 'w') as f: | |
3560 | current.write(nb, f, new_format) |
|
3561 | current.write(nb, f, new_format) | |
3561 |
|
3562 | |||
3562 |
|
3563 | |||
3563 | # end Magic |
|
3564 | # end Magic |
@@ -1,397 +1,410 b'' | |||||
1 |
|
1 | |||
2 | //============================================================================ |
|
2 | //============================================================================ | |
3 | // CodeCell |
|
3 | // CodeCell | |
4 | //============================================================================ |
|
4 | //============================================================================ | |
5 |
|
5 | |||
6 | var IPython = (function (IPython) { |
|
6 | var IPython = (function (IPython) { | |
7 |
|
7 | |||
8 | var utils = IPython.utils; |
|
8 | var utils = IPython.utils; | |
9 |
|
9 | |||
10 | var CodeCell = function (notebook) { |
|
10 | var CodeCell = function (notebook) { | |
11 | this.code_mirror = null; |
|
11 | this.code_mirror = null; | |
12 | this.input_prompt_number = ' '; |
|
12 | this.input_prompt_number = ' '; | |
13 | this.is_completing = false; |
|
13 | this.is_completing = false; | |
14 | this.completion_cursor = null; |
|
14 | this.completion_cursor = null; | |
15 | this.outputs = []; |
|
15 | this.outputs = []; | |
16 | IPython.Cell.apply(this, arguments); |
|
16 | IPython.Cell.apply(this, arguments); | |
17 | }; |
|
17 | }; | |
18 |
|
18 | |||
19 |
|
19 | |||
20 | CodeCell.prototype = new IPython.Cell(); |
|
20 | CodeCell.prototype = new IPython.Cell(); | |
21 |
|
21 | |||
22 |
|
22 | |||
23 | CodeCell.prototype.create_element = function () { |
|
23 | CodeCell.prototype.create_element = function () { | |
24 | var cell = $('<div></div>').addClass('cell border-box-sizing code_cell vbox'); |
|
24 | var cell = $('<div></div>').addClass('cell border-box-sizing code_cell vbox'); | |
25 | var input = $('<div></div>').addClass('input hbox'); |
|
25 | var input = $('<div></div>').addClass('input hbox'); | |
26 | input.append($('<div/>').addClass('prompt input_prompt')); |
|
26 | input.append($('<div/>').addClass('prompt input_prompt')); | |
27 | var input_area = $('<div/>').addClass('input_area box-flex1'); |
|
27 | var input_area = $('<div/>').addClass('input_area box-flex1'); | |
28 | this.code_mirror = CodeMirror(input_area.get(0), { |
|
28 | this.code_mirror = CodeMirror(input_area.get(0), { | |
29 | indentUnit : 4, |
|
29 | indentUnit : 4, | |
30 | enterMode : 'flat', |
|
30 | enterMode : 'flat', | |
31 | tabMode: 'shift', |
|
31 | tabMode: 'shift', | |
32 | mode: 'python', |
|
32 | mode: 'python', | |
33 | theme: 'ipython', |
|
33 | theme: 'ipython', | |
34 | onKeyEvent: $.proxy(this.handle_codemirror_keyevent,this) |
|
34 | onKeyEvent: $.proxy(this.handle_codemirror_keyevent,this) | |
35 | }); |
|
35 | }); | |
36 | input.append(input_area); |
|
36 | input.append(input_area); | |
37 | var output = $('<div></div>').addClass('output vbox'); |
|
37 | var output = $('<div></div>').addClass('output vbox'); | |
38 | cell.append(input).append(output); |
|
38 | cell.append(input).append(output); | |
39 | this.element = cell; |
|
39 | this.element = cell; | |
40 | this.collapse() |
|
40 | this.collapse() | |
41 | }; |
|
41 | }; | |
42 |
|
42 | |||
43 |
|
43 | |||
44 | CodeCell.prototype.handle_codemirror_keyevent = function (editor, event) { |
|
44 | CodeCell.prototype.handle_codemirror_keyevent = function (editor, event) { | |
45 | // This method gets called in CodeMirror's onKeyDown/onKeyPress handlers and |
|
45 | // This method gets called in CodeMirror's onKeyDown/onKeyPress handlers and | |
46 | // is used to provide custom key handling. Its return value is used to determine |
|
46 | // is used to provide custom key handling. Its return value is used to determine | |
47 | // if CodeMirror should ignore the event: true = ignore, false = don't ignore. |
|
47 | // if CodeMirror should ignore the event: true = ignore, false = don't ignore. | |
48 | if (event.keyCode === 13 && event.shiftKey) { |
|
48 | if (event.keyCode === 13 && event.shiftKey) { | |
49 | // Always ignore shift-enter in CodeMirror as we handle it. |
|
49 | // Always ignore shift-enter in CodeMirror as we handle it. | |
50 | return true; |
|
50 | return true; | |
51 | } else if (event.keyCode === 9) { |
|
51 | } else if (event.keyCode === 9) { | |
52 | var cur = editor.getCursor(); |
|
52 | var cur = editor.getCursor(); | |
53 | var pre_cursor = editor.getRange({line:cur.line,ch:0},cur).trim(); |
|
53 | var pre_cursor = editor.getRange({line:cur.line,ch:0},cur).trim(); | |
54 | if (pre_cursor === "") { |
|
54 | if (pre_cursor === "") { | |
55 | // Don't autocomplete if the part of the line before the cursor is empty. |
|
55 | // Don't autocomplete if the part of the line before the cursor is empty. | |
56 | // In this case, let CodeMirror handle indentation. |
|
56 | // In this case, let CodeMirror handle indentation. | |
57 | return false; |
|
57 | return false; | |
58 | } else { |
|
58 | } else { | |
59 | // Autocomplete the current line. |
|
59 | // Autocomplete the current line. | |
60 | event.stop(); |
|
60 | event.stop(); | |
61 | var line = editor.getLine(cur.line); |
|
61 | var line = editor.getLine(cur.line); | |
62 | this.is_completing = true; |
|
62 | this.is_completing = true; | |
63 | this.completion_cursor = cur; |
|
63 | this.completion_cursor = cur; | |
64 | IPython.notebook.complete_cell(this, line, cur.ch); |
|
64 | IPython.notebook.complete_cell(this, line, cur.ch); | |
65 | return true; |
|
65 | return true; | |
66 | } |
|
66 | } | |
67 | } else if (event.keyCode === 8) { |
|
67 | } else if (event.keyCode === 8) { | |
68 | // If backspace and the line ends with 4 spaces, remove them. |
|
68 | // If backspace and the line ends with 4 spaces, remove them. | |
69 | var cur = editor.getCursor(); |
|
69 | var cur = editor.getCursor(); | |
70 | var line = editor.getLine(cur.line); |
|
70 | var line = editor.getLine(cur.line); | |
71 | var ending = line.slice(-4); |
|
71 | var ending = line.slice(-4); | |
72 | if (ending === ' ') { |
|
72 | if (ending === ' ') { | |
73 | editor.replaceRange('', |
|
73 | editor.replaceRange('', | |
74 | {line: cur.line, ch: cur.ch-4}, |
|
74 | {line: cur.line, ch: cur.ch-4}, | |
75 | {line: cur.line, ch: cur.ch} |
|
75 | {line: cur.line, ch: cur.ch} | |
76 | ); |
|
76 | ); | |
77 | event.stop(); |
|
77 | event.stop(); | |
78 | return true; |
|
78 | return true; | |
79 | } else { |
|
79 | } else { | |
80 | return false; |
|
80 | return false; | |
81 | }; |
|
81 | }; | |
82 | } else { |
|
82 | } else { | |
83 | if (this.is_completing && this.completion_cursor !== editor.getCursor()) { |
|
83 | if (this.is_completing && this.completion_cursor !== editor.getCursor()) { | |
84 | this.is_completing = false; |
|
84 | this.is_completing = false; | |
85 | this.completion_cursor = null; |
|
85 | this.completion_cursor = null; | |
86 | } |
|
86 | } | |
87 | return false; |
|
87 | return false; | |
88 | }; |
|
88 | }; | |
89 | }; |
|
89 | }; | |
90 |
|
90 | |||
91 |
|
91 | |||
92 | CodeCell.prototype.finish_completing = function (matched_text, matches) { |
|
92 | CodeCell.prototype.finish_completing = function (matched_text, matches) { | |
93 | if (!this.is_completing || matches.length === 0) {return;} |
|
93 | if (!this.is_completing || matches.length === 0) {return;} | |
94 | // console.log("Got matches", matched_text, matches); |
|
94 | // console.log("Got matches", matched_text, matches); | |
95 |
|
95 | |||
96 | var that = this; |
|
96 | var that = this; | |
97 | var cur = this.completion_cursor; |
|
97 | var cur = this.completion_cursor; | |
98 | var complete = $('<div/>').addClass('completions'); |
|
98 | var complete = $('<div/>').addClass('completions'); | |
99 | var select = $('<select/>').attr('multiple','true'); |
|
99 | var select = $('<select/>').attr('multiple','true'); | |
100 | for (var i=0; i<matches.length; ++i) { |
|
100 | for (var i=0; i<matches.length; ++i) { | |
101 | select.append($('<option/>').text(matches[i])); |
|
101 | select.append($('<option/>').text(matches[i])); | |
102 | } |
|
102 | } | |
103 | select.children().first().attr('selected','true'); |
|
103 | select.children().first().attr('selected','true'); | |
104 | select.attr('size',Math.min(10,matches.length)); |
|
104 | select.attr('size',Math.min(10,matches.length)); | |
105 | var pos = this.code_mirror.cursorCoords(); |
|
105 | var pos = this.code_mirror.cursorCoords(); | |
106 | complete.css('left',pos.x+'px'); |
|
106 | complete.css('left',pos.x+'px'); | |
107 | complete.css('top',pos.yBot+'px'); |
|
107 | complete.css('top',pos.yBot+'px'); | |
108 | complete.append(select); |
|
108 | complete.append(select); | |
109 |
|
109 | |||
110 | $('body').append(complete); |
|
110 | $('body').append(complete); | |
111 | var done = false; |
|
111 | var done = false; | |
112 |
|
112 | |||
113 | var insert = function (selected_text) { |
|
113 | var insert = function (selected_text) { | |
114 | that.code_mirror.replaceRange( |
|
114 | that.code_mirror.replaceRange( | |
115 | selected_text, |
|
115 | selected_text, | |
116 | {line: cur.line, ch: (cur.ch-matched_text.length)}, |
|
116 | {line: cur.line, ch: (cur.ch-matched_text.length)}, | |
117 | {line: cur.line, ch: cur.ch} |
|
117 | {line: cur.line, ch: cur.ch} | |
118 | ); |
|
118 | ); | |
119 | }; |
|
119 | }; | |
120 |
|
120 | |||
121 | var close = function () { |
|
121 | var close = function () { | |
122 | if (done) return; |
|
122 | if (done) return; | |
123 | done = true; |
|
123 | done = true; | |
124 | complete.remove(); |
|
124 | complete.remove(); | |
125 | that.is_completing = false; |
|
125 | that.is_completing = false; | |
126 | that.completion_cursor = null; |
|
126 | that.completion_cursor = null; | |
127 | }; |
|
127 | }; | |
128 |
|
128 | |||
129 | var pick = function () { |
|
129 | var pick = function () { | |
130 | insert(select.val()[0]); |
|
130 | insert(select.val()[0]); | |
131 | close(); |
|
131 | close(); | |
132 | setTimeout(function(){that.code_mirror.focus();}, 50); |
|
132 | setTimeout(function(){that.code_mirror.focus();}, 50); | |
133 | }; |
|
133 | }; | |
134 |
|
134 | |||
135 | select.blur(close); |
|
135 | select.blur(close); | |
136 | select.keydown(function (event) { |
|
136 | select.keydown(function (event) { | |
137 | var code = event.which; |
|
137 | var code = event.which; | |
138 | if (code === 13 || code === 32) { |
|
138 | if (code === 13 || code === 32) { | |
139 | // Pressing SPACE or ENTER will cause a pick |
|
139 | // Pressing SPACE or ENTER will cause a pick | |
140 | event.stopPropagation(); |
|
140 | event.stopPropagation(); | |
141 | event.preventDefault(); |
|
141 | event.preventDefault(); | |
142 | pick(); |
|
142 | pick(); | |
143 | } else if (code === 38 || code === 40) { |
|
143 | } else if (code === 38 || code === 40) { | |
144 | // We don't want the document keydown handler to handle UP/DOWN, |
|
144 | // We don't want the document keydown handler to handle UP/DOWN, | |
145 | // but we want the default action. |
|
145 | // but we want the default action. | |
146 | event.stopPropagation(); |
|
146 | event.stopPropagation(); | |
147 | } else { |
|
147 | } else { | |
148 | // All other key presses simple exit completion. |
|
148 | // All other key presses simple exit completion. | |
149 | event.stopPropagation(); |
|
149 | event.stopPropagation(); | |
150 | event.preventDefault(); |
|
150 | event.preventDefault(); | |
151 | close(); |
|
151 | close(); | |
152 | that.code_mirror.focus(); |
|
152 | that.code_mirror.focus(); | |
153 | } |
|
153 | } | |
154 | }); |
|
154 | }); | |
155 | // Double click also causes a pick. |
|
155 | // Double click also causes a pick. | |
156 | select.dblclick(pick); |
|
156 | select.dblclick(pick); | |
157 | select.focus(); |
|
157 | select.focus(); | |
158 | }; |
|
158 | }; | |
159 |
|
159 | |||
160 |
|
160 | |||
161 | CodeCell.prototype.select = function () { |
|
161 | CodeCell.prototype.select = function () { | |
162 | IPython.Cell.prototype.select.apply(this); |
|
162 | IPython.Cell.prototype.select.apply(this); | |
163 | // Todo: this dance is needed because as of CodeMirror 2.12, focus is |
|
163 | // Todo: this dance is needed because as of CodeMirror 2.12, focus is | |
164 | // not causing the cursor to blink if the editor is empty initially. |
|
164 | // not causing the cursor to blink if the editor is empty initially. | |
165 | // While this seems to fix the issue, this should be fixed |
|
165 | // While this seems to fix the issue, this should be fixed | |
166 | // in CodeMirror proper. |
|
166 | // in CodeMirror proper. | |
167 | var s = this.code_mirror.getValue(); |
|
167 | var s = this.code_mirror.getValue(); | |
168 | if (s === '') this.code_mirror.setValue('.'); |
|
168 | if (s === '') this.code_mirror.setValue('.'); | |
169 | this.code_mirror.focus(); |
|
169 | this.code_mirror.focus(); | |
170 | if (s === '') this.code_mirror.setValue(''); |
|
170 | if (s === '') this.code_mirror.setValue(''); | |
171 | }; |
|
171 | }; | |
172 |
|
172 | |||
173 |
|
173 | |||
174 | CodeCell.prototype.append_output = function (json) { |
|
174 | CodeCell.prototype.append_output = function (json) { | |
175 | this.expand(); |
|
175 | this.expand(); | |
176 | if (json.output_type === 'pyout') { |
|
176 | if (json.output_type === 'pyout') { | |
177 | this.append_pyout(json); |
|
177 | this.append_pyout(json); | |
178 | } else if (json.output_type === 'pyerr') { |
|
178 | } else if (json.output_type === 'pyerr') { | |
179 | this.append_pyerr(json); |
|
179 | this.append_pyerr(json); | |
180 | } else if (json.output_type === 'display_data') { |
|
180 | } else if (json.output_type === 'display_data') { | |
181 | this.append_display_data(json); |
|
181 | this.append_display_data(json); | |
182 | } else if (json.output_type === 'stream') { |
|
182 | } else if (json.output_type === 'stream') { | |
183 | this.append_stream(json); |
|
183 | this.append_stream(json); | |
184 | }; |
|
184 | }; | |
185 | this.outputs.push(json); |
|
185 | this.outputs.push(json); | |
186 | }; |
|
186 | }; | |
187 |
|
187 | |||
188 |
|
188 | |||
189 | CodeCell.prototype.append_pyout = function (json) { |
|
189 | CodeCell.prototype.append_pyout = function (json) { | |
190 | n = json.prompt_number || ' '; |
|
190 | n = json.prompt_number || ' '; | |
191 | var toinsert = $("<div/>").addClass("output_area output_pyout hbox"); |
|
191 | var toinsert = $("<div/>").addClass("output_area output_pyout hbox"); | |
192 | toinsert.append($('<div/>'). |
|
192 | toinsert.append($('<div/>'). | |
193 | addClass('prompt output_prompt'). |
|
193 | addClass('prompt output_prompt'). | |
194 | html('Out[' + n + ']:') |
|
194 | html('Out[' + n + ']:') | |
195 | ); |
|
195 | ); | |
196 | this.append_mime_type(json, toinsert); |
|
196 | this.append_mime_type(json, toinsert); | |
197 | toinsert.children().last().addClass("box_flex1"); |
|
197 | toinsert.children().last().addClass("box_flex1"); | |
198 | this.element.find("div.output").append(toinsert); |
|
198 | this.element.find("div.output").append(toinsert); | |
199 | // If we just output latex, typeset it. |
|
199 | // If we just output latex, typeset it. | |
200 | if (json.latex !== undefined) { |
|
200 | if (json.latex !== undefined) { | |
201 | MathJax.Hub.Queue(["Typeset",MathJax.Hub]); |
|
201 | MathJax.Hub.Queue(["Typeset",MathJax.Hub]); | |
202 | }; |
|
202 | }; | |
203 | }; |
|
203 | }; | |
204 |
|
204 | |||
205 |
|
205 | |||
206 | CodeCell.prototype.append_pyerr = function (json) { |
|
206 | CodeCell.prototype.append_pyerr = function (json) { | |
207 | var tb = json.traceback; |
|
207 | var tb = json.traceback; | |
|
208 | if (tb !== undefined) { | |||
208 | var s = ''; |
|
209 | var s = ''; | |
209 | var len = tb.length; |
|
210 | var len = tb.length; | |
210 | for (var i=0; i<len; i++) { |
|
211 | for (var i=0; i<len; i++) { | |
211 | s = s + tb[i] + '\n'; |
|
212 | s = s + tb[i] + '\n'; | |
212 | } |
|
213 | } | |
213 | s = s + '\n'; |
|
214 | s = s + '\n'; | |
214 | this.append_text(s); |
|
215 | this.append_text(s); | |
215 | }; |
|
216 | }; | |
|
217 | }; | |||
216 |
|
218 | |||
217 |
|
219 | |||
218 | CodeCell.prototype.append_stream = function (json) { |
|
220 | CodeCell.prototype.append_stream = function (json) { | |
219 | this.append_text(json.text); |
|
221 | this.append_text(json.text); | |
220 | }; |
|
222 | }; | |
221 |
|
223 | |||
222 |
|
224 | |||
223 | CodeCell.prototype.append_display_data = function (json) { |
|
225 | CodeCell.prototype.append_display_data = function (json) { | |
224 | this.append_mime_type(json); |
|
226 | this.append_mime_type(json); | |
225 | }; |
|
227 | }; | |
226 |
|
228 | |||
227 |
|
229 | |||
228 | CodeCell.prototype.append_mime_type = function (json, element) { |
|
230 | CodeCell.prototype.append_mime_type = function (json, element) { | |
229 | if (json.html !== undefined) { |
|
231 | if (json.html !== undefined) { | |
230 | this.append_html(json.html, element); |
|
232 | this.append_html(json.html, element); | |
231 | } else if (json.latex !== undefined) { |
|
233 | } else if (json.latex !== undefined) { | |
232 | this.append_latex(json.latex, element); |
|
234 | this.append_latex(json.latex, element); | |
233 | // If it is undefined, then we just appended to div.output, which |
|
235 | // If it is undefined, then we just appended to div.output, which | |
234 | // makes the latex visible and we can typeset it. The typesetting |
|
236 | // makes the latex visible and we can typeset it. The typesetting | |
235 | // has to be done after the latex is on the page. |
|
237 | // has to be done after the latex is on the page. | |
236 | if (element === undefined) { |
|
238 | if (element === undefined) { | |
237 | MathJax.Hub.Queue(["Typeset",MathJax.Hub]); |
|
239 | MathJax.Hub.Queue(["Typeset",MathJax.Hub]); | |
238 | }; |
|
240 | }; | |
239 | } else if (json.svg !== undefined) { |
|
241 | } else if (json.svg !== undefined) { | |
240 | this.append_svg(json.svg, element); |
|
242 | this.append_svg(json.svg, element); | |
241 | } else if (json.png !== undefined) { |
|
243 | } else if (json.png !== undefined) { | |
242 | this.append_png(json.png, element); |
|
244 | this.append_png(json.png, element); | |
|
245 | } else if (json.jpeg !== undefined) { | |||
|
246 | this.append_jpeg(json.jpeg, element); | |||
243 | } else if (json.text !== undefined) { |
|
247 | } else if (json.text !== undefined) { | |
244 | this.append_text(json.text, element); |
|
248 | this.append_text(json.text, element); | |
245 | }; |
|
249 | }; | |
246 | return element; |
|
250 | return element; | |
247 | }; |
|
251 | }; | |
248 |
|
252 | |||
249 |
|
253 | |||
250 | CodeCell.prototype.append_html = function (html, element) { |
|
254 | CodeCell.prototype.append_html = function (html, element) { | |
251 | element = element || this.element.find("div.output"); |
|
255 | element = element || this.element.find("div.output"); | |
252 | var toinsert = $("<div/>").addClass("output_area output_html"); |
|
256 | var toinsert = $("<div/>").addClass("output_area output_html"); | |
253 | toinsert.append(html); |
|
257 | toinsert.append(html); | |
254 | element.append(toinsert); |
|
258 | element.append(toinsert); | |
255 | return element; |
|
259 | return element; | |
256 | } |
|
260 | } | |
257 |
|
261 | |||
258 |
|
262 | |||
259 | CodeCell.prototype.append_text = function (data, element) { |
|
263 | CodeCell.prototype.append_text = function (data, element) { | |
260 | element = element || this.element.find("div.output"); |
|
264 | element = element || this.element.find("div.output"); | |
261 | var toinsert = $("<div/>").addClass("output_area output_stream"); |
|
265 | var toinsert = $("<div/>").addClass("output_area output_stream"); | |
262 | toinsert.append($("<pre/>").html(utils.fixConsole(data))); |
|
266 | toinsert.append($("<pre/>").html(utils.fixConsole(data))); | |
263 | element.append(toinsert); |
|
267 | element.append(toinsert); | |
264 | return element; |
|
268 | return element; | |
265 | }; |
|
269 | }; | |
266 |
|
270 | |||
267 |
|
271 | |||
268 | CodeCell.prototype.append_svg = function (svg, element) { |
|
272 | CodeCell.prototype.append_svg = function (svg, element) { | |
269 | element = element || this.element.find("div.output"); |
|
273 | element = element || this.element.find("div.output"); | |
270 | var toinsert = $("<div/>").addClass("output_area output_svg"); |
|
274 | var toinsert = $("<div/>").addClass("output_area output_svg"); | |
271 | toinsert.append(svg); |
|
275 | toinsert.append(svg); | |
272 | element.append(toinsert); |
|
276 | element.append(toinsert); | |
273 | return element; |
|
277 | return element; | |
274 | }; |
|
278 | }; | |
275 |
|
279 | |||
276 |
|
280 | |||
277 | CodeCell.prototype.append_png = function (png, element) { |
|
281 | CodeCell.prototype.append_png = function (png, element) { | |
278 | element = element || this.element.find("div.output"); |
|
282 | element = element || this.element.find("div.output"); | |
279 | var toinsert = $("<div/>").addClass("output_area output_png"); |
|
283 | var toinsert = $("<div/>").addClass("output_area output_png"); | |
280 | toinsert.append($("<img/>").attr('src','data:image/png;base64,'+png)); |
|
284 | toinsert.append($("<img/>").attr('src','data:image/png;base64,'+png)); | |
281 | element.append(toinsert); |
|
285 | element.append(toinsert); | |
282 | return element; |
|
286 | return element; | |
283 | }; |
|
287 | }; | |
284 |
|
288 | |||
285 |
|
289 | |||
|
290 | CodeCell.prototype.append_jpeg = function (jpeg, element) { | |||
|
291 | element = element || this.element.find("div.output"); | |||
|
292 | var toinsert = $("<div/>").addClass("output_area output_jpeg"); | |||
|
293 | toinsert.append($("<img/>").attr('src','data:image/jpeg;base64,'+jpeg)); | |||
|
294 | element.append(toinsert); | |||
|
295 | return element; | |||
|
296 | }; | |||
|
297 | ||||
|
298 | ||||
286 | CodeCell.prototype.append_latex = function (latex, element) { |
|
299 | CodeCell.prototype.append_latex = function (latex, element) { | |
287 | // This method cannot do the typesetting because the latex first has to |
|
300 | // This method cannot do the typesetting because the latex first has to | |
288 | // be on the page. |
|
301 | // be on the page. | |
289 | element = element || this.element.find("div.output"); |
|
302 | element = element || this.element.find("div.output"); | |
290 | var toinsert = $("<div/>").addClass("output_area output_latex"); |
|
303 | var toinsert = $("<div/>").addClass("output_area output_latex"); | |
291 | toinsert.append(latex); |
|
304 | toinsert.append(latex); | |
292 | element.append(toinsert); |
|
305 | element.append(toinsert); | |
293 | return element; |
|
306 | return element; | |
294 | } |
|
307 | } | |
295 |
|
308 | |||
296 |
|
309 | |||
297 | CodeCell.prototype.clear_output = function () { |
|
310 | CodeCell.prototype.clear_output = function () { | |
298 | this.element.find("div.output").html(""); |
|
311 | this.element.find("div.output").html(""); | |
299 | this.outputs = []; |
|
312 | this.outputs = []; | |
300 | }; |
|
313 | }; | |
301 |
|
314 | |||
302 |
|
315 | |||
303 | CodeCell.prototype.clear_input = function () { |
|
316 | CodeCell.prototype.clear_input = function () { | |
304 | this.code_mirror.setValue(''); |
|
317 | this.code_mirror.setValue(''); | |
305 | }; |
|
318 | }; | |
306 |
|
319 | |||
307 |
|
320 | |||
308 | CodeCell.prototype.collapse = function () { |
|
321 | CodeCell.prototype.collapse = function () { | |
309 | this.element.find('div.output').hide(); |
|
322 | this.element.find('div.output').hide(); | |
310 | }; |
|
323 | }; | |
311 |
|
324 | |||
312 |
|
325 | |||
313 | CodeCell.prototype.expand = function () { |
|
326 | CodeCell.prototype.expand = function () { | |
314 | this.element.find('div.output').show(); |
|
327 | this.element.find('div.output').show(); | |
315 | }; |
|
328 | }; | |
316 |
|
329 | |||
317 |
|
330 | |||
318 | CodeCell.prototype.set_input_prompt = function (number) { |
|
331 | CodeCell.prototype.set_input_prompt = function (number) { | |
319 | var n = number || ' '; |
|
332 | var n = number || ' '; | |
320 | this.input_prompt_number = n |
|
333 | this.input_prompt_number = n | |
321 | this.element.find('div.input_prompt').html('In [' + n + ']:'); |
|
334 | this.element.find('div.input_prompt').html('In [' + n + ']:'); | |
322 | }; |
|
335 | }; | |
323 |
|
336 | |||
324 |
|
337 | |||
325 | CodeCell.prototype.get_code = function () { |
|
338 | CodeCell.prototype.get_code = function () { | |
326 | return this.code_mirror.getValue(); |
|
339 | return this.code_mirror.getValue(); | |
327 | }; |
|
340 | }; | |
328 |
|
341 | |||
329 |
|
342 | |||
330 | CodeCell.prototype.set_code = function (code) { |
|
343 | CodeCell.prototype.set_code = function (code) { | |
331 | return this.code_mirror.setValue(code); |
|
344 | return this.code_mirror.setValue(code); | |
332 | }; |
|
345 | }; | |
333 |
|
346 | |||
334 |
|
347 | |||
335 | CodeCell.prototype.at_top = function () { |
|
348 | CodeCell.prototype.at_top = function () { | |
336 | var cursor = this.code_mirror.getCursor(); |
|
349 | var cursor = this.code_mirror.getCursor(); | |
337 | if (cursor.line === 0) { |
|
350 | if (cursor.line === 0) { | |
338 | return true; |
|
351 | return true; | |
339 | } else { |
|
352 | } else { | |
340 | return false; |
|
353 | return false; | |
341 | } |
|
354 | } | |
342 | }; |
|
355 | }; | |
343 |
|
356 | |||
344 |
|
357 | |||
345 | CodeCell.prototype.at_bottom = function () { |
|
358 | CodeCell.prototype.at_bottom = function () { | |
346 | var cursor = this.code_mirror.getCursor(); |
|
359 | var cursor = this.code_mirror.getCursor(); | |
347 | if (cursor.line === (this.code_mirror.lineCount()-1)) { |
|
360 | if (cursor.line === (this.code_mirror.lineCount()-1)) { | |
348 | return true; |
|
361 | return true; | |
349 | } else { |
|
362 | } else { | |
350 | return false; |
|
363 | return false; | |
351 | } |
|
364 | } | |
352 | }; |
|
365 | }; | |
353 |
|
366 | |||
354 |
|
367 | |||
355 | CodeCell.prototype.fromJSON = function (data) { |
|
368 | CodeCell.prototype.fromJSON = function (data) { | |
356 | // console.log('Import from JSON:', data); |
|
369 | // console.log('Import from JSON:', data); | |
357 | if (data.cell_type === 'code') { |
|
370 | if (data.cell_type === 'code') { | |
358 | if (data.input !== undefined) { |
|
371 | if (data.input !== undefined) { | |
359 | this.set_code(data.input); |
|
372 | this.set_code(data.input); | |
360 | } |
|
373 | } | |
361 | if (data.prompt_number !== undefined) { |
|
374 | if (data.prompt_number !== undefined) { | |
362 | this.set_input_prompt(data.prompt_number); |
|
375 | this.set_input_prompt(data.prompt_number); | |
363 | } else { |
|
376 | } else { | |
364 | this.set_input_prompt(); |
|
377 | this.set_input_prompt(); | |
365 | }; |
|
378 | }; | |
366 | var len = data.outputs.length; |
|
379 | var len = data.outputs.length; | |
367 | for (var i=0; i<len; i++) { |
|
380 | for (var i=0; i<len; i++) { | |
368 | this.append_output(data.outputs[i]); |
|
381 | this.append_output(data.outputs[i]); | |
369 | }; |
|
382 | }; | |
370 | }; |
|
383 | }; | |
371 | }; |
|
384 | }; | |
372 |
|
385 | |||
373 |
|
386 | |||
374 | CodeCell.prototype.toJSON = function () { |
|
387 | CodeCell.prototype.toJSON = function () { | |
375 | var data = {}; |
|
388 | var data = {}; | |
376 | data.input = this.get_code(); |
|
389 | data.input = this.get_code(); | |
377 | data.cell_type = 'code'; |
|
390 | data.cell_type = 'code'; | |
378 | if (this.input_prompt_number !== ' ') { |
|
391 | if (this.input_prompt_number !== ' ') { | |
379 | data.prompt_number = this.input_prompt_number |
|
392 | data.prompt_number = this.input_prompt_number | |
380 | }; |
|
393 | }; | |
381 | var outputs = []; |
|
394 | var outputs = []; | |
382 | var len = this.outputs.length; |
|
395 | var len = this.outputs.length; | |
383 | for (var i=0; i<len; i++) { |
|
396 | for (var i=0; i<len; i++) { | |
384 | outputs[i] = this.outputs[i]; |
|
397 | outputs[i] = this.outputs[i]; | |
385 | }; |
|
398 | }; | |
386 | data.outputs = outputs; |
|
399 | data.outputs = outputs; | |
387 | data.language = 'python'; |
|
400 | data.language = 'python'; | |
388 | // console.log('Export to JSON:',data); |
|
401 | // console.log('Export to JSON:',data); | |
389 | return data; |
|
402 | return data; | |
390 | }; |
|
403 | }; | |
391 |
|
404 | |||
392 |
|
405 | |||
393 | IPython.CodeCell = CodeCell; |
|
406 | IPython.CodeCell = CodeCell; | |
394 |
|
407 | |||
395 | return IPython; |
|
408 | return IPython; | |
396 | }(IPython)); |
|
409 | }(IPython)); | |
397 |
|
410 |
@@ -1,729 +1,732 b'' | |||||
1 |
|
1 | |||
2 | //============================================================================ |
|
2 | //============================================================================ | |
3 | // Notebook |
|
3 | // Notebook | |
4 | //============================================================================ |
|
4 | //============================================================================ | |
5 |
|
5 | |||
6 | var IPython = (function (IPython) { |
|
6 | var IPython = (function (IPython) { | |
7 |
|
7 | |||
8 | var utils = IPython.utils; |
|
8 | var utils = IPython.utils; | |
9 |
|
9 | |||
10 | var Notebook = function (selector) { |
|
10 | var Notebook = function (selector) { | |
11 | this.element = $(selector); |
|
11 | this.element = $(selector); | |
12 | this.element.scroll(); |
|
12 | this.element.scroll(); | |
13 | this.element.data("notebook", this); |
|
13 | this.element.data("notebook", this); | |
14 | this.next_prompt_number = 1; |
|
14 | this.next_prompt_number = 1; | |
15 | this.kernel = null; |
|
15 | this.kernel = null; | |
16 | this.msg_cell_map = {}; |
|
16 | this.msg_cell_map = {}; | |
17 | this.style(); |
|
17 | this.style(); | |
18 | this.create_elements(); |
|
18 | this.create_elements(); | |
19 | this.bind_events(); |
|
19 | this.bind_events(); | |
20 | }; |
|
20 | }; | |
21 |
|
21 | |||
22 |
|
22 | |||
23 | Notebook.prototype.style = function () { |
|
23 | Notebook.prototype.style = function () { | |
24 | $('div#notebook').addClass('border-box-sizing'); |
|
24 | $('div#notebook').addClass('border-box-sizing'); | |
25 | }; |
|
25 | }; | |
26 |
|
26 | |||
27 |
|
27 | |||
28 | Notebook.prototype.create_elements = function () { |
|
28 | Notebook.prototype.create_elements = function () { | |
29 | // We add this end_space div to the end of the notebook div to: |
|
29 | // We add this end_space div to the end of the notebook div to: | |
30 | // i) provide a margin between the last cell and the end of the notebook |
|
30 | // i) provide a margin between the last cell and the end of the notebook | |
31 | // ii) to prevent the div from scrolling up when the last cell is being |
|
31 | // ii) to prevent the div from scrolling up when the last cell is being | |
32 | // edited, but is too low on the page, which browsers will do automatically. |
|
32 | // edited, but is too low on the page, which browsers will do automatically. | |
33 | this.element.append($('<div class="end_space"></div>').height(50)); |
|
33 | this.element.append($('<div class="end_space"></div>').height(50)); | |
34 | $('div#notebook').addClass('border-box-sizing'); |
|
34 | $('div#notebook').addClass('border-box-sizing'); | |
35 | }; |
|
35 | }; | |
36 |
|
36 | |||
37 |
|
37 | |||
38 | Notebook.prototype.bind_events = function () { |
|
38 | Notebook.prototype.bind_events = function () { | |
39 | var that = this; |
|
39 | var that = this; | |
40 | $(document).keydown(function (event) { |
|
40 | $(document).keydown(function (event) { | |
41 | // console.log(event); |
|
41 | // console.log(event); | |
42 | if (event.which === 38) { |
|
42 | if (event.which === 38) { | |
43 | var cell = that.selected_cell(); |
|
43 | var cell = that.selected_cell(); | |
44 | if (cell.at_top()) { |
|
44 | if (cell.at_top()) { | |
45 | event.preventDefault(); |
|
45 | event.preventDefault(); | |
46 | that.select_prev(); |
|
46 | that.select_prev(); | |
47 | }; |
|
47 | }; | |
48 | } else if (event.which === 40) { |
|
48 | } else if (event.which === 40) { | |
49 | var cell = that.selected_cell(); |
|
49 | var cell = that.selected_cell(); | |
50 | if (cell.at_bottom()) { |
|
50 | if (cell.at_bottom()) { | |
51 | event.preventDefault(); |
|
51 | event.preventDefault(); | |
52 | that.select_next(); |
|
52 | that.select_next(); | |
53 | }; |
|
53 | }; | |
54 | } else if (event.which === 13 && event.shiftKey) { |
|
54 | } else if (event.which === 13 && event.shiftKey) { | |
55 | that.execute_selected_cell(); |
|
55 | that.execute_selected_cell(); | |
56 | return false; |
|
56 | return false; | |
57 | } else if (event.which === 13 && event.ctrlKey) { |
|
57 | } else if (event.which === 13 && event.ctrlKey) { | |
58 | that.execute_selected_cell({terminal:true}); |
|
58 | that.execute_selected_cell({terminal:true}); | |
59 | return false; |
|
59 | return false; | |
60 | }; |
|
60 | }; | |
61 | }); |
|
61 | }); | |
62 |
|
62 | |||
63 | this.element.bind('collapse_pager', function () { |
|
63 | this.element.bind('collapse_pager', function () { | |
64 | var app_height = $('div#main_app').height(); // content height |
|
64 | var app_height = $('div#main_app').height(); // content height | |
65 | var splitter_height = $('div#pager_splitter').outerHeight(true); |
|
65 | var splitter_height = $('div#pager_splitter').outerHeight(true); | |
66 | var new_height = app_height - splitter_height; |
|
66 | var new_height = app_height - splitter_height; | |
67 | that.element.animate({height : new_height + 'px'}, 'fast'); |
|
67 | that.element.animate({height : new_height + 'px'}, 'fast'); | |
68 | }); |
|
68 | }); | |
69 |
|
69 | |||
70 | this.element.bind('expand_pager', function () { |
|
70 | this.element.bind('expand_pager', function () { | |
71 | var app_height = $('div#main_app').height(); // content height |
|
71 | var app_height = $('div#main_app').height(); // content height | |
72 | var splitter_height = $('div#pager_splitter').outerHeight(true); |
|
72 | var splitter_height = $('div#pager_splitter').outerHeight(true); | |
73 | var pager_height = $('div#pager').outerHeight(true); |
|
73 | var pager_height = $('div#pager').outerHeight(true); | |
74 | var new_height = app_height - pager_height - splitter_height; |
|
74 | var new_height = app_height - pager_height - splitter_height; | |
75 | that.element.animate({height : new_height + 'px'}, 'fast'); |
|
75 | that.element.animate({height : new_height + 'px'}, 'fast'); | |
76 | }); |
|
76 | }); | |
77 |
|
77 | |||
78 | this.element.bind('collapse_left_panel', function () { |
|
78 | this.element.bind('collapse_left_panel', function () { | |
79 | var splitter_width = $('div#left_panel_splitter').outerWidth(true); |
|
79 | var splitter_width = $('div#left_panel_splitter').outerWidth(true); | |
80 | var new_margin = splitter_width; |
|
80 | var new_margin = splitter_width; | |
81 | $('div#notebook_panel').animate({marginLeft : new_margin + 'px'}, 'fast'); |
|
81 | $('div#notebook_panel').animate({marginLeft : new_margin + 'px'}, 'fast'); | |
82 | }); |
|
82 | }); | |
83 |
|
83 | |||
84 | this.element.bind('expand_left_panel', function () { |
|
84 | this.element.bind('expand_left_panel', function () { | |
85 | var splitter_width = $('div#left_panel_splitter').outerWidth(true); |
|
85 | var splitter_width = $('div#left_panel_splitter').outerWidth(true); | |
86 | var left_panel_width = IPython.left_panel.width; |
|
86 | var left_panel_width = IPython.left_panel.width; | |
87 | var new_margin = splitter_width + left_panel_width; |
|
87 | var new_margin = splitter_width + left_panel_width; | |
88 | $('div#notebook_panel').animate({marginLeft : new_margin + 'px'}, 'fast'); |
|
88 | $('div#notebook_panel').animate({marginLeft : new_margin + 'px'}, 'fast'); | |
89 | }); |
|
89 | }); | |
90 | }; |
|
90 | }; | |
91 |
|
91 | |||
92 |
|
92 | |||
93 | Notebook.prototype.scroll_to_bottom = function () { |
|
93 | Notebook.prototype.scroll_to_bottom = function () { | |
94 | this.element.animate({scrollTop:this.element.get(0).scrollHeight}, 0); |
|
94 | this.element.animate({scrollTop:this.element.get(0).scrollHeight}, 0); | |
95 | }; |
|
95 | }; | |
96 |
|
96 | |||
97 |
|
97 | |||
98 | Notebook.prototype.scroll_to_top = function () { |
|
98 | Notebook.prototype.scroll_to_top = function () { | |
99 | this.element.animate({scrollTop:0}, 0); |
|
99 | this.element.animate({scrollTop:0}, 0); | |
100 | }; |
|
100 | }; | |
101 |
|
101 | |||
102 |
|
102 | |||
103 | // Cell indexing, retrieval, etc. |
|
103 | // Cell indexing, retrieval, etc. | |
104 |
|
104 | |||
105 |
|
105 | |||
106 | Notebook.prototype.cell_elements = function () { |
|
106 | Notebook.prototype.cell_elements = function () { | |
107 | return this.element.children("div.cell"); |
|
107 | return this.element.children("div.cell"); | |
108 | } |
|
108 | } | |
109 |
|
109 | |||
110 |
|
110 | |||
111 | Notebook.prototype.ncells = function (cell) { |
|
111 | Notebook.prototype.ncells = function (cell) { | |
112 | return this.cell_elements().length; |
|
112 | return this.cell_elements().length; | |
113 | } |
|
113 | } | |
114 |
|
114 | |||
115 |
|
115 | |||
116 | // TODO: we are often calling cells as cells()[i], which we should optimize |
|
116 | // TODO: we are often calling cells as cells()[i], which we should optimize | |
117 | // to cells(i) or a new method. |
|
117 | // to cells(i) or a new method. | |
118 | Notebook.prototype.cells = function () { |
|
118 | Notebook.prototype.cells = function () { | |
119 | return this.cell_elements().toArray().map(function (e) { |
|
119 | return this.cell_elements().toArray().map(function (e) { | |
120 | return $(e).data("cell"); |
|
120 | return $(e).data("cell"); | |
121 | }); |
|
121 | }); | |
122 | } |
|
122 | } | |
123 |
|
123 | |||
124 |
|
124 | |||
125 | Notebook.prototype.find_cell_index = function (cell) { |
|
125 | Notebook.prototype.find_cell_index = function (cell) { | |
126 | var result = null; |
|
126 | var result = null; | |
127 | this.cell_elements().filter(function (index) { |
|
127 | this.cell_elements().filter(function (index) { | |
128 | if ($(this).data("cell") === cell) { |
|
128 | if ($(this).data("cell") === cell) { | |
129 | result = index; |
|
129 | result = index; | |
130 | }; |
|
130 | }; | |
131 | }); |
|
131 | }); | |
132 | return result; |
|
132 | return result; | |
133 | }; |
|
133 | }; | |
134 |
|
134 | |||
135 |
|
135 | |||
136 | Notebook.prototype.index_or_selected = function (index) { |
|
136 | Notebook.prototype.index_or_selected = function (index) { | |
137 | return index || this.selected_index() || 0; |
|
137 | return index || this.selected_index() || 0; | |
138 | } |
|
138 | } | |
139 |
|
139 | |||
140 |
|
140 | |||
141 | Notebook.prototype.select = function (index) { |
|
141 | Notebook.prototype.select = function (index) { | |
142 | if (index !== undefined && index >= 0 && index < this.ncells()) { |
|
142 | if (index !== undefined && index >= 0 && index < this.ncells()) { | |
143 | if (this.selected_index() !== null) { |
|
143 | if (this.selected_index() !== null) { | |
144 | this.selected_cell().unselect(); |
|
144 | this.selected_cell().unselect(); | |
145 | }; |
|
145 | }; | |
146 | this.cells()[index].select(); |
|
146 | this.cells()[index].select(); | |
147 | if (index === (this.ncells()-1)) { |
|
147 | if (index === (this.ncells()-1)) { | |
148 | this.scroll_to_bottom(); |
|
148 | this.scroll_to_bottom(); | |
149 | }; |
|
149 | }; | |
150 | }; |
|
150 | }; | |
151 | return this; |
|
151 | return this; | |
152 | }; |
|
152 | }; | |
153 |
|
153 | |||
154 |
|
154 | |||
155 | Notebook.prototype.select_next = function () { |
|
155 | Notebook.prototype.select_next = function () { | |
156 | var index = this.selected_index(); |
|
156 | var index = this.selected_index(); | |
157 | if (index !== null && index >= 0 && (index+1) < this.ncells()) { |
|
157 | if (index !== null && index >= 0 && (index+1) < this.ncells()) { | |
158 | this.select(index+1); |
|
158 | this.select(index+1); | |
159 | }; |
|
159 | }; | |
160 | return this; |
|
160 | return this; | |
161 | }; |
|
161 | }; | |
162 |
|
162 | |||
163 |
|
163 | |||
164 | Notebook.prototype.select_prev = function () { |
|
164 | Notebook.prototype.select_prev = function () { | |
165 | var index = this.selected_index(); |
|
165 | var index = this.selected_index(); | |
166 | if (index !== null && index >= 0 && (index-1) < this.ncells()) { |
|
166 | if (index !== null && index >= 0 && (index-1) < this.ncells()) { | |
167 | this.select(index-1); |
|
167 | this.select(index-1); | |
168 | }; |
|
168 | }; | |
169 | return this; |
|
169 | return this; | |
170 | }; |
|
170 | }; | |
171 |
|
171 | |||
172 |
|
172 | |||
173 | Notebook.prototype.selected_index = function () { |
|
173 | Notebook.prototype.selected_index = function () { | |
174 | var result = null; |
|
174 | var result = null; | |
175 | this.cell_elements().filter(function (index) { |
|
175 | this.cell_elements().filter(function (index) { | |
176 | if ($(this).data("cell").selected === true) { |
|
176 | if ($(this).data("cell").selected === true) { | |
177 | result = index; |
|
177 | result = index; | |
178 | }; |
|
178 | }; | |
179 | }); |
|
179 | }); | |
180 | return result; |
|
180 | return result; | |
181 | }; |
|
181 | }; | |
182 |
|
182 | |||
183 |
|
183 | |||
184 | Notebook.prototype.cell_for_msg = function (msg_id) { |
|
184 | Notebook.prototype.cell_for_msg = function (msg_id) { | |
185 | var cell_id = this.msg_cell_map[msg_id]; |
|
185 | var cell_id = this.msg_cell_map[msg_id]; | |
186 | var result = null; |
|
186 | var result = null; | |
187 | this.cell_elements().filter(function (index) { |
|
187 | this.cell_elements().filter(function (index) { | |
188 | cell = $(this).data("cell"); |
|
188 | cell = $(this).data("cell"); | |
189 | if (cell.cell_id === cell_id) { |
|
189 | if (cell.cell_id === cell_id) { | |
190 | result = cell; |
|
190 | result = cell; | |
191 | }; |
|
191 | }; | |
192 | }); |
|
192 | }); | |
193 | return result; |
|
193 | return result; | |
194 | }; |
|
194 | }; | |
195 |
|
195 | |||
196 |
|
196 | |||
197 | Notebook.prototype.selected_cell = function () { |
|
197 | Notebook.prototype.selected_cell = function () { | |
198 | return this.cell_elements().eq(this.selected_index()).data("cell"); |
|
198 | return this.cell_elements().eq(this.selected_index()).data("cell"); | |
199 | } |
|
199 | } | |
200 |
|
200 | |||
201 |
|
201 | |||
202 | // Cell insertion, deletion and moving. |
|
202 | // Cell insertion, deletion and moving. | |
203 |
|
203 | |||
204 |
|
204 | |||
205 | Notebook.prototype.delete_cell = function (index) { |
|
205 | Notebook.prototype.delete_cell = function (index) { | |
206 | var i = index || this.selected_index(); |
|
206 | var i = index || this.selected_index(); | |
207 | if (i !== null && i >= 0 && i < this.ncells()) { |
|
207 | if (i !== null && i >= 0 && i < this.ncells()) { | |
208 | this.cell_elements().eq(i).remove(); |
|
208 | this.cell_elements().eq(i).remove(); | |
209 | if (i === (this.ncells())) { |
|
209 | if (i === (this.ncells())) { | |
210 | this.select(i-1); |
|
210 | this.select(i-1); | |
211 | } else { |
|
211 | } else { | |
212 | this.select(i); |
|
212 | this.select(i); | |
213 | }; |
|
213 | }; | |
214 | }; |
|
214 | }; | |
215 | return this; |
|
215 | return this; | |
216 | }; |
|
216 | }; | |
217 |
|
217 | |||
218 |
|
218 | |||
219 | Notebook.prototype.append_cell = function (cell) { |
|
219 | Notebook.prototype.append_cell = function (cell) { | |
220 | this.element.find('div.end_space').before(cell.element); |
|
220 | this.element.find('div.end_space').before(cell.element); | |
221 | return this; |
|
221 | return this; | |
222 | }; |
|
222 | }; | |
223 |
|
223 | |||
224 |
|
224 | |||
225 | Notebook.prototype.insert_cell_after = function (cell, index) { |
|
225 | Notebook.prototype.insert_cell_after = function (cell, index) { | |
226 | var ncells = this.ncells(); |
|
226 | var ncells = this.ncells(); | |
227 | if (ncells === 0) { |
|
227 | if (ncells === 0) { | |
228 | this.append_cell(cell); |
|
228 | this.append_cell(cell); | |
229 | return this; |
|
229 | return this; | |
230 | }; |
|
230 | }; | |
231 | if (index >= 0 && index < ncells) { |
|
231 | if (index >= 0 && index < ncells) { | |
232 | this.cell_elements().eq(index).after(cell.element); |
|
232 | this.cell_elements().eq(index).after(cell.element); | |
233 | }; |
|
233 | }; | |
234 | return this |
|
234 | return this | |
235 | }; |
|
235 | }; | |
236 |
|
236 | |||
237 |
|
237 | |||
238 | Notebook.prototype.insert_cell_before = function (cell, index) { |
|
238 | Notebook.prototype.insert_cell_before = function (cell, index) { | |
239 | var ncells = this.ncells(); |
|
239 | var ncells = this.ncells(); | |
240 | if (ncells === 0) { |
|
240 | if (ncells === 0) { | |
241 | this.append_cell(cell); |
|
241 | this.append_cell(cell); | |
242 | return this; |
|
242 | return this; | |
243 | }; |
|
243 | }; | |
244 | if (index >= 0 && index < ncells) { |
|
244 | if (index >= 0 && index < ncells) { | |
245 | this.cell_elements().eq(index).before(cell.element); |
|
245 | this.cell_elements().eq(index).before(cell.element); | |
246 | }; |
|
246 | }; | |
247 | return this; |
|
247 | return this; | |
248 | }; |
|
248 | }; | |
249 |
|
249 | |||
250 |
|
250 | |||
251 | Notebook.prototype.move_cell_up = function (index) { |
|
251 | Notebook.prototype.move_cell_up = function (index) { | |
252 | var i = index || this.selected_index(); |
|
252 | var i = index || this.selected_index(); | |
253 | if (i !== null && i < this.ncells() && i > 0) { |
|
253 | if (i !== null && i < this.ncells() && i > 0) { | |
254 | var pivot = this.cell_elements().eq(i-1); |
|
254 | var pivot = this.cell_elements().eq(i-1); | |
255 | var tomove = this.cell_elements().eq(i); |
|
255 | var tomove = this.cell_elements().eq(i); | |
256 | if (pivot !== null && tomove !== null) { |
|
256 | if (pivot !== null && tomove !== null) { | |
257 | tomove.detach(); |
|
257 | tomove.detach(); | |
258 | pivot.before(tomove); |
|
258 | pivot.before(tomove); | |
259 | this.select(i-1); |
|
259 | this.select(i-1); | |
260 | }; |
|
260 | }; | |
261 | }; |
|
261 | }; | |
262 | return this; |
|
262 | return this; | |
263 | } |
|
263 | } | |
264 |
|
264 | |||
265 |
|
265 | |||
266 | Notebook.prototype.move_cell_down = function (index) { |
|
266 | Notebook.prototype.move_cell_down = function (index) { | |
267 | var i = index || this.selected_index(); |
|
267 | var i = index || this.selected_index(); | |
268 | if (i !== null && i < (this.ncells()-1) && i >= 0) { |
|
268 | if (i !== null && i < (this.ncells()-1) && i >= 0) { | |
269 | var pivot = this.cell_elements().eq(i+1) |
|
269 | var pivot = this.cell_elements().eq(i+1) | |
270 | var tomove = this.cell_elements().eq(i) |
|
270 | var tomove = this.cell_elements().eq(i) | |
271 | if (pivot !== null && tomove !== null) { |
|
271 | if (pivot !== null && tomove !== null) { | |
272 | tomove.detach(); |
|
272 | tomove.detach(); | |
273 | pivot.after(tomove); |
|
273 | pivot.after(tomove); | |
274 | this.select(i+1); |
|
274 | this.select(i+1); | |
275 | }; |
|
275 | }; | |
276 | }; |
|
276 | }; | |
277 | return this; |
|
277 | return this; | |
278 | } |
|
278 | } | |
279 |
|
279 | |||
280 |
|
280 | |||
281 | Notebook.prototype.sort_cells = function () { |
|
281 | Notebook.prototype.sort_cells = function () { | |
282 | var ncells = this.ncells(); |
|
282 | var ncells = this.ncells(); | |
283 | var sindex = this.selected_index(); |
|
283 | var sindex = this.selected_index(); | |
284 | var swapped; |
|
284 | var swapped; | |
285 | do { |
|
285 | do { | |
286 | swapped = false |
|
286 | swapped = false | |
287 | for (var i=1; i<ncells; i++) { |
|
287 | for (var i=1; i<ncells; i++) { | |
288 | current = this.cell_elements().eq(i).data("cell"); |
|
288 | current = this.cell_elements().eq(i).data("cell"); | |
289 | previous = this.cell_elements().eq(i-1).data("cell"); |
|
289 | previous = this.cell_elements().eq(i-1).data("cell"); | |
290 | if (previous.input_prompt_number > current.input_prompt_number) { |
|
290 | if (previous.input_prompt_number > current.input_prompt_number) { | |
291 | this.move_cell_up(i); |
|
291 | this.move_cell_up(i); | |
292 | swapped = true; |
|
292 | swapped = true; | |
293 | }; |
|
293 | }; | |
294 | }; |
|
294 | }; | |
295 | } while (swapped); |
|
295 | } while (swapped); | |
296 | this.select(sindex); |
|
296 | this.select(sindex); | |
297 | return this; |
|
297 | return this; | |
298 | }; |
|
298 | }; | |
299 |
|
299 | |||
300 |
|
300 | |||
301 | Notebook.prototype.insert_code_cell_before = function (index) { |
|
301 | Notebook.prototype.insert_code_cell_before = function (index) { | |
302 | // TODO: Bounds check for i |
|
302 | // TODO: Bounds check for i | |
303 | var i = this.index_or_selected(index); |
|
303 | var i = this.index_or_selected(index); | |
304 | var cell = new IPython.CodeCell(this); |
|
304 | var cell = new IPython.CodeCell(this); | |
305 | cell.set_input_prompt(); |
|
305 | cell.set_input_prompt(); | |
306 | this.insert_cell_before(cell, i); |
|
306 | this.insert_cell_before(cell, i); | |
307 | this.select(this.find_cell_index(cell)); |
|
307 | this.select(this.find_cell_index(cell)); | |
308 | return cell; |
|
308 | return cell; | |
309 | } |
|
309 | } | |
310 |
|
310 | |||
311 |
|
311 | |||
312 | Notebook.prototype.insert_code_cell_after = function (index) { |
|
312 | Notebook.prototype.insert_code_cell_after = function (index) { | |
313 | // TODO: Bounds check for i |
|
313 | // TODO: Bounds check for i | |
314 | var i = this.index_or_selected(index); |
|
314 | var i = this.index_or_selected(index); | |
315 | var cell = new IPython.CodeCell(this); |
|
315 | var cell = new IPython.CodeCell(this); | |
316 | cell.set_input_prompt(); |
|
316 | cell.set_input_prompt(); | |
317 | this.insert_cell_after(cell, i); |
|
317 | this.insert_cell_after(cell, i); | |
318 | this.select(this.find_cell_index(cell)); |
|
318 | this.select(this.find_cell_index(cell)); | |
319 | return cell; |
|
319 | return cell; | |
320 | } |
|
320 | } | |
321 |
|
321 | |||
322 |
|
322 | |||
323 | Notebook.prototype.insert_html_cell_before = function (index) { |
|
323 | Notebook.prototype.insert_html_cell_before = function (index) { | |
324 | // TODO: Bounds check for i |
|
324 | // TODO: Bounds check for i | |
325 | var i = this.index_or_selected(index); |
|
325 | var i = this.index_or_selected(index); | |
326 | var cell = new IPython.HTMLCell(this); |
|
326 | var cell = new IPython.HTMLCell(this); | |
327 | cell.config_mathjax(); |
|
327 | cell.config_mathjax(); | |
328 | this.insert_cell_before(cell, i); |
|
328 | this.insert_cell_before(cell, i); | |
329 | this.select(this.find_cell_index(cell)); |
|
329 | this.select(this.find_cell_index(cell)); | |
330 | return cell; |
|
330 | return cell; | |
331 | } |
|
331 | } | |
332 |
|
332 | |||
333 |
|
333 | |||
334 | Notebook.prototype.insert_html_cell_after = function (index) { |
|
334 | Notebook.prototype.insert_html_cell_after = function (index) { | |
335 | // TODO: Bounds check for i |
|
335 | // TODO: Bounds check for i | |
336 | var i = this.index_or_selected(index); |
|
336 | var i = this.index_or_selected(index); | |
337 | var cell = new IPython.HTMLCell(this); |
|
337 | var cell = new IPython.HTMLCell(this); | |
338 | cell.config_mathjax(); |
|
338 | cell.config_mathjax(); | |
339 | this.insert_cell_after(cell, i); |
|
339 | this.insert_cell_after(cell, i); | |
340 | this.select(this.find_cell_index(cell)); |
|
340 | this.select(this.find_cell_index(cell)); | |
341 | return cell; |
|
341 | return cell; | |
342 | } |
|
342 | } | |
343 |
|
343 | |||
344 |
|
344 | |||
345 | Notebook.prototype.insert_markdown_cell_before = function (index) { |
|
345 | Notebook.prototype.insert_markdown_cell_before = function (index) { | |
346 | // TODO: Bounds check for i |
|
346 | // TODO: Bounds check for i | |
347 | var i = this.index_or_selected(index); |
|
347 | var i = this.index_or_selected(index); | |
348 | var cell = new IPython.MarkdownCell(this); |
|
348 | var cell = new IPython.MarkdownCell(this); | |
349 | cell.config_mathjax(); |
|
349 | cell.config_mathjax(); | |
350 | this.insert_cell_before(cell, i); |
|
350 | this.insert_cell_before(cell, i); | |
351 | this.select(this.find_cell_index(cell)); |
|
351 | this.select(this.find_cell_index(cell)); | |
352 | return cell; |
|
352 | return cell; | |
353 | } |
|
353 | } | |
354 |
|
354 | |||
355 |
|
355 | |||
356 | Notebook.prototype.insert_markdown_cell_after = function (index) { |
|
356 | Notebook.prototype.insert_markdown_cell_after = function (index) { | |
357 | // TODO: Bounds check for i |
|
357 | // TODO: Bounds check for i | |
358 | var i = this.index_or_selected(index); |
|
358 | var i = this.index_or_selected(index); | |
359 | var cell = new IPython.MarkdownCell(this); |
|
359 | var cell = new IPython.MarkdownCell(this); | |
360 | cell.config_mathjax(); |
|
360 | cell.config_mathjax(); | |
361 | this.insert_cell_after(cell, i); |
|
361 | this.insert_cell_after(cell, i); | |
362 | this.select(this.find_cell_index(cell)); |
|
362 | this.select(this.find_cell_index(cell)); | |
363 | return cell; |
|
363 | return cell; | |
364 | } |
|
364 | } | |
365 |
|
365 | |||
366 |
|
366 | |||
367 | Notebook.prototype.to_code = function (index) { |
|
367 | Notebook.prototype.to_code = function (index) { | |
368 | // TODO: Bounds check for i |
|
368 | // TODO: Bounds check for i | |
369 | var i = this.index_or_selected(index); |
|
369 | var i = this.index_or_selected(index); | |
370 | var source_element = this.cell_elements().eq(i); |
|
370 | var source_element = this.cell_elements().eq(i); | |
371 | var source_cell = source_element.data("cell"); |
|
371 | var source_cell = source_element.data("cell"); | |
372 | if (source_cell instanceof IPython.HTMLCell || |
|
372 | if (source_cell instanceof IPython.HTMLCell || | |
373 | source_cell instanceof IPython.MarkdownCell) { |
|
373 | source_cell instanceof IPython.MarkdownCell) { | |
374 | this.insert_code_cell_after(i); |
|
374 | this.insert_code_cell_after(i); | |
375 | var target_cell = this.cells()[i+1]; |
|
375 | var target_cell = this.cells()[i+1]; | |
376 | target_cell.set_code(source_cell.get_source()); |
|
376 | target_cell.set_code(source_cell.get_source()); | |
377 | source_element.remove(); |
|
377 | source_element.remove(); | |
378 | }; |
|
378 | }; | |
379 | }; |
|
379 | }; | |
380 |
|
380 | |||
381 |
|
381 | |||
382 | Notebook.prototype.to_markdown = function (index) { |
|
382 | Notebook.prototype.to_markdown = function (index) { | |
383 | // TODO: Bounds check for i |
|
383 | // TODO: Bounds check for i | |
384 | var i = this.index_or_selected(index); |
|
384 | var i = this.index_or_selected(index); | |
385 | var source_element = this.cell_elements().eq(i); |
|
385 | var source_element = this.cell_elements().eq(i); | |
386 | var source_cell = source_element.data("cell"); |
|
386 | var source_cell = source_element.data("cell"); | |
387 | var target_cell = null; |
|
387 | var target_cell = null; | |
388 | if (source_cell instanceof IPython.CodeCell) { |
|
388 | if (source_cell instanceof IPython.CodeCell) { | |
389 | this.insert_markdown_cell_after(i); |
|
389 | this.insert_markdown_cell_after(i); | |
390 | var target_cell = this.cells()[i+1]; |
|
390 | var target_cell = this.cells()[i+1]; | |
391 | var text = source_cell.get_code(); |
|
391 | var text = source_cell.get_code(); | |
392 | } else if (source_cell instanceof IPython.HTMLCell) { |
|
392 | } else if (source_cell instanceof IPython.HTMLCell) { | |
393 | this.insert_markdown_cell_after(i); |
|
393 | this.insert_markdown_cell_after(i); | |
394 | var target_cell = this.cells()[i+1]; |
|
394 | var target_cell = this.cells()[i+1]; | |
395 | var text = source_cell.get_source(); |
|
395 | var text = source_cell.get_source(); | |
396 | if (text === source_cell.placeholder) { |
|
396 | if (text === source_cell.placeholder) { | |
397 | text = target_cell.placeholder; |
|
397 | text = target_cell.placeholder; | |
398 | } |
|
398 | } | |
399 | } |
|
399 | } | |
400 | if (target_cell !== null) { |
|
400 | if (target_cell !== null) { | |
401 | if (text === "") {text = target_cell.placeholder;}; |
|
401 | if (text === "") {text = target_cell.placeholder;}; | |
402 | target_cell.set_source(text); |
|
402 | target_cell.set_source(text); | |
403 | source_element.remove(); |
|
403 | source_element.remove(); | |
404 | target_cell.edit(); |
|
404 | target_cell.edit(); | |
405 | } |
|
405 | } | |
406 | }; |
|
406 | }; | |
407 |
|
407 | |||
408 |
|
408 | |||
409 | Notebook.prototype.to_html = function (index) { |
|
409 | Notebook.prototype.to_html = function (index) { | |
410 | // TODO: Bounds check for i |
|
410 | // TODO: Bounds check for i | |
411 | var i = this.index_or_selected(index); |
|
411 | var i = this.index_or_selected(index); | |
412 | var source_element = this.cell_elements().eq(i); |
|
412 | var source_element = this.cell_elements().eq(i); | |
413 | var source_cell = source_element.data("cell"); |
|
413 | var source_cell = source_element.data("cell"); | |
414 | var target_cell = null; |
|
414 | var target_cell = null; | |
415 | if (source_cell instanceof IPython.CodeCell) { |
|
415 | if (source_cell instanceof IPython.CodeCell) { | |
416 | this.insert_html_cell_after(i); |
|
416 | this.insert_html_cell_after(i); | |
417 | var target_cell = this.cells()[i+1]; |
|
417 | var target_cell = this.cells()[i+1]; | |
418 | var text = source_cell.get_code(); |
|
418 | var text = source_cell.get_code(); | |
419 | } else if (source_cell instanceof IPython.MarkdownCell) { |
|
419 | } else if (source_cell instanceof IPython.MarkdownCell) { | |
420 | this.insert_html_cell_after(i); |
|
420 | this.insert_html_cell_after(i); | |
421 | var target_cell = this.cells()[i+1]; |
|
421 | var target_cell = this.cells()[i+1]; | |
422 | var text = source_cell.get_source(); |
|
422 | var text = source_cell.get_source(); | |
423 | if (text === source_cell.placeholder) { |
|
423 | if (text === source_cell.placeholder) { | |
424 | text = target_cell.placeholder; |
|
424 | text = target_cell.placeholder; | |
425 | } |
|
425 | } | |
426 | } |
|
426 | } | |
427 | if (target_cell !== null) { |
|
427 | if (target_cell !== null) { | |
428 | if (text === "") {text = target_cell.placeholder;}; |
|
428 | if (text === "") {text = target_cell.placeholder;}; | |
429 | target_cell.set_source(text); |
|
429 | target_cell.set_source(text); | |
430 | source_element.remove(); |
|
430 | source_element.remove(); | |
431 | target_cell.edit(); |
|
431 | target_cell.edit(); | |
432 | } |
|
432 | } | |
433 | }; |
|
433 | }; | |
434 |
|
434 | |||
435 |
|
435 | |||
436 | // Cell collapsing |
|
436 | // Cell collapsing | |
437 |
|
437 | |||
438 | Notebook.prototype.collapse = function (index) { |
|
438 | Notebook.prototype.collapse = function (index) { | |
439 | var i = this.index_or_selected(index); |
|
439 | var i = this.index_or_selected(index); | |
440 | this.cells()[i].collapse(); |
|
440 | this.cells()[i].collapse(); | |
441 | }; |
|
441 | }; | |
442 |
|
442 | |||
443 |
|
443 | |||
444 | Notebook.prototype.expand = function (index) { |
|
444 | Notebook.prototype.expand = function (index) { | |
445 | var i = this.index_or_selected(index); |
|
445 | var i = this.index_or_selected(index); | |
446 | this.cells()[i].expand(); |
|
446 | this.cells()[i].expand(); | |
447 | }; |
|
447 | }; | |
448 |
|
448 | |||
449 |
|
449 | |||
450 | Notebook.prototype.set_autoindent = function (state) { |
|
450 | Notebook.prototype.set_autoindent = function (state) { | |
451 | var cells = this.cells(); |
|
451 | var cells = this.cells(); | |
452 | len = cells.length; |
|
452 | len = cells.length; | |
453 | for (var i=0; i<len; i++) { |
|
453 | for (var i=0; i<len; i++) { | |
454 | cells[i].set_autoindent(state) |
|
454 | cells[i].set_autoindent(state) | |
455 | }; |
|
455 | }; | |
456 | }; |
|
456 | }; | |
457 |
|
457 | |||
458 | // Kernel related things |
|
458 | // Kernel related things | |
459 |
|
459 | |||
460 | Notebook.prototype.start_kernel = function () { |
|
460 | Notebook.prototype.start_kernel = function () { | |
461 | this.kernel = new IPython.Kernel(); |
|
461 | this.kernel = new IPython.Kernel(); | |
462 | var notebook_id = IPython.save_widget.get_notebook_id(); |
|
462 | var notebook_id = IPython.save_widget.get_notebook_id(); | |
463 | this.kernel.start_kernel(notebook_id, $.proxy(this.kernel_started, this)); |
|
463 | this.kernel.start_kernel(notebook_id, $.proxy(this.kernel_started, this)); | |
464 | }; |
|
464 | }; | |
465 |
|
465 | |||
466 |
|
466 | |||
467 | Notebook.prototype.handle_shell_reply = function (e) { |
|
467 | Notebook.prototype.handle_shell_reply = function (e) { | |
468 | reply = $.parseJSON(e.data); |
|
468 | reply = $.parseJSON(e.data); | |
469 | var header = reply.header; |
|
469 | var header = reply.header; | |
470 | var content = reply.content; |
|
470 | var content = reply.content; | |
471 | var msg_type = header.msg_type; |
|
471 | var msg_type = header.msg_type; | |
472 | // console.log(reply); |
|
472 | // console.log(reply); | |
473 | var cell = this.cell_for_msg(reply.parent_header.msg_id); |
|
473 | var cell = this.cell_for_msg(reply.parent_header.msg_id); | |
474 | if (msg_type === "execute_reply") { |
|
474 | if (msg_type === "execute_reply") { | |
475 | cell.set_input_prompt(content.execution_count); |
|
475 | cell.set_input_prompt(content.execution_count); | |
476 | } else if (msg_type === "complete_reply") { |
|
476 | } else if (msg_type === "complete_reply") { | |
477 | cell.finish_completing(content.matched_text, content.matches); |
|
477 | cell.finish_completing(content.matched_text, content.matches); | |
478 | }; |
|
478 | }; | |
479 | var payload = content.payload || []; |
|
479 | var payload = content.payload || []; | |
480 | this.handle_payload(payload); |
|
480 | this.handle_payload(payload); | |
481 | }; |
|
481 | }; | |
482 |
|
482 | |||
483 |
|
483 | |||
484 | Notebook.prototype.handle_payload = function (payload) { |
|
484 | Notebook.prototype.handle_payload = function (payload) { | |
485 | var l = payload.length; |
|
485 | var l = payload.length; | |
486 | if (l > 0) { |
|
486 | if (l > 0) { | |
487 | IPython.pager.clear(); |
|
487 | IPython.pager.clear(); | |
488 | IPython.pager.expand(); |
|
488 | IPython.pager.expand(); | |
489 | }; |
|
489 | }; | |
490 | for (var i=0; i<l; i++) { |
|
490 | for (var i=0; i<l; i++) { | |
491 | IPython.pager.append_text(payload[i].text); |
|
491 | IPython.pager.append_text(payload[i].text); | |
492 | }; |
|
492 | }; | |
493 | }; |
|
493 | }; | |
494 |
|
494 | |||
495 |
|
495 | |||
496 | Notebook.prototype.handle_iopub_reply = function (e) { |
|
496 | Notebook.prototype.handle_iopub_reply = function (e) { | |
497 | reply = $.parseJSON(e.data); |
|
497 | reply = $.parseJSON(e.data); | |
498 | var content = reply.content; |
|
498 | var content = reply.content; | |
499 | // console.log(reply); |
|
499 | // console.log(reply); | |
500 | var msg_type = reply.header.msg_type; |
|
500 | var msg_type = reply.header.msg_type; | |
501 | var cell = this.cell_for_msg(reply.parent_header.msg_id); |
|
501 | var cell = this.cell_for_msg(reply.parent_header.msg_id); | |
502 | var output_types = ['stream','display_data','pyout','pyerr']; |
|
502 | var output_types = ['stream','display_data','pyout','pyerr']; | |
503 | if (output_types.indexOf(msg_type) >= 0) { |
|
503 | if (output_types.indexOf(msg_type) >= 0) { | |
504 | this.handle_output(cell, msg_type, content); |
|
504 | this.handle_output(cell, msg_type, content); | |
505 | } else if (msg_type === "status") { |
|
505 | } else if (msg_type === "status") { | |
506 | if (content.execution_state === "busy") { |
|
506 | if (content.execution_state === "busy") { | |
507 | IPython.kernel_status_widget.status_busy(); |
|
507 | IPython.kernel_status_widget.status_busy(); | |
508 | } else if (content.execution_state === "idle") { |
|
508 | } else if (content.execution_state === "idle") { | |
509 | IPython.kernel_status_widget.status_idle(); |
|
509 | IPython.kernel_status_widget.status_idle(); | |
510 | }; |
|
510 | }; | |
511 | } |
|
511 | } | |
512 | }; |
|
512 | }; | |
513 |
|
513 | |||
514 |
|
514 | |||
515 | Notebook.prototype.handle_output = function (cell, msg_type, content) { |
|
515 | Notebook.prototype.handle_output = function (cell, msg_type, content) { | |
516 | var json = {}; |
|
516 | var json = {}; | |
517 | json.output_type = msg_type; |
|
517 | json.output_type = msg_type; | |
518 | if (msg_type === "stream") { |
|
518 | if (msg_type === "stream") { | |
519 | json.text = content.data + '\n'; |
|
519 | json.text = content.data + '\n'; | |
520 | } else if (msg_type === "display_data") { |
|
520 | } else if (msg_type === "display_data") { | |
521 | json = this.convert_mime_types(json, content.data); |
|
521 | json = this.convert_mime_types(json, content.data); | |
522 | } else if (msg_type === "pyout") { |
|
522 | } else if (msg_type === "pyout") { | |
523 | json.prompt_number = content.execution_count; |
|
523 | json.prompt_number = content.execution_count; | |
524 | json = this.convert_mime_types(json, content.data); |
|
524 | json = this.convert_mime_types(json, content.data); | |
525 | } else if (msg_type === "pyerr") { |
|
525 | } else if (msg_type === "pyerr") { | |
526 | json.ename = content.ename; |
|
526 | json.ename = content.ename; | |
527 | json.evalue = content.evalue; |
|
527 | json.evalue = content.evalue; | |
528 | json.traceback = content.traceback; |
|
528 | json.traceback = content.traceback; | |
529 | }; |
|
529 | }; | |
530 | cell.append_output(json); |
|
530 | cell.append_output(json); | |
531 | }; |
|
531 | }; | |
532 |
|
532 | |||
533 |
|
533 | |||
534 | Notebook.prototype.convert_mime_types = function (json, data) { |
|
534 | Notebook.prototype.convert_mime_types = function (json, data) { | |
535 | if (data['text/plain'] !== undefined) { |
|
535 | if (data['text/plain'] !== undefined) { | |
536 | json.text = data['text/plain']; |
|
536 | json.text = data['text/plain']; | |
537 | }; |
|
537 | }; | |
538 | if (data['text/html'] !== undefined) { |
|
538 | if (data['text/html'] !== undefined) { | |
539 | json.html = data['text/html']; |
|
539 | json.html = data['text/html']; | |
540 | }; |
|
540 | }; | |
541 | if (data['image/svg+xml'] !== undefined) { |
|
541 | if (data['image/svg+xml'] !== undefined) { | |
542 | json.svg = data['image/svg+xml']; |
|
542 | json.svg = data['image/svg+xml']; | |
543 | }; |
|
543 | }; | |
544 | if (data['image/png'] !== undefined) { |
|
544 | if (data['image/png'] !== undefined) { | |
545 | json.png = data['image/png']; |
|
545 | json.png = data['image/png']; | |
546 | }; |
|
546 | }; | |
|
547 | if (data['image/jpeg'] !== undefined) { | |||
|
548 | json.jpeg = data['image/jpeg']; | |||
|
549 | }; | |||
547 | if (data['text/latex'] !== undefined) { |
|
550 | if (data['text/latex'] !== undefined) { | |
548 | json.latex = data['text/latex']; |
|
551 | json.latex = data['text/latex']; | |
549 | }; |
|
552 | }; | |
550 | if (data['application/json'] !== undefined) { |
|
553 | if (data['application/json'] !== undefined) { | |
551 | json.json = data['application/json']; |
|
554 | json.json = data['application/json']; | |
552 | }; |
|
555 | }; | |
553 | if (data['application/javascript'] !== undefined) { |
|
556 | if (data['application/javascript'] !== undefined) { | |
554 | json.javascript = data['application/javascript']; |
|
557 | json.javascript = data['application/javascript']; | |
555 | } |
|
558 | } | |
556 | return json; |
|
559 | return json; | |
557 | }; |
|
560 | }; | |
558 |
|
561 | |||
559 | Notebook.prototype.kernel_started = function () { |
|
562 | Notebook.prototype.kernel_started = function () { | |
560 | console.log("Kernel started: ", this.kernel.kernel_id); |
|
563 | console.log("Kernel started: ", this.kernel.kernel_id); | |
561 | this.kernel.shell_channel.onmessage = $.proxy(this.handle_shell_reply,this); |
|
564 | this.kernel.shell_channel.onmessage = $.proxy(this.handle_shell_reply,this); | |
562 | this.kernel.iopub_channel.onmessage = $.proxy(this.handle_iopub_reply,this); |
|
565 | this.kernel.iopub_channel.onmessage = $.proxy(this.handle_iopub_reply,this); | |
563 | }; |
|
566 | }; | |
564 |
|
567 | |||
565 |
|
568 | |||
566 | Notebook.prototype.execute_selected_cell = function (options) { |
|
569 | Notebook.prototype.execute_selected_cell = function (options) { | |
567 | // add_new: should a new cell be added if we are at the end of the nb |
|
570 | // add_new: should a new cell be added if we are at the end of the nb | |
568 | // terminal: execute in terminal mode, which stays in the current cell |
|
571 | // terminal: execute in terminal mode, which stays in the current cell | |
569 | default_options = {terminal: false, add_new: true} |
|
572 | default_options = {terminal: false, add_new: true} | |
570 | $.extend(default_options, options) |
|
573 | $.extend(default_options, options) | |
571 | var that = this; |
|
574 | var that = this; | |
572 | var cell = that.selected_cell(); |
|
575 | var cell = that.selected_cell(); | |
573 | var cell_index = that.find_cell_index(cell); |
|
576 | var cell_index = that.find_cell_index(cell); | |
574 | if (cell instanceof IPython.CodeCell) { |
|
577 | if (cell instanceof IPython.CodeCell) { | |
575 | cell.clear_output(); |
|
578 | cell.clear_output(); | |
576 | var code = cell.get_code(); |
|
579 | var code = cell.get_code(); | |
577 | var msg_id = that.kernel.execute(cell.get_code()); |
|
580 | var msg_id = that.kernel.execute(cell.get_code()); | |
578 | that.msg_cell_map[msg_id] = cell.cell_id; |
|
581 | that.msg_cell_map[msg_id] = cell.cell_id; | |
579 | } else if (cell instanceof IPython.HTMLCell) { |
|
582 | } else if (cell instanceof IPython.HTMLCell) { | |
580 | cell.render(); |
|
583 | cell.render(); | |
581 | } |
|
584 | } | |
582 | if (default_options.terminal) { |
|
585 | if (default_options.terminal) { | |
583 | cell.clear_input(); |
|
586 | cell.clear_input(); | |
584 | } else { |
|
587 | } else { | |
585 | if ((cell_index === (that.ncells()-1)) && default_options.add_new) { |
|
588 | if ((cell_index === (that.ncells()-1)) && default_options.add_new) { | |
586 | that.insert_code_cell_after(); |
|
589 | that.insert_code_cell_after(); | |
587 | // If we are adding a new cell at the end, scroll down to show it. |
|
590 | // If we are adding a new cell at the end, scroll down to show it. | |
588 | that.scroll_to_bottom(); |
|
591 | that.scroll_to_bottom(); | |
589 | } else { |
|
592 | } else { | |
590 | that.select(cell_index+1); |
|
593 | that.select(cell_index+1); | |
591 | }; |
|
594 | }; | |
592 | }; |
|
595 | }; | |
593 | }; |
|
596 | }; | |
594 |
|
597 | |||
595 |
|
598 | |||
596 | Notebook.prototype.execute_all_cells = function () { |
|
599 | Notebook.prototype.execute_all_cells = function () { | |
597 | var ncells = this.ncells(); |
|
600 | var ncells = this.ncells(); | |
598 | for (var i=0; i<ncells; i++) { |
|
601 | for (var i=0; i<ncells; i++) { | |
599 | this.select(i); |
|
602 | this.select(i); | |
600 | this.execute_selected_cell({add_new:false}); |
|
603 | this.execute_selected_cell({add_new:false}); | |
601 | }; |
|
604 | }; | |
602 | this.scroll_to_bottom(); |
|
605 | this.scroll_to_bottom(); | |
603 | }; |
|
606 | }; | |
604 |
|
607 | |||
605 |
|
608 | |||
606 | Notebook.prototype.complete_cell = function (cell, line, cursor_pos) { |
|
609 | Notebook.prototype.complete_cell = function (cell, line, cursor_pos) { | |
607 | var msg_id = this.kernel.complete(line, cursor_pos); |
|
610 | var msg_id = this.kernel.complete(line, cursor_pos); | |
608 | this.msg_cell_map[msg_id] = cell.cell_id; |
|
611 | this.msg_cell_map[msg_id] = cell.cell_id; | |
609 | }; |
|
612 | }; | |
610 |
|
613 | |||
611 | // Persistance and loading |
|
614 | // Persistance and loading | |
612 |
|
615 | |||
613 |
|
616 | |||
614 | Notebook.prototype.fromJSON = function (data) { |
|
617 | Notebook.prototype.fromJSON = function (data) { | |
615 | var ncells = this.ncells(); |
|
618 | var ncells = this.ncells(); | |
616 | for (var i=0; i<ncells; i++) { |
|
619 | for (var i=0; i<ncells; i++) { | |
617 | // Always delete cell 0 as they get renumbered as they are deleted. |
|
620 | // Always delete cell 0 as they get renumbered as they are deleted. | |
618 | this.delete_cell(0); |
|
621 | this.delete_cell(0); | |
619 | }; |
|
622 | }; | |
620 | // Only handle 1 worksheet for now. |
|
623 | // Only handle 1 worksheet for now. | |
621 | var worksheet = data.worksheets[0]; |
|
624 | var worksheet = data.worksheets[0]; | |
622 | if (worksheet !== undefined) { |
|
625 | if (worksheet !== undefined) { | |
623 | var new_cells = worksheet.cells; |
|
626 | var new_cells = worksheet.cells; | |
624 | ncells = new_cells.length; |
|
627 | ncells = new_cells.length; | |
625 | var cell_data = null; |
|
628 | var cell_data = null; | |
626 | var new_cell = null; |
|
629 | var new_cell = null; | |
627 | for (var i=0; i<ncells; i++) { |
|
630 | for (var i=0; i<ncells; i++) { | |
628 | cell_data = new_cells[i]; |
|
631 | cell_data = new_cells[i]; | |
629 | if (cell_data.cell_type == 'code') { |
|
632 | if (cell_data.cell_type == 'code') { | |
630 | new_cell = this.insert_code_cell_after(); |
|
633 | new_cell = this.insert_code_cell_after(); | |
631 | new_cell.fromJSON(cell_data); |
|
634 | new_cell.fromJSON(cell_data); | |
632 | } else if (cell_data.cell_type === 'html') { |
|
635 | } else if (cell_data.cell_type === 'html') { | |
633 | new_cell = this.insert_html_cell_after(); |
|
636 | new_cell = this.insert_html_cell_after(); | |
634 | new_cell.fromJSON(cell_data); |
|
637 | new_cell.fromJSON(cell_data); | |
635 | } else if (cell_data.cell_type === 'markdown') { |
|
638 | } else if (cell_data.cell_type === 'markdown') { | |
636 | new_cell = this.insert_markdown_cell_after(); |
|
639 | new_cell = this.insert_markdown_cell_after(); | |
637 | new_cell.fromJSON(cell_data); |
|
640 | new_cell.fromJSON(cell_data); | |
638 | }; |
|
641 | }; | |
639 | }; |
|
642 | }; | |
640 | }; |
|
643 | }; | |
641 | }; |
|
644 | }; | |
642 |
|
645 | |||
643 |
|
646 | |||
644 | Notebook.prototype.toJSON = function () { |
|
647 | Notebook.prototype.toJSON = function () { | |
645 | var cells = this.cells(); |
|
648 | var cells = this.cells(); | |
646 | var ncells = cells.length; |
|
649 | var ncells = cells.length; | |
647 | cell_array = new Array(ncells); |
|
650 | cell_array = new Array(ncells); | |
648 | for (var i=0; i<ncells; i++) { |
|
651 | for (var i=0; i<ncells; i++) { | |
649 | cell_array[i] = cells[i].toJSON(); |
|
652 | cell_array[i] = cells[i].toJSON(); | |
650 | }; |
|
653 | }; | |
651 | data = { |
|
654 | data = { | |
652 | // Only handle 1 worksheet for now. |
|
655 | // Only handle 1 worksheet for now. | |
653 | worksheets : [{cells:cell_array}] |
|
656 | worksheets : [{cells:cell_array}] | |
654 | } |
|
657 | } | |
655 | return data |
|
658 | return data | |
656 | }; |
|
659 | }; | |
657 |
|
660 | |||
658 | Notebook.prototype.save_notebook = function () { |
|
661 | Notebook.prototype.save_notebook = function () { | |
659 | if (IPython.save_widget.test_notebook_name()) { |
|
662 | if (IPython.save_widget.test_notebook_name()) { | |
660 | var notebook_id = IPython.save_widget.get_notebook_id(); |
|
663 | var notebook_id = IPython.save_widget.get_notebook_id(); | |
661 | var nbname = IPython.save_widget.get_notebook_name(); |
|
664 | var nbname = IPython.save_widget.get_notebook_name(); | |
662 | // We may want to move the name/id/nbformat logic inside toJSON? |
|
665 | // We may want to move the name/id/nbformat logic inside toJSON? | |
663 | var data = this.toJSON(); |
|
666 | var data = this.toJSON(); | |
664 | data.name = nbname; |
|
667 | data.name = nbname; | |
665 | data.nbformat = 2; |
|
668 | data.nbformat = 2; | |
666 | data.id = notebook_id |
|
669 | data.id = notebook_id | |
667 | // We do the call with settings so we can set cache to false. |
|
670 | // We do the call with settings so we can set cache to false. | |
668 | var settings = { |
|
671 | var settings = { | |
669 | processData : false, |
|
672 | processData : false, | |
670 | cache : false, |
|
673 | cache : false, | |
671 | type : "PUT", |
|
674 | type : "PUT", | |
672 | data : JSON.stringify(data), |
|
675 | data : JSON.stringify(data), | |
673 | headers : {'Content-Type': 'application/json'}, |
|
676 | headers : {'Content-Type': 'application/json'}, | |
674 | success : $.proxy(this.notebook_saved,this) |
|
677 | success : $.proxy(this.notebook_saved,this) | |
675 | }; |
|
678 | }; | |
676 | IPython.save_widget.status_saving(); |
|
679 | IPython.save_widget.status_saving(); | |
677 | $.ajax("/notebooks/" + notebook_id, settings); |
|
680 | $.ajax("/notebooks/" + notebook_id, settings); | |
678 | }; |
|
681 | }; | |
679 | }; |
|
682 | }; | |
680 |
|
683 | |||
681 |
|
684 | |||
682 | Notebook.prototype.notebook_saved = function (data, status, xhr) { |
|
685 | Notebook.prototype.notebook_saved = function (data, status, xhr) { | |
683 | IPython.save_widget.status_save(); |
|
686 | IPython.save_widget.status_save(); | |
684 | } |
|
687 | } | |
685 |
|
688 | |||
686 |
|
689 | |||
687 | Notebook.prototype.load_notebook = function (callback) { |
|
690 | Notebook.prototype.load_notebook = function (callback) { | |
688 | var that = this; |
|
691 | var that = this; | |
689 | var notebook_id = IPython.save_widget.get_notebook_id(); |
|
692 | var notebook_id = IPython.save_widget.get_notebook_id(); | |
690 | // We do the call with settings so we can set cache to false. |
|
693 | // We do the call with settings so we can set cache to false. | |
691 | var settings = { |
|
694 | var settings = { | |
692 | processData : false, |
|
695 | processData : false, | |
693 | cache : false, |
|
696 | cache : false, | |
694 | type : "GET", |
|
697 | type : "GET", | |
695 | dataType : "json", |
|
698 | dataType : "json", | |
696 | success : function (data, status, xhr) { |
|
699 | success : function (data, status, xhr) { | |
697 | that.notebook_loaded(data, status, xhr); |
|
700 | that.notebook_loaded(data, status, xhr); | |
698 | if (callback !== undefined) { |
|
701 | if (callback !== undefined) { | |
699 | callback(); |
|
702 | callback(); | |
700 | }; |
|
703 | }; | |
701 | } |
|
704 | } | |
702 | }; |
|
705 | }; | |
703 | IPython.save_widget.status_loading(); |
|
706 | IPython.save_widget.status_loading(); | |
704 | $.ajax("/notebooks/" + notebook_id, settings); |
|
707 | $.ajax("/notebooks/" + notebook_id, settings); | |
705 | } |
|
708 | } | |
706 |
|
709 | |||
707 |
|
710 | |||
708 | Notebook.prototype.notebook_loaded = function (data, status, xhr) { |
|
711 | Notebook.prototype.notebook_loaded = function (data, status, xhr) { | |
709 | this.fromJSON(data); |
|
712 | this.fromJSON(data); | |
710 | if (this.ncells() === 0) { |
|
713 | if (this.ncells() === 0) { | |
711 | this.insert_code_cell_after(); |
|
714 | this.insert_code_cell_after(); | |
712 | }; |
|
715 | }; | |
713 | IPython.save_widget.status_save(); |
|
716 | IPython.save_widget.status_save(); | |
714 | IPython.save_widget.set_notebook_name(data.name); |
|
717 | IPython.save_widget.set_notebook_name(data.name); | |
715 | this.start_kernel(); |
|
718 | this.start_kernel(); | |
716 | // fromJSON always selects the last cell inserted. We need to wait |
|
719 | // fromJSON always selects the last cell inserted. We need to wait | |
717 | // until that is done before scrolling to the top. |
|
720 | // until that is done before scrolling to the top. | |
718 | setTimeout(function () { |
|
721 | setTimeout(function () { | |
719 | IPython.notebook.select(0); |
|
722 | IPython.notebook.select(0); | |
720 | IPython.notebook.scroll_to_top(); |
|
723 | IPython.notebook.scroll_to_top(); | |
721 | }, 50); |
|
724 | }, 50); | |
722 | }; |
|
725 | }; | |
723 |
|
726 | |||
724 | IPython.Notebook = Notebook; |
|
727 | IPython.Notebook = Notebook; | |
725 |
|
728 | |||
726 | return IPython; |
|
729 | return IPython; | |
727 |
|
730 | |||
728 | }(IPython)); |
|
731 | }(IPython)); | |
729 |
|
732 |
@@ -1,106 +1,108 b'' | |||||
1 | """The basic dict based notebook format.""" |
|
1 | """The basic dict based notebook format.""" | |
2 |
|
2 | |||
3 | import pprint |
|
3 | import pprint | |
4 | import uuid |
|
4 | import uuid | |
5 |
|
5 | |||
6 | from IPython.utils.ipstruct import Struct |
|
6 | from IPython.utils.ipstruct import Struct | |
7 |
|
7 | |||
8 |
|
8 | |||
9 | class NotebookNode(Struct): |
|
9 | class NotebookNode(Struct): | |
10 | pass |
|
10 | pass | |
11 |
|
11 | |||
12 |
|
12 | |||
13 | def from_dict(d): |
|
13 | def from_dict(d): | |
14 | if isinstance(d, dict): |
|
14 | if isinstance(d, dict): | |
15 | newd = NotebookNode() |
|
15 | newd = NotebookNode() | |
16 | for k,v in d.items(): |
|
16 | for k,v in d.items(): | |
17 | newd[k] = from_dict(v) |
|
17 | newd[k] = from_dict(v) | |
18 | return newd |
|
18 | return newd | |
19 | elif isinstance(d, (tuple, list)): |
|
19 | elif isinstance(d, (tuple, list)): | |
20 | return [from_dict(i) for i in d] |
|
20 | return [from_dict(i) for i in d] | |
21 | else: |
|
21 | else: | |
22 | return d |
|
22 | return d | |
23 |
|
23 | |||
24 |
|
24 | |||
25 | def new_output(output_type=None, output_text=None, output_png=None, |
|
25 | def new_output(output_type=None, output_text=None, output_png=None, | |
26 | output_html=None, output_svg=None, output_latex=None, output_json=None, |
|
26 | output_html=None, output_svg=None, output_latex=None, output_json=None, | |
27 | output_javascript=None, prompt_number=None): |
|
27 | output_javascript=None, output_jpeg=None, prompt_number=None): | |
28 | """Create a new code cell with input and output""" |
|
28 | """Create a new code cell with input and output""" | |
29 | output = NotebookNode() |
|
29 | output = NotebookNode() | |
30 | if output_type is not None: |
|
30 | if output_type is not None: | |
31 | output.output_type = unicode(output_type) |
|
31 | output.output_type = unicode(output_type) | |
32 | if output_text is not None: |
|
32 | if output_text is not None: | |
33 | output.text = unicode(output_text) |
|
33 | output.text = unicode(output_text) | |
34 | if output_png is not None: |
|
34 | if output_png is not None: | |
35 | output.png = bytes(output_png) |
|
35 | output.png = bytes(output_png) | |
|
36 | if output_jpeg is not None: | |||
|
37 | output.jpeg = bytes(output_jpeg) | |||
36 | if output_html is not None: |
|
38 | if output_html is not None: | |
37 | output.html = unicode(output_html) |
|
39 | output.html = unicode(output_html) | |
38 | if output_svg is not None: |
|
40 | if output_svg is not None: | |
39 | output.svg = unicode(output_svg) |
|
41 | output.svg = unicode(output_svg) | |
40 | if output_latex is not None: |
|
42 | if output_latex is not None: | |
41 | output.latex = unicode(output_latex) |
|
43 | output.latex = unicode(output_latex) | |
42 | if output_json is not None: |
|
44 | if output_json is not None: | |
43 | output.json = unicode(output_json) |
|
45 | output.json = unicode(output_json) | |
44 | if output_javascript is not None: |
|
46 | if output_javascript is not None: | |
45 | output.javascript = unicode(output_javascript) |
|
47 | output.javascript = unicode(output_javascript) | |
46 | if prompt_number is not None: |
|
48 | if prompt_number is not None: | |
47 | output.prompt_number = int(prompt_number) |
|
49 | output.prompt_number = int(prompt_number) | |
48 | return output |
|
50 | return output | |
49 |
|
51 | |||
50 |
|
52 | |||
51 | def new_code_cell(input=None, prompt_number=None, outputs=None, language=u'python'): |
|
53 | def new_code_cell(input=None, prompt_number=None, outputs=None, language=u'python'): | |
52 | """Create a new code cell with input and output""" |
|
54 | """Create a new code cell with input and output""" | |
53 | cell = NotebookNode() |
|
55 | cell = NotebookNode() | |
54 | cell.cell_type = u'code' |
|
56 | cell.cell_type = u'code' | |
55 | if language is not None: |
|
57 | if language is not None: | |
56 | cell.language = unicode(language) |
|
58 | cell.language = unicode(language) | |
57 | if input is not None: |
|
59 | if input is not None: | |
58 | cell.input = unicode(input) |
|
60 | cell.input = unicode(input) | |
59 | if prompt_number is not None: |
|
61 | if prompt_number is not None: | |
60 | cell.prompt_number = int(prompt_number) |
|
62 | cell.prompt_number = int(prompt_number) | |
61 | if outputs is None: |
|
63 | if outputs is None: | |
62 | cell.outputs = [] |
|
64 | cell.outputs = [] | |
63 | else: |
|
65 | else: | |
64 | cell.outputs = outputs |
|
66 | cell.outputs = outputs | |
65 |
|
67 | |||
66 | return cell |
|
68 | return cell | |
67 |
|
69 | |||
68 | def new_text_cell(cell_type, source=None, rendered=None): |
|
70 | def new_text_cell(cell_type, source=None, rendered=None): | |
69 | """Create a new text cell.""" |
|
71 | """Create a new text cell.""" | |
70 | cell = NotebookNode() |
|
72 | cell = NotebookNode() | |
71 | if source is not None: |
|
73 | if source is not None: | |
72 | cell.source = unicode(source) |
|
74 | cell.source = unicode(source) | |
73 | if rendered is not None: |
|
75 | if rendered is not None: | |
74 | cell.rendered = unicode(rendered) |
|
76 | cell.rendered = unicode(rendered) | |
75 | cell.cell_type = cell_type |
|
77 | cell.cell_type = cell_type | |
76 | return cell |
|
78 | return cell | |
77 |
|
79 | |||
78 |
|
80 | |||
79 | def new_worksheet(name=None, cells=None): |
|
81 | def new_worksheet(name=None, cells=None): | |
80 | """Create a worksheet by name with with a list of cells.""" |
|
82 | """Create a worksheet by name with with a list of cells.""" | |
81 | ws = NotebookNode() |
|
83 | ws = NotebookNode() | |
82 | if name is not None: |
|
84 | if name is not None: | |
83 | ws.name = unicode(name) |
|
85 | ws.name = unicode(name) | |
84 | if cells is None: |
|
86 | if cells is None: | |
85 | ws.cells = [] |
|
87 | ws.cells = [] | |
86 | else: |
|
88 | else: | |
87 | ws.cells = list(cells) |
|
89 | ws.cells = list(cells) | |
88 | return ws |
|
90 | return ws | |
89 |
|
91 | |||
90 |
|
92 | |||
91 | def new_notebook(name=None, id=None, worksheets=None): |
|
93 | def new_notebook(name=None, id=None, worksheets=None): | |
92 | """Create a notebook by name, id and a list of worksheets.""" |
|
94 | """Create a notebook by name, id and a list of worksheets.""" | |
93 | nb = NotebookNode() |
|
95 | nb = NotebookNode() | |
94 | nb.nbformat = 2 |
|
96 | nb.nbformat = 2 | |
95 | if name is not None: |
|
97 | if name is not None: | |
96 | nb.name = unicode(name) |
|
98 | nb.name = unicode(name) | |
97 | if id is None: |
|
99 | if id is None: | |
98 | nb.id = unicode(uuid.uuid4()) |
|
100 | nb.id = unicode(uuid.uuid4()) | |
99 | else: |
|
101 | else: | |
100 | nb.id = unicode(id) |
|
102 | nb.id = unicode(id) | |
101 | if worksheets is None: |
|
103 | if worksheets is None: | |
102 | nb.worksheets = [] |
|
104 | nb.worksheets = [] | |
103 | else: |
|
105 | else: | |
104 | nb.worksheets = list(worksheets) |
|
106 | nb.worksheets = list(worksheets) | |
105 | return nb |
|
107 | return nb | |
106 |
|
108 |
@@ -1,178 +1,180 b'' | |||||
1 | """Read and write notebook files as XML.""" |
|
1 | """Read and write notebook files as XML.""" | |
2 |
|
2 | |||
3 | from base64 import encodestring, decodestring |
|
3 | from base64 import encodestring, decodestring | |
4 | from xml.etree import ElementTree as ET |
|
4 | from xml.etree import ElementTree as ET | |
5 |
|
5 | |||
6 | from .rwbase import NotebookReader, NotebookWriter |
|
6 | from .rwbase import NotebookReader, NotebookWriter | |
7 | from .nbbase import ( |
|
7 | from .nbbase import ( | |
8 | new_code_cell, new_text_cell, new_worksheet, new_notebook, new_output |
|
8 | new_code_cell, new_text_cell, new_worksheet, new_notebook, new_output | |
9 | ) |
|
9 | ) | |
10 |
|
10 | |||
11 | def indent(elem, level=0): |
|
11 | def indent(elem, level=0): | |
12 | i = "\n" + level*" " |
|
12 | i = "\n" + level*" " | |
13 | if len(elem): |
|
13 | if len(elem): | |
14 | if not elem.text or not elem.text.strip(): |
|
14 | if not elem.text or not elem.text.strip(): | |
15 | elem.text = i + " " |
|
15 | elem.text = i + " " | |
16 | if not elem.tail or not elem.tail.strip(): |
|
16 | if not elem.tail or not elem.tail.strip(): | |
17 | elem.tail = i |
|
17 | elem.tail = i | |
18 | for elem in elem: |
|
18 | for elem in elem: | |
19 | indent(elem, level+1) |
|
19 | indent(elem, level+1) | |
20 | if not elem.tail or not elem.tail.strip(): |
|
20 | if not elem.tail or not elem.tail.strip(): | |
21 | elem.tail = i |
|
21 | elem.tail = i | |
22 | else: |
|
22 | else: | |
23 | if level and (not elem.tail or not elem.tail.strip()): |
|
23 | if level and (not elem.tail or not elem.tail.strip()): | |
24 | elem.tail = i |
|
24 | elem.tail = i | |
25 |
|
25 | |||
26 |
|
26 | |||
27 | def _get_text(e, tag): |
|
27 | def _get_text(e, tag): | |
28 | sub_e = e.find(tag) |
|
28 | sub_e = e.find(tag) | |
29 | if sub_e is None: |
|
29 | if sub_e is None: | |
30 | return None |
|
30 | return None | |
31 | else: |
|
31 | else: | |
32 | return sub_e.text |
|
32 | return sub_e.text | |
33 |
|
33 | |||
34 |
|
34 | |||
35 | def _set_text(nbnode, attr, parent, tag): |
|
35 | def _set_text(nbnode, attr, parent, tag): | |
36 | if attr in nbnode: |
|
36 | if attr in nbnode: | |
37 | e = ET.SubElement(parent, tag) |
|
37 | e = ET.SubElement(parent, tag) | |
38 | e.text = nbnode[attr] |
|
38 | e.text = nbnode[attr] | |
39 |
|
39 | |||
40 |
|
40 | |||
41 | def _get_int(e, tag): |
|
41 | def _get_int(e, tag): | |
42 | sub_e = e.find(tag) |
|
42 | sub_e = e.find(tag) | |
43 | if sub_e is None: |
|
43 | if sub_e is None: | |
44 | return None |
|
44 | return None | |
45 | else: |
|
45 | else: | |
46 | return int(sub_e.text) |
|
46 | return int(sub_e.text) | |
47 |
|
47 | |||
48 |
|
48 | |||
49 | def _set_int(nbnode, attr, parent, tag): |
|
49 | def _set_int(nbnode, attr, parent, tag): | |
50 | if attr in nbnode: |
|
50 | if attr in nbnode: | |
51 | e = ET.SubElement(parent, tag) |
|
51 | e = ET.SubElement(parent, tag) | |
52 | e.text = unicode(nbnode[attr]) |
|
52 | e.text = unicode(nbnode[attr]) | |
53 |
|
53 | |||
54 |
|
54 | |||
55 | def _get_binary(e, tag): |
|
55 | def _get_binary(e, tag): | |
56 | sub_e = e.find(tag) |
|
56 | sub_e = e.find(tag) | |
57 | if sub_e is None: |
|
57 | if sub_e is None: | |
58 | return None |
|
58 | return None | |
59 | else: |
|
59 | else: | |
60 | return decodestring(sub_e.text) |
|
60 | return decodestring(sub_e.text) | |
61 |
|
61 | |||
62 |
|
62 | |||
63 | def _set_binary(nbnode, attr, parent, tag): |
|
63 | def _set_binary(nbnode, attr, parent, tag): | |
64 | if attr in nbnode: |
|
64 | if attr in nbnode: | |
65 | e = ET.SubElement(parent, tag) |
|
65 | e = ET.SubElement(parent, tag) | |
66 | e.text = encodestring(nbnode[attr]) |
|
66 | e.text = encodestring(nbnode[attr]) | |
67 |
|
67 | |||
68 |
|
68 | |||
69 | class XMLReader(NotebookReader): |
|
69 | class XMLReader(NotebookReader): | |
70 |
|
70 | |||
71 | def reads(self, s, **kwargs): |
|
71 | def reads(self, s, **kwargs): | |
72 | root = ET.fromstring(s) |
|
72 | root = ET.fromstring(s) | |
73 | return self.to_notebook(root, **kwargs) |
|
73 | return self.to_notebook(root, **kwargs) | |
74 |
|
74 | |||
75 | def to_notebook(self, root, **kwargs): |
|
75 | def to_notebook(self, root, **kwargs): | |
76 | nbname = _get_text(root,'name') |
|
76 | nbname = _get_text(root,'name') | |
77 | nbid = _get_text(root,'id') |
|
77 | nbid = _get_text(root,'id') | |
78 |
|
78 | |||
79 | worksheets = [] |
|
79 | worksheets = [] | |
80 | for ws_e in root.find('worksheets').getiterator('worksheet'): |
|
80 | for ws_e in root.find('worksheets').getiterator('worksheet'): | |
81 | wsname = _get_text(ws_e,'name') |
|
81 | wsname = _get_text(ws_e,'name') | |
82 | cells = [] |
|
82 | cells = [] | |
83 | for cell_e in ws_e.find('cells').getiterator(): |
|
83 | for cell_e in ws_e.find('cells').getiterator(): | |
84 | if cell_e.tag == 'codecell': |
|
84 | if cell_e.tag == 'codecell': | |
85 | input = _get_text(cell_e,'input') |
|
85 | input = _get_text(cell_e,'input') | |
86 | prompt_number = _get_int(cell_e,'prompt_number') |
|
86 | prompt_number = _get_int(cell_e,'prompt_number') | |
87 | language = _get_text(cell_e,'language') |
|
87 | language = _get_text(cell_e,'language') | |
88 | outputs = [] |
|
88 | outputs = [] | |
89 | for output_e in cell_e.find('outputs').getiterator('output'): |
|
89 | for output_e in cell_e.find('outputs').getiterator('output'): | |
90 | out_prompt_number = _get_int(output_e,'prompt_number') |
|
90 | out_prompt_number = _get_int(output_e,'prompt_number') | |
91 | output_type = _get_text(output_e,'output_type') |
|
91 | output_type = _get_text(output_e,'output_type') | |
92 | output_text = _get_text(output_e,'text') |
|
92 | output_text = _get_text(output_e,'text') | |
93 | output_png = _get_binary(output_e,'png') |
|
93 | output_png = _get_binary(output_e,'png') | |
|
94 | output_jpeg = _get_binary(output_e,'jpeg') | |||
94 | output_svg = _get_text(output_e,'svg') |
|
95 | output_svg = _get_text(output_e,'svg') | |
95 | output_html = _get_text(output_e,'html') |
|
96 | output_html = _get_text(output_e,'html') | |
96 | output_latex = _get_text(output_e,'latex') |
|
97 | output_latex = _get_text(output_e,'latex') | |
97 | output_json = _get_text(output_e,'json') |
|
98 | output_json = _get_text(output_e,'json') | |
98 | output_javascript = _get_text(output_e,'javascript') |
|
99 | output_javascript = _get_text(output_e,'javascript') | |
99 | output = new_output(output_type=output_type,output_png=output_png, |
|
100 | output = new_output(output_type=output_type,output_png=output_png, | |
100 | output_text=output_text,output_svg=output_svg, |
|
101 | output_text=output_text, output_svg=output_svg, | |
101 | output_html=output_html,output_latex=output_latex, |
|
102 | output_html=output_html, output_latex=output_latex, | |
102 | output_json=output_json,output_javascript=output_javascript, |
|
103 | output_json=output_json, output_javascript=output_javascript, | |
103 | prompt_number=out_prompt_number |
|
104 | output_jpeg=output_jpeg, prompt_number=out_prompt_number | |
104 | ) |
|
105 | ) | |
105 | outputs.append(output) |
|
106 | outputs.append(output) | |
106 | cc = new_code_cell(input=input,prompt_number=prompt_number, |
|
107 | cc = new_code_cell(input=input,prompt_number=prompt_number, | |
107 | language=language,outputs=outputs) |
|
108 | language=language,outputs=outputs) | |
108 | cells.append(cc) |
|
109 | cells.append(cc) | |
109 | if cell_e.tag == 'htmlcell': |
|
110 | if cell_e.tag == 'htmlcell': | |
110 | source = _get_text(cell_e,'source') |
|
111 | source = _get_text(cell_e,'source') | |
111 | rendered = _get_text(cell_e,'rendered') |
|
112 | rendered = _get_text(cell_e,'rendered') | |
112 | cells.append(new_text_cell(u'html', source=source, rendered=rendered)) |
|
113 | cells.append(new_text_cell(u'html', source=source, rendered=rendered)) | |
113 | if cell_e.tag == 'markdowncell': |
|
114 | if cell_e.tag == 'markdowncell': | |
114 | source = _get_text(cell_e,'source') |
|
115 | source = _get_text(cell_e,'source') | |
115 | rendered = _get_text(cell_e,'rendered') |
|
116 | rendered = _get_text(cell_e,'rendered') | |
116 | cells.append(new_text_cell(u'markdown', source=source, rendered=rendered)) |
|
117 | cells.append(new_text_cell(u'markdown', source=source, rendered=rendered)) | |
117 | ws = new_worksheet(name=wsname,cells=cells) |
|
118 | ws = new_worksheet(name=wsname,cells=cells) | |
118 | worksheets.append(ws) |
|
119 | worksheets.append(ws) | |
119 |
|
120 | |||
120 | nb = new_notebook(name=nbname,id=nbid,worksheets=worksheets) |
|
121 | nb = new_notebook(name=nbname,id=nbid,worksheets=worksheets) | |
121 | return nb |
|
122 | return nb | |
122 |
|
123 | |||
123 |
|
124 | |||
124 | class XMLWriter(NotebookWriter): |
|
125 | class XMLWriter(NotebookWriter): | |
125 |
|
126 | |||
126 | def writes(self, nb, **kwargs): |
|
127 | def writes(self, nb, **kwargs): | |
127 | nb_e = ET.Element('notebook') |
|
128 | nb_e = ET.Element('notebook') | |
128 | _set_text(nb,'name',nb_e,'name') |
|
129 | _set_text(nb,'name',nb_e,'name') | |
129 | _set_text(nb,'id',nb_e,'id') |
|
130 | _set_text(nb,'id',nb_e,'id') | |
130 | _set_int(nb,'nbformat',nb_e,'nbformat') |
|
131 | _set_int(nb,'nbformat',nb_e,'nbformat') | |
131 | wss_e = ET.SubElement(nb_e,'worksheets') |
|
132 | wss_e = ET.SubElement(nb_e,'worksheets') | |
132 | for ws in nb.worksheets: |
|
133 | for ws in nb.worksheets: | |
133 | ws_e = ET.SubElement(wss_e, 'worksheet') |
|
134 | ws_e = ET.SubElement(wss_e, 'worksheet') | |
134 | _set_text(ws,'name',ws_e,'name') |
|
135 | _set_text(ws,'name',ws_e,'name') | |
135 | cells_e = ET.SubElement(ws_e,'cells') |
|
136 | cells_e = ET.SubElement(ws_e,'cells') | |
136 | for cell in ws.cells: |
|
137 | for cell in ws.cells: | |
137 | cell_type = cell.cell_type |
|
138 | cell_type = cell.cell_type | |
138 | if cell_type == 'code': |
|
139 | if cell_type == 'code': | |
139 | cell_e = ET.SubElement(cells_e, 'codecell') |
|
140 | cell_e = ET.SubElement(cells_e, 'codecell') | |
140 | _set_text(cell,'input',cell_e,'input') |
|
141 | _set_text(cell,'input',cell_e,'input') | |
141 | _set_text(cell,'language',cell_e,'language') |
|
142 | _set_text(cell,'language',cell_e,'language') | |
142 | _set_int(cell,'prompt_number',cell_e,'prompt_number') |
|
143 | _set_int(cell,'prompt_number',cell_e,'prompt_number') | |
143 | outputs_e = ET.SubElement(cell_e, 'outputs') |
|
144 | outputs_e = ET.SubElement(cell_e, 'outputs') | |
144 | for output in cell.outputs: |
|
145 | for output in cell.outputs: | |
145 | output_e = ET.SubElement(outputs_e, 'output') |
|
146 | output_e = ET.SubElement(outputs_e, 'output') | |
146 | _set_int(output,'prompt_number',output_e,'prompt_number') |
|
147 | _set_int(output,'prompt_number',output_e,'prompt_number') | |
147 | _set_text(output,'output_type',output_e,'output_type') |
|
148 | _set_text(output,'output_type',output_e,'output_type') | |
148 | _set_text(output,'text',output_e,'text') |
|
149 | _set_text(output,'text',output_e,'text') | |
149 | _set_binary(output,'png',output_e,'png') |
|
150 | _set_binary(output,'png',output_e,'png') | |
|
151 | _set_binary(output,'jpeg',output_e,'jpeg') | |||
150 | _set_text(output,'html',output_e,'html') |
|
152 | _set_text(output,'html',output_e,'html') | |
151 | _set_text(output,'svg',output_e,'svg') |
|
153 | _set_text(output,'svg',output_e,'svg') | |
152 | _set_text(output,'latex',output_e,'latex') |
|
154 | _set_text(output,'latex',output_e,'latex') | |
153 | _set_text(output,'json',output_e,'json') |
|
155 | _set_text(output,'json',output_e,'json') | |
154 | _set_text(output,'javascript',output_e,'javascript') |
|
156 | _set_text(output,'javascript',output_e,'javascript') | |
155 | elif cell_type == 'html': |
|
157 | elif cell_type == 'html': | |
156 | cell_e = ET.SubElement(cells_e, 'htmlcell') |
|
158 | cell_e = ET.SubElement(cells_e, 'htmlcell') | |
157 | _set_text(cell,'source',cell_e,'source') |
|
159 | _set_text(cell,'source',cell_e,'source') | |
158 | _set_text(cell,'rendered',cell_e,'rendered') |
|
160 | _set_text(cell,'rendered',cell_e,'rendered') | |
159 | elif cell_type == 'markdown': |
|
161 | elif cell_type == 'markdown': | |
160 | cell_e = ET.SubElement(cells_e, 'markdowncell') |
|
162 | cell_e = ET.SubElement(cells_e, 'markdowncell') | |
161 | _set_text(cell,'source',cell_e,'source') |
|
163 | _set_text(cell,'source',cell_e,'source') | |
162 | _set_text(cell,'rendered',cell_e,'rendered') |
|
164 | _set_text(cell,'rendered',cell_e,'rendered') | |
163 |
|
165 | |||
164 | indent(nb_e) |
|
166 | indent(nb_e) | |
165 | txt = ET.tostring(nb_e, encoding="utf-8") |
|
167 | txt = ET.tostring(nb_e, encoding="utf-8") | |
166 | txt = '<?xml version="1.0" encoding="utf-8"?>\n' + txt |
|
168 | txt = '<?xml version="1.0" encoding="utf-8"?>\n' + txt | |
167 | return txt |
|
169 | return txt | |
168 |
|
170 | |||
169 |
|
171 | |||
170 | _reader = XMLReader() |
|
172 | _reader = XMLReader() | |
171 | _writer = XMLWriter() |
|
173 | _writer = XMLWriter() | |
172 |
|
174 | |||
173 | reads = _reader.reads |
|
175 | reads = _reader.reads | |
174 | read = _reader.read |
|
176 | read = _reader.read | |
175 | to_notebook = _reader.to_notebook |
|
177 | to_notebook = _reader.to_notebook | |
176 | write = _writer.write |
|
178 | write = _writer.write | |
177 | writes = _writer.writes |
|
179 | writes = _writer.writes | |
178 |
|
180 |
@@ -1,46 +1,50 b'' | |||||
1 | from base64 import encodestring, decodestring |
|
1 | from base64 import encodestring, decodestring | |
2 | import pprint |
|
2 | import pprint | |
3 |
|
3 | |||
4 | def base64_decode(nb): |
|
4 | def base64_decode(nb): | |
5 | """Base64 encode all bytes objects in the notebook.""" |
|
5 | """Base64 encode all bytes objects in the notebook.""" | |
6 | for ws in nb.worksheets: |
|
6 | for ws in nb.worksheets: | |
7 | for cell in ws.cells: |
|
7 | for cell in ws.cells: | |
8 | if cell.cell_type == 'code': |
|
8 | if cell.cell_type == 'code': | |
9 | if 'png' in cell: |
|
9 | if 'png' in cell: | |
10 | cell.png = bytes(decodestring(cell.png)) |
|
10 | cell.png = bytes(decodestring(cell.png)) | |
|
11 | if 'jpeg' in cell: | |||
|
12 | cell.jpeg = bytes(decodestring(cell.jpeg)) | |||
11 | return nb |
|
13 | return nb | |
12 |
|
14 | |||
13 |
|
15 | |||
14 | def base64_encode(nb): |
|
16 | def base64_encode(nb): | |
15 | """Base64 decode all binary objects in the notebook.""" |
|
17 | """Base64 decode all binary objects in the notebook.""" | |
16 | for ws in nb.worksheets: |
|
18 | for ws in nb.worksheets: | |
17 | for cell in ws.cells: |
|
19 | for cell in ws.cells: | |
18 | if cell.cell_type == 'code': |
|
20 | if cell.cell_type == 'code': | |
19 | if 'png' in cell: |
|
21 | if 'png' in cell: | |
20 | cell.png = unicode(encodestring(cell.png)) |
|
22 | cell.png = unicode(encodestring(cell.png)) | |
|
23 | if 'jpeg' in cell: | |||
|
24 | cell.jpeg = unicode(encodestring(cell.jpeg)) | |||
21 | return nb |
|
25 | return nb | |
22 |
|
26 | |||
23 |
|
27 | |||
24 | class NotebookReader(object): |
|
28 | class NotebookReader(object): | |
25 |
|
29 | |||
26 | def reads(self, s, **kwargs): |
|
30 | def reads(self, s, **kwargs): | |
27 | """Read a notebook from a string.""" |
|
31 | """Read a notebook from a string.""" | |
28 | raise NotImplementedError("loads must be implemented in a subclass") |
|
32 | raise NotImplementedError("loads must be implemented in a subclass") | |
29 |
|
33 | |||
30 | def read(self, fp, **kwargs): |
|
34 | def read(self, fp, **kwargs): | |
31 | """Read a notebook from a file like object""" |
|
35 | """Read a notebook from a file like object""" | |
32 | return self.read(fp.read(), **kwargs) |
|
36 | return self.read(fp.read(), **kwargs) | |
33 |
|
37 | |||
34 |
|
38 | |||
35 | class NotebookWriter(object): |
|
39 | class NotebookWriter(object): | |
36 |
|
40 | |||
37 | def writes(self, nb, **kwargs): |
|
41 | def writes(self, nb, **kwargs): | |
38 | """Write a notebook to a string.""" |
|
42 | """Write a notebook to a string.""" | |
39 | raise NotImplementedError("loads must be implemented in a subclass") |
|
43 | raise NotImplementedError("loads must be implemented in a subclass") | |
40 |
|
44 | |||
41 | def write(self, nb, fp, **kwargs): |
|
45 | def write(self, nb, fp, **kwargs): | |
42 | """Write a notebook to a file like object""" |
|
46 | """Write a notebook to a file like object""" | |
43 | return fp.write(self.writes(nb,**kwargs)) |
|
47 | return fp.write(self.writes(nb,**kwargs)) | |
44 |
|
48 | |||
45 |
|
49 | |||
46 |
|
50 |
@@ -1,83 +1,85 b'' | |||||
1 | from ..nbbase import ( |
|
1 | from ..nbbase import ( | |
2 | NotebookNode, |
|
2 | NotebookNode, | |
3 | new_code_cell, new_text_cell, new_worksheet, new_notebook, new_output |
|
3 | new_code_cell, new_text_cell, new_worksheet, new_notebook, new_output | |
4 | ) |
|
4 | ) | |
5 |
|
5 | |||
6 |
|
6 | |||
7 |
|
7 | |||
8 | ws = new_worksheet(name='worksheet1') |
|
8 | ws = new_worksheet(name='worksheet1') | |
9 |
|
9 | |||
10 | ws.cells.append(new_text_cell( |
|
10 | ws.cells.append(new_text_cell( | |
11 | u'html', |
|
11 | u'html', | |
12 | source='Some NumPy Examples', |
|
12 | source='Some NumPy Examples', | |
13 | rendered='Some NumPy Examples' |
|
13 | rendered='Some NumPy Examples' | |
14 | )) |
|
14 | )) | |
15 |
|
15 | |||
16 |
|
16 | |||
17 | ws.cells.append(new_code_cell( |
|
17 | ws.cells.append(new_code_cell( | |
18 | input='import numpy', |
|
18 | input='import numpy', | |
19 | prompt_number=1 |
|
19 | prompt_number=1 | |
20 | )) |
|
20 | )) | |
21 |
|
21 | |||
22 | ws.cells.append(new_text_cell( |
|
22 | ws.cells.append(new_text_cell( | |
23 | u'markdown', |
|
23 | u'markdown', | |
24 | source='Some NumPy Examples', |
|
24 | source='Some NumPy Examples', | |
25 | rendered='Some NumPy Examples' |
|
25 | rendered='Some NumPy Examples' | |
26 | )) |
|
26 | )) | |
27 |
|
27 | |||
28 | ws.cells.append(new_code_cell( |
|
28 | ws.cells.append(new_code_cell( | |
29 | input='a = numpy.random.rand(100)', |
|
29 | input='a = numpy.random.rand(100)', | |
30 | prompt_number=2 |
|
30 | prompt_number=2 | |
31 | )) |
|
31 | )) | |
32 |
|
32 | |||
33 | ws.cells.append(new_code_cell( |
|
33 | ws.cells.append(new_code_cell( | |
34 | input='print a', |
|
34 | input='print a', | |
35 | prompt_number=3, |
|
35 | prompt_number=3, | |
36 | outputs=[new_output( |
|
36 | outputs=[new_output( | |
37 | output_type=u'pyout', |
|
37 | output_type=u'pyout', | |
38 | output_text=u'<array a>', |
|
38 | output_text=u'<array a>', | |
39 | output_html=u'The HTML rep', |
|
39 | output_html=u'The HTML rep', | |
40 | output_latex=u'$a$', |
|
40 | output_latex=u'$a$', | |
41 | output_png=b'data', |
|
41 | output_png=b'data', | |
|
42 | output_jpeg=b'data', | |||
42 | output_svg=u'<svg>', |
|
43 | output_svg=u'<svg>', | |
43 | output_json=u'json data', |
|
44 | output_json=u'json data', | |
44 | output_javascript=u'var i=0;', |
|
45 | output_javascript=u'var i=0;', | |
45 | prompt_number=3 |
|
46 | prompt_number=3 | |
46 | ),new_output( |
|
47 | ),new_output( | |
47 | output_type=u'display_data', |
|
48 | output_type=u'display_data', | |
48 | output_text=u'<array a>', |
|
49 | output_text=u'<array a>', | |
49 | output_html=u'The HTML rep', |
|
50 | output_html=u'The HTML rep', | |
50 | output_latex=u'$a$', |
|
51 | output_latex=u'$a$', | |
51 | output_png=b'data', |
|
52 | output_png=b'data', | |
|
53 | output_jpeg=b'data', | |||
52 | output_svg=u'<svg>', |
|
54 | output_svg=u'<svg>', | |
53 | output_json=u'json data', |
|
55 | output_json=u'json data', | |
54 | output_javascript=u'var i=0;', |
|
56 | output_javascript=u'var i=0;', | |
55 | prompt_number=4 |
|
57 | prompt_number=4 | |
56 | )] |
|
58 | )] | |
57 | )) |
|
59 | )) | |
58 |
|
60 | |||
59 | nb0 = new_notebook( |
|
61 | nb0 = new_notebook( | |
60 | name='nb0', |
|
62 | name='nb0', | |
61 | worksheets=[ws, new_worksheet(name='worksheet2')] |
|
63 | worksheets=[ws, new_worksheet(name='worksheet2')] | |
62 | ) |
|
64 | ) | |
63 |
|
65 | |||
64 | nb0_py = """# <nbformat>2</nbformat> |
|
66 | nb0_py = """# <nbformat>2</nbformat> | |
65 |
|
67 | |||
66 | # <codecell> |
|
68 | # <codecell> | |
67 |
|
69 | |||
68 | import numpy |
|
70 | import numpy | |
69 |
|
71 | |||
70 | # </codecell> |
|
72 | # </codecell> | |
71 | # <codecell> |
|
73 | # <codecell> | |
72 |
|
74 | |||
73 | a = numpy.random.rand(100) |
|
75 | a = numpy.random.rand(100) | |
74 |
|
76 | |||
75 | # </codecell> |
|
77 | # </codecell> | |
76 | # <codecell> |
|
78 | # <codecell> | |
77 |
|
79 | |||
78 | print a |
|
80 | print a | |
79 |
|
81 | |||
80 | # </codecell> |
|
82 | # </codecell> | |
81 | """ |
|
83 | """ | |
82 |
|
84 | |||
83 |
|
85 |
@@ -1,64 +1,68 b'' | |||||
1 | import __builtin__ |
|
1 | import __builtin__ | |
2 | from base64 import encodestring |
|
2 | from base64 import encodestring | |
3 |
|
3 | |||
4 | from IPython.core.displayhook import DisplayHook |
|
4 | from IPython.core.displayhook import DisplayHook | |
5 | from IPython.utils.traitlets import Instance, Dict |
|
5 | from IPython.utils.traitlets import Instance, Dict | |
6 | from session import extract_header, Session |
|
6 | from session import extract_header, Session | |
7 |
|
7 | |||
8 | class ZMQDisplayHook(object): |
|
8 | class ZMQDisplayHook(object): | |
9 | """A simple displayhook that publishes the object's repr over a ZeroMQ |
|
9 | """A simple displayhook that publishes the object's repr over a ZeroMQ | |
10 | socket.""" |
|
10 | socket.""" | |
11 | topic=None |
|
11 | topic=None | |
12 |
|
12 | |||
13 | def __init__(self, session, pub_socket): |
|
13 | def __init__(self, session, pub_socket): | |
14 | self.session = session |
|
14 | self.session = session | |
15 | self.pub_socket = pub_socket |
|
15 | self.pub_socket = pub_socket | |
16 | self.parent_header = {} |
|
16 | self.parent_header = {} | |
17 |
|
17 | |||
18 | def __call__(self, obj): |
|
18 | def __call__(self, obj): | |
19 | if obj is None: |
|
19 | if obj is None: | |
20 | return |
|
20 | return | |
21 |
|
21 | |||
22 | __builtin__._ = obj |
|
22 | __builtin__._ = obj | |
23 | msg = self.session.send(self.pub_socket, u'pyout', {u'data':repr(obj)}, |
|
23 | msg = self.session.send(self.pub_socket, u'pyout', {u'data':repr(obj)}, | |
24 | parent=self.parent_header, ident=self.topic) |
|
24 | parent=self.parent_header, ident=self.topic) | |
25 |
|
25 | |||
26 | def set_parent(self, parent): |
|
26 | def set_parent(self, parent): | |
27 | self.parent_header = extract_header(parent) |
|
27 | self.parent_header = extract_header(parent) | |
28 |
|
28 | |||
29 |
|
29 | |||
30 |
def _encode_ |
|
30 | def _encode_binary(format_dict): | |
31 |
pngdata = |
|
31 | pngdata = format_dict.get('image/png') | |
32 | if pngdata is not None: |
|
32 | if pngdata is not None: | |
33 |
|
|
33 | format_dict['image/png'] = encodestring(pngdata) | |
|
34 | jpegdata = format_dict.get('image/jpeg') | |||
|
35 | if jpegdata is not None: | |||
|
36 | format_dict['image/jpeg'] = encodestring(jpegdata) | |||
|
37 | ||||
34 |
|
38 | |||
35 | class ZMQShellDisplayHook(DisplayHook): |
|
39 | class ZMQShellDisplayHook(DisplayHook): | |
36 | """A displayhook subclass that publishes data using ZeroMQ. This is intended |
|
40 | """A displayhook subclass that publishes data using ZeroMQ. This is intended | |
37 | to work with an InteractiveShell instance. It sends a dict of different |
|
41 | to work with an InteractiveShell instance. It sends a dict of different | |
38 | representations of the object.""" |
|
42 | representations of the object.""" | |
39 |
|
43 | |||
40 | session = Instance(Session) |
|
44 | session = Instance(Session) | |
41 | pub_socket = Instance('zmq.Socket') |
|
45 | pub_socket = Instance('zmq.Socket') | |
42 | parent_header = Dict({}) |
|
46 | parent_header = Dict({}) | |
43 |
|
47 | |||
44 | def set_parent(self, parent): |
|
48 | def set_parent(self, parent): | |
45 | """Set the parent for outbound messages.""" |
|
49 | """Set the parent for outbound messages.""" | |
46 | self.parent_header = extract_header(parent) |
|
50 | self.parent_header = extract_header(parent) | |
47 |
|
51 | |||
48 | def start_displayhook(self): |
|
52 | def start_displayhook(self): | |
49 | self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header) |
|
53 | self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header) | |
50 |
|
54 | |||
51 | def write_output_prompt(self): |
|
55 | def write_output_prompt(self): | |
52 | """Write the output prompt.""" |
|
56 | """Write the output prompt.""" | |
53 | if self.do_full_cache: |
|
57 | if self.do_full_cache: | |
54 | self.msg['content']['execution_count'] = self.prompt_count |
|
58 | self.msg['content']['execution_count'] = self.prompt_count | |
55 |
|
59 | |||
56 | def write_format_data(self, format_dict): |
|
60 | def write_format_data(self, format_dict): | |
57 | pngdata = format_dict.get('image/png') |
|
61 | _encode_binary(format_dict) | |
58 | _encode_png(format_dict) |
|
|||
59 | self.msg['content']['data'] = format_dict |
|
62 | self.msg['content']['data'] = format_dict | |
60 |
|
63 | |||
61 | def finish_displayhook(self): |
|
64 | def finish_displayhook(self): | |
62 | """Finish up all displayhook activities.""" |
|
65 | """Finish up all displayhook activities.""" | |
63 | self.session.send(self.pub_socket, self.msg) |
|
66 | self.session.send(self.pub_socket, self.msg) | |
64 | self.msg = None |
|
67 | self.msg = None | |
|
68 |
@@ -1,457 +1,457 b'' | |||||
1 | """A ZMQ-based subclass of InteractiveShell. |
|
1 | """A ZMQ-based subclass of InteractiveShell. | |
2 |
|
2 | |||
3 | This code is meant to ease the refactoring of the base InteractiveShell into |
|
3 | This code is meant to ease the refactoring of the base InteractiveShell into | |
4 | something with a cleaner architecture for 2-process use, without actually |
|
4 | something with a cleaner architecture for 2-process use, without actually | |
5 | breaking InteractiveShell itself. So we're doing something a bit ugly, where |
|
5 | breaking InteractiveShell itself. So we're doing something a bit ugly, where | |
6 | we subclass and override what we want to fix. Once this is working well, we |
|
6 | we subclass and override what we want to fix. Once this is working well, we | |
7 | can go back to the base class and refactor the code for a cleaner inheritance |
|
7 | can go back to the base class and refactor the code for a cleaner inheritance | |
8 | implementation that doesn't rely on so much monkeypatching. |
|
8 | implementation that doesn't rely on so much monkeypatching. | |
9 |
|
9 | |||
10 | But this lets us maintain a fully working IPython as we develop the new |
|
10 | But this lets us maintain a fully working IPython as we develop the new | |
11 | machinery. This should thus be thought of as scaffolding. |
|
11 | machinery. This should thus be thought of as scaffolding. | |
12 | """ |
|
12 | """ | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | from __future__ import print_function |
|
16 | from __future__ import print_function | |
17 |
|
17 | |||
18 | # Stdlib |
|
18 | # Stdlib | |
19 | import inspect |
|
19 | import inspect | |
20 | import os |
|
20 | import os | |
21 |
|
21 | |||
22 | # Our own |
|
22 | # Our own | |
23 | from IPython.core.interactiveshell import ( |
|
23 | from IPython.core.interactiveshell import ( | |
24 | InteractiveShell, InteractiveShellABC |
|
24 | InteractiveShell, InteractiveShellABC | |
25 | ) |
|
25 | ) | |
26 | from IPython.core import page |
|
26 | from IPython.core import page | |
27 | from IPython.core.autocall import ZMQExitAutocall |
|
27 | from IPython.core.autocall import ZMQExitAutocall | |
28 | from IPython.core.displaypub import DisplayPublisher |
|
28 | from IPython.core.displaypub import DisplayPublisher | |
29 | from IPython.core.macro import Macro |
|
29 | from IPython.core.macro import Macro | |
30 | from IPython.core.magic import MacroToEdit |
|
30 | from IPython.core.magic import MacroToEdit | |
31 | from IPython.core.payloadpage import install_payload_page |
|
31 | from IPython.core.payloadpage import install_payload_page | |
32 | from IPython.utils import io |
|
32 | from IPython.utils import io | |
33 | from IPython.utils.path import get_py_filename |
|
33 | from IPython.utils.path import get_py_filename | |
34 | from IPython.utils.traitlets import Instance, Type, Dict, CBool |
|
34 | from IPython.utils.traitlets import Instance, Type, Dict, CBool | |
35 | from IPython.utils.warn import warn |
|
35 | from IPython.utils.warn import warn | |
36 |
from IPython.zmq.displayhook import ZMQShellDisplayHook, _encode_ |
|
36 | from IPython.zmq.displayhook import ZMQShellDisplayHook, _encode_binary | |
37 | from IPython.zmq.session import extract_header |
|
37 | from IPython.zmq.session import extract_header | |
38 | from session import Session |
|
38 | from session import Session | |
39 |
|
39 | |||
40 | #----------------------------------------------------------------------------- |
|
40 | #----------------------------------------------------------------------------- | |
41 | # Globals and side-effects |
|
41 | # Globals and side-effects | |
42 | #----------------------------------------------------------------------------- |
|
42 | #----------------------------------------------------------------------------- | |
43 |
|
43 | |||
44 | # Install the payload version of page. |
|
44 | # Install the payload version of page. | |
45 | install_payload_page() |
|
45 | install_payload_page() | |
46 |
|
46 | |||
47 | #----------------------------------------------------------------------------- |
|
47 | #----------------------------------------------------------------------------- | |
48 | # Functions and classes |
|
48 | # Functions and classes | |
49 | #----------------------------------------------------------------------------- |
|
49 | #----------------------------------------------------------------------------- | |
50 |
|
50 | |||
51 | class ZMQDisplayPublisher(DisplayPublisher): |
|
51 | class ZMQDisplayPublisher(DisplayPublisher): | |
52 | """A display publisher that publishes data using a ZeroMQ PUB socket.""" |
|
52 | """A display publisher that publishes data using a ZeroMQ PUB socket.""" | |
53 |
|
53 | |||
54 | session = Instance(Session) |
|
54 | session = Instance(Session) | |
55 | pub_socket = Instance('zmq.Socket') |
|
55 | pub_socket = Instance('zmq.Socket') | |
56 | parent_header = Dict({}) |
|
56 | parent_header = Dict({}) | |
57 |
|
57 | |||
58 | def set_parent(self, parent): |
|
58 | def set_parent(self, parent): | |
59 | """Set the parent for outbound messages.""" |
|
59 | """Set the parent for outbound messages.""" | |
60 | self.parent_header = extract_header(parent) |
|
60 | self.parent_header = extract_header(parent) | |
61 |
|
61 | |||
62 | def publish(self, source, data, metadata=None): |
|
62 | def publish(self, source, data, metadata=None): | |
63 | if metadata is None: |
|
63 | if metadata is None: | |
64 | metadata = {} |
|
64 | metadata = {} | |
65 | self._validate_data(source, data, metadata) |
|
65 | self._validate_data(source, data, metadata) | |
66 | content = {} |
|
66 | content = {} | |
67 | content['source'] = source |
|
67 | content['source'] = source | |
68 |
_encode_ |
|
68 | _encode_binary(data) | |
69 | content['data'] = data |
|
69 | content['data'] = data | |
70 | content['metadata'] = metadata |
|
70 | content['metadata'] = metadata | |
71 | self.session.send( |
|
71 | self.session.send( | |
72 | self.pub_socket, u'display_data', content, |
|
72 | self.pub_socket, u'display_data', content, | |
73 | parent=self.parent_header |
|
73 | parent=self.parent_header | |
74 | ) |
|
74 | ) | |
75 |
|
75 | |||
76 |
|
76 | |||
77 | class ZMQInteractiveShell(InteractiveShell): |
|
77 | class ZMQInteractiveShell(InteractiveShell): | |
78 | """A subclass of InteractiveShell for ZMQ.""" |
|
78 | """A subclass of InteractiveShell for ZMQ.""" | |
79 |
|
79 | |||
80 | displayhook_class = Type(ZMQShellDisplayHook) |
|
80 | displayhook_class = Type(ZMQShellDisplayHook) | |
81 | display_pub_class = Type(ZMQDisplayPublisher) |
|
81 | display_pub_class = Type(ZMQDisplayPublisher) | |
82 |
|
82 | |||
83 | # Override the traitlet in the parent class, because there's no point using |
|
83 | # Override the traitlet in the parent class, because there's no point using | |
84 | # readline for the kernel. Can be removed when the readline code is moved |
|
84 | # readline for the kernel. Can be removed when the readline code is moved | |
85 | # to the terminal frontend. |
|
85 | # to the terminal frontend. | |
86 |
|
86 | |||
87 | # FIXME. This is disabled for now, even though it may cause problems under |
|
87 | # FIXME. This is disabled for now, even though it may cause problems under | |
88 | # Windows, because it breaks %run in the Qt console. See gh-617 for more |
|
88 | # Windows, because it breaks %run in the Qt console. See gh-617 for more | |
89 | # details. Re-enable once we've fully tested that %run works in the Qt |
|
89 | # details. Re-enable once we've fully tested that %run works in the Qt | |
90 | # console with syntax highlighting in tracebacks. |
|
90 | # console with syntax highlighting in tracebacks. | |
91 | # readline_use = CBool(False) |
|
91 | # readline_use = CBool(False) | |
92 | # /FIXME |
|
92 | # /FIXME | |
93 |
|
93 | |||
94 | exiter = Instance(ZMQExitAutocall) |
|
94 | exiter = Instance(ZMQExitAutocall) | |
95 | def _exiter_default(self): |
|
95 | def _exiter_default(self): | |
96 | return ZMQExitAutocall(self) |
|
96 | return ZMQExitAutocall(self) | |
97 |
|
97 | |||
98 | keepkernel_on_exit = None |
|
98 | keepkernel_on_exit = None | |
99 |
|
99 | |||
100 | def init_environment(self): |
|
100 | def init_environment(self): | |
101 | """Configure the user's environment. |
|
101 | """Configure the user's environment. | |
102 |
|
102 | |||
103 | """ |
|
103 | """ | |
104 | env = os.environ |
|
104 | env = os.environ | |
105 | # These two ensure 'ls' produces nice coloring on BSD-derived systems |
|
105 | # These two ensure 'ls' produces nice coloring on BSD-derived systems | |
106 | env['TERM'] = 'xterm-color' |
|
106 | env['TERM'] = 'xterm-color' | |
107 | env['CLICOLOR'] = '1' |
|
107 | env['CLICOLOR'] = '1' | |
108 | # Since normal pagers don't work at all (over pexpect we don't have |
|
108 | # Since normal pagers don't work at all (over pexpect we don't have | |
109 | # single-key control of the subprocess), try to disable paging in |
|
109 | # single-key control of the subprocess), try to disable paging in | |
110 | # subprocesses as much as possible. |
|
110 | # subprocesses as much as possible. | |
111 | env['PAGER'] = 'cat' |
|
111 | env['PAGER'] = 'cat' | |
112 | env['GIT_PAGER'] = 'cat' |
|
112 | env['GIT_PAGER'] = 'cat' | |
113 |
|
113 | |||
114 | def auto_rewrite_input(self, cmd): |
|
114 | def auto_rewrite_input(self, cmd): | |
115 | """Called to show the auto-rewritten input for autocall and friends. |
|
115 | """Called to show the auto-rewritten input for autocall and friends. | |
116 |
|
116 | |||
117 | FIXME: this payload is currently not correctly processed by the |
|
117 | FIXME: this payload is currently not correctly processed by the | |
118 | frontend. |
|
118 | frontend. | |
119 | """ |
|
119 | """ | |
120 | new = self.displayhook.prompt1.auto_rewrite() + cmd |
|
120 | new = self.displayhook.prompt1.auto_rewrite() + cmd | |
121 | payload = dict( |
|
121 | payload = dict( | |
122 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input', |
|
122 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input', | |
123 | transformed_input=new, |
|
123 | transformed_input=new, | |
124 | ) |
|
124 | ) | |
125 | self.payload_manager.write_payload(payload) |
|
125 | self.payload_manager.write_payload(payload) | |
126 |
|
126 | |||
127 | def ask_exit(self): |
|
127 | def ask_exit(self): | |
128 | """Engage the exit actions.""" |
|
128 | """Engage the exit actions.""" | |
129 | payload = dict( |
|
129 | payload = dict( | |
130 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit', |
|
130 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit', | |
131 | exit=True, |
|
131 | exit=True, | |
132 | keepkernel=self.keepkernel_on_exit, |
|
132 | keepkernel=self.keepkernel_on_exit, | |
133 | ) |
|
133 | ) | |
134 | self.payload_manager.write_payload(payload) |
|
134 | self.payload_manager.write_payload(payload) | |
135 |
|
135 | |||
136 | def _showtraceback(self, etype, evalue, stb): |
|
136 | def _showtraceback(self, etype, evalue, stb): | |
137 |
|
137 | |||
138 | exc_content = { |
|
138 | exc_content = { | |
139 | u'traceback' : stb, |
|
139 | u'traceback' : stb, | |
140 | u'ename' : unicode(etype.__name__), |
|
140 | u'ename' : unicode(etype.__name__), | |
141 | u'evalue' : unicode(evalue) |
|
141 | u'evalue' : unicode(evalue) | |
142 | } |
|
142 | } | |
143 |
|
143 | |||
144 | dh = self.displayhook |
|
144 | dh = self.displayhook | |
145 | # Send exception info over pub socket for other clients than the caller |
|
145 | # Send exception info over pub socket for other clients than the caller | |
146 | # to pick up |
|
146 | # to pick up | |
147 | exc_msg = dh.session.send(dh.pub_socket, u'pyerr', exc_content, dh.parent_header) |
|
147 | exc_msg = dh.session.send(dh.pub_socket, u'pyerr', exc_content, dh.parent_header) | |
148 |
|
148 | |||
149 | # FIXME - Hack: store exception info in shell object. Right now, the |
|
149 | # FIXME - Hack: store exception info in shell object. Right now, the | |
150 | # caller is reading this info after the fact, we need to fix this logic |
|
150 | # caller is reading this info after the fact, we need to fix this logic | |
151 | # to remove this hack. Even uglier, we need to store the error status |
|
151 | # to remove this hack. Even uglier, we need to store the error status | |
152 | # here, because in the main loop, the logic that sets it is being |
|
152 | # here, because in the main loop, the logic that sets it is being | |
153 | # skipped because runlines swallows the exceptions. |
|
153 | # skipped because runlines swallows the exceptions. | |
154 | exc_content[u'status'] = u'error' |
|
154 | exc_content[u'status'] = u'error' | |
155 | self._reply_content = exc_content |
|
155 | self._reply_content = exc_content | |
156 | # /FIXME |
|
156 | # /FIXME | |
157 |
|
157 | |||
158 | return exc_content |
|
158 | return exc_content | |
159 |
|
159 | |||
160 | #------------------------------------------------------------------------ |
|
160 | #------------------------------------------------------------------------ | |
161 | # Magic overrides |
|
161 | # Magic overrides | |
162 | #------------------------------------------------------------------------ |
|
162 | #------------------------------------------------------------------------ | |
163 | # Once the base class stops inheriting from magic, this code needs to be |
|
163 | # Once the base class stops inheriting from magic, this code needs to be | |
164 | # moved into a separate machinery as well. For now, at least isolate here |
|
164 | # moved into a separate machinery as well. For now, at least isolate here | |
165 | # the magics which this class needs to implement differently from the base |
|
165 | # the magics which this class needs to implement differently from the base | |
166 | # class, or that are unique to it. |
|
166 | # class, or that are unique to it. | |
167 |
|
167 | |||
168 | def magic_doctest_mode(self,parameter_s=''): |
|
168 | def magic_doctest_mode(self,parameter_s=''): | |
169 | """Toggle doctest mode on and off. |
|
169 | """Toggle doctest mode on and off. | |
170 |
|
170 | |||
171 | This mode is intended to make IPython behave as much as possible like a |
|
171 | This mode is intended to make IPython behave as much as possible like a | |
172 | plain Python shell, from the perspective of how its prompts, exceptions |
|
172 | plain Python shell, from the perspective of how its prompts, exceptions | |
173 | and output look. This makes it easy to copy and paste parts of a |
|
173 | and output look. This makes it easy to copy and paste parts of a | |
174 | session into doctests. It does so by: |
|
174 | session into doctests. It does so by: | |
175 |
|
175 | |||
176 | - Changing the prompts to the classic ``>>>`` ones. |
|
176 | - Changing the prompts to the classic ``>>>`` ones. | |
177 | - Changing the exception reporting mode to 'Plain'. |
|
177 | - Changing the exception reporting mode to 'Plain'. | |
178 | - Disabling pretty-printing of output. |
|
178 | - Disabling pretty-printing of output. | |
179 |
|
179 | |||
180 | Note that IPython also supports the pasting of code snippets that have |
|
180 | Note that IPython also supports the pasting of code snippets that have | |
181 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
181 | leading '>>>' and '...' prompts in them. This means that you can paste | |
182 | doctests from files or docstrings (even if they have leading |
|
182 | doctests from files or docstrings (even if they have leading | |
183 | whitespace), and the code will execute correctly. You can then use |
|
183 | whitespace), and the code will execute correctly. You can then use | |
184 | '%history -t' to see the translated history; this will give you the |
|
184 | '%history -t' to see the translated history; this will give you the | |
185 | input after removal of all the leading prompts and whitespace, which |
|
185 | input after removal of all the leading prompts and whitespace, which | |
186 | can be pasted back into an editor. |
|
186 | can be pasted back into an editor. | |
187 |
|
187 | |||
188 | With these features, you can switch into this mode easily whenever you |
|
188 | With these features, you can switch into this mode easily whenever you | |
189 | need to do testing and changes to doctests, without having to leave |
|
189 | need to do testing and changes to doctests, without having to leave | |
190 | your existing IPython session. |
|
190 | your existing IPython session. | |
191 | """ |
|
191 | """ | |
192 |
|
192 | |||
193 | from IPython.utils.ipstruct import Struct |
|
193 | from IPython.utils.ipstruct import Struct | |
194 |
|
194 | |||
195 | # Shorthands |
|
195 | # Shorthands | |
196 | shell = self.shell |
|
196 | shell = self.shell | |
197 | disp_formatter = self.shell.display_formatter |
|
197 | disp_formatter = self.shell.display_formatter | |
198 | ptformatter = disp_formatter.formatters['text/plain'] |
|
198 | ptformatter = disp_formatter.formatters['text/plain'] | |
199 | # dstore is a data store kept in the instance metadata bag to track any |
|
199 | # dstore is a data store kept in the instance metadata bag to track any | |
200 | # changes we make, so we can undo them later. |
|
200 | # changes we make, so we can undo them later. | |
201 | dstore = shell.meta.setdefault('doctest_mode', Struct()) |
|
201 | dstore = shell.meta.setdefault('doctest_mode', Struct()) | |
202 | save_dstore = dstore.setdefault |
|
202 | save_dstore = dstore.setdefault | |
203 |
|
203 | |||
204 | # save a few values we'll need to recover later |
|
204 | # save a few values we'll need to recover later | |
205 | mode = save_dstore('mode', False) |
|
205 | mode = save_dstore('mode', False) | |
206 | save_dstore('rc_pprint', ptformatter.pprint) |
|
206 | save_dstore('rc_pprint', ptformatter.pprint) | |
207 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) |
|
207 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) | |
208 | save_dstore('xmode', shell.InteractiveTB.mode) |
|
208 | save_dstore('xmode', shell.InteractiveTB.mode) | |
209 |
|
209 | |||
210 | if mode == False: |
|
210 | if mode == False: | |
211 | # turn on |
|
211 | # turn on | |
212 | ptformatter.pprint = False |
|
212 | ptformatter.pprint = False | |
213 | disp_formatter.plain_text_only = True |
|
213 | disp_formatter.plain_text_only = True | |
214 | shell.magic_xmode('Plain') |
|
214 | shell.magic_xmode('Plain') | |
215 | else: |
|
215 | else: | |
216 | # turn off |
|
216 | # turn off | |
217 | ptformatter.pprint = dstore.rc_pprint |
|
217 | ptformatter.pprint = dstore.rc_pprint | |
218 | disp_formatter.plain_text_only = dstore.rc_plain_text_only |
|
218 | disp_formatter.plain_text_only = dstore.rc_plain_text_only | |
219 | shell.magic_xmode(dstore.xmode) |
|
219 | shell.magic_xmode(dstore.xmode) | |
220 |
|
220 | |||
221 | # Store new mode and inform on console |
|
221 | # Store new mode and inform on console | |
222 | dstore.mode = bool(1-int(mode)) |
|
222 | dstore.mode = bool(1-int(mode)) | |
223 | mode_label = ['OFF','ON'][dstore.mode] |
|
223 | mode_label = ['OFF','ON'][dstore.mode] | |
224 | print('Doctest mode is:', mode_label) |
|
224 | print('Doctest mode is:', mode_label) | |
225 |
|
225 | |||
226 | # Send the payload back so that clients can modify their prompt display |
|
226 | # Send the payload back so that clients can modify their prompt display | |
227 | payload = dict( |
|
227 | payload = dict( | |
228 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode', |
|
228 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode', | |
229 | mode=dstore.mode) |
|
229 | mode=dstore.mode) | |
230 | self.payload_manager.write_payload(payload) |
|
230 | self.payload_manager.write_payload(payload) | |
231 |
|
231 | |||
232 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
232 | def magic_edit(self,parameter_s='',last_call=['','']): | |
233 | """Bring up an editor and execute the resulting code. |
|
233 | """Bring up an editor and execute the resulting code. | |
234 |
|
234 | |||
235 | Usage: |
|
235 | Usage: | |
236 | %edit [options] [args] |
|
236 | %edit [options] [args] | |
237 |
|
237 | |||
238 | %edit runs IPython's editor hook. The default version of this hook is |
|
238 | %edit runs IPython's editor hook. The default version of this hook is | |
239 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
239 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
240 | environment variable $EDITOR. If this isn't found, it will default to |
|
240 | environment variable $EDITOR. If this isn't found, it will default to | |
241 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
241 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
242 | docstring for how to change the editor hook. |
|
242 | docstring for how to change the editor hook. | |
243 |
|
243 | |||
244 | You can also set the value of this editor via the command line option |
|
244 | You can also set the value of this editor via the command line option | |
245 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
245 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
246 | specifically for IPython an editor different from your typical default |
|
246 | specifically for IPython an editor different from your typical default | |
247 | (and for Windows users who typically don't set environment variables). |
|
247 | (and for Windows users who typically don't set environment variables). | |
248 |
|
248 | |||
249 | This command allows you to conveniently edit multi-line code right in |
|
249 | This command allows you to conveniently edit multi-line code right in | |
250 | your IPython session. |
|
250 | your IPython session. | |
251 |
|
251 | |||
252 | If called without arguments, %edit opens up an empty editor with a |
|
252 | If called without arguments, %edit opens up an empty editor with a | |
253 | temporary file and will execute the contents of this file when you |
|
253 | temporary file and will execute the contents of this file when you | |
254 | close it (don't forget to save it!). |
|
254 | close it (don't forget to save it!). | |
255 |
|
255 | |||
256 |
|
256 | |||
257 | Options: |
|
257 | Options: | |
258 |
|
258 | |||
259 | -n <number>: open the editor at a specified line number. By default, |
|
259 | -n <number>: open the editor at a specified line number. By default, | |
260 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
260 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
261 | you can configure this by providing your own modified hook if your |
|
261 | you can configure this by providing your own modified hook if your | |
262 | favorite editor supports line-number specifications with a different |
|
262 | favorite editor supports line-number specifications with a different | |
263 | syntax. |
|
263 | syntax. | |
264 |
|
264 | |||
265 | -p: this will call the editor with the same data as the previous time |
|
265 | -p: this will call the editor with the same data as the previous time | |
266 | it was used, regardless of how long ago (in your current session) it |
|
266 | it was used, regardless of how long ago (in your current session) it | |
267 | was. |
|
267 | was. | |
268 |
|
268 | |||
269 | -r: use 'raw' input. This option only applies to input taken from the |
|
269 | -r: use 'raw' input. This option only applies to input taken from the | |
270 | user's history. By default, the 'processed' history is used, so that |
|
270 | user's history. By default, the 'processed' history is used, so that | |
271 | magics are loaded in their transformed version to valid Python. If |
|
271 | magics are loaded in their transformed version to valid Python. If | |
272 | this option is given, the raw input as typed as the command line is |
|
272 | this option is given, the raw input as typed as the command line is | |
273 | used instead. When you exit the editor, it will be executed by |
|
273 | used instead. When you exit the editor, it will be executed by | |
274 | IPython's own processor. |
|
274 | IPython's own processor. | |
275 |
|
275 | |||
276 | -x: do not execute the edited code immediately upon exit. This is |
|
276 | -x: do not execute the edited code immediately upon exit. This is | |
277 | mainly useful if you are editing programs which need to be called with |
|
277 | mainly useful if you are editing programs which need to be called with | |
278 | command line arguments, which you can then do using %run. |
|
278 | command line arguments, which you can then do using %run. | |
279 |
|
279 | |||
280 |
|
280 | |||
281 | Arguments: |
|
281 | Arguments: | |
282 |
|
282 | |||
283 | If arguments are given, the following possibilites exist: |
|
283 | If arguments are given, the following possibilites exist: | |
284 |
|
284 | |||
285 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
285 | - The arguments are numbers or pairs of colon-separated numbers (like | |
286 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
286 | 1 4:8 9). These are interpreted as lines of previous input to be | |
287 | loaded into the editor. The syntax is the same of the %macro command. |
|
287 | loaded into the editor. The syntax is the same of the %macro command. | |
288 |
|
288 | |||
289 | - If the argument doesn't start with a number, it is evaluated as a |
|
289 | - If the argument doesn't start with a number, it is evaluated as a | |
290 | variable and its contents loaded into the editor. You can thus edit |
|
290 | variable and its contents loaded into the editor. You can thus edit | |
291 | any string which contains python code (including the result of |
|
291 | any string which contains python code (including the result of | |
292 | previous edits). |
|
292 | previous edits). | |
293 |
|
293 | |||
294 | - If the argument is the name of an object (other than a string), |
|
294 | - If the argument is the name of an object (other than a string), | |
295 | IPython will try to locate the file where it was defined and open the |
|
295 | IPython will try to locate the file where it was defined and open the | |
296 | editor at the point where it is defined. You can use `%edit function` |
|
296 | editor at the point where it is defined. You can use `%edit function` | |
297 | to load an editor exactly at the point where 'function' is defined, |
|
297 | to load an editor exactly at the point where 'function' is defined, | |
298 | edit it and have the file be executed automatically. |
|
298 | edit it and have the file be executed automatically. | |
299 |
|
299 | |||
300 | If the object is a macro (see %macro for details), this opens up your |
|
300 | If the object is a macro (see %macro for details), this opens up your | |
301 | specified editor with a temporary file containing the macro's data. |
|
301 | specified editor with a temporary file containing the macro's data. | |
302 | Upon exit, the macro is reloaded with the contents of the file. |
|
302 | Upon exit, the macro is reloaded with the contents of the file. | |
303 |
|
303 | |||
304 | Note: opening at an exact line is only supported under Unix, and some |
|
304 | Note: opening at an exact line is only supported under Unix, and some | |
305 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
305 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
306 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
306 | '+NUMBER' parameter necessary for this feature. Good editors like | |
307 | (X)Emacs, vi, jed, pico and joe all do. |
|
307 | (X)Emacs, vi, jed, pico and joe all do. | |
308 |
|
308 | |||
309 | - If the argument is not found as a variable, IPython will look for a |
|
309 | - If the argument is not found as a variable, IPython will look for a | |
310 | file with that name (adding .py if necessary) and load it into the |
|
310 | file with that name (adding .py if necessary) and load it into the | |
311 | editor. It will execute its contents with execfile() when you exit, |
|
311 | editor. It will execute its contents with execfile() when you exit, | |
312 | loading any code in the file into your interactive namespace. |
|
312 | loading any code in the file into your interactive namespace. | |
313 |
|
313 | |||
314 | After executing your code, %edit will return as output the code you |
|
314 | After executing your code, %edit will return as output the code you | |
315 | typed in the editor (except when it was an existing file). This way |
|
315 | typed in the editor (except when it was an existing file). This way | |
316 | you can reload the code in further invocations of %edit as a variable, |
|
316 | you can reload the code in further invocations of %edit as a variable, | |
317 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
317 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
318 | the output. |
|
318 | the output. | |
319 |
|
319 | |||
320 | Note that %edit is also available through the alias %ed. |
|
320 | Note that %edit is also available through the alias %ed. | |
321 |
|
321 | |||
322 | This is an example of creating a simple function inside the editor and |
|
322 | This is an example of creating a simple function inside the editor and | |
323 | then modifying it. First, start up the editor: |
|
323 | then modifying it. First, start up the editor: | |
324 |
|
324 | |||
325 | In [1]: ed |
|
325 | In [1]: ed | |
326 | Editing... done. Executing edited code... |
|
326 | Editing... done. Executing edited code... | |
327 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
327 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
328 |
|
328 | |||
329 | We can then call the function foo(): |
|
329 | We can then call the function foo(): | |
330 |
|
330 | |||
331 | In [2]: foo() |
|
331 | In [2]: foo() | |
332 | foo() was defined in an editing session |
|
332 | foo() was defined in an editing session | |
333 |
|
333 | |||
334 | Now we edit foo. IPython automatically loads the editor with the |
|
334 | Now we edit foo. IPython automatically loads the editor with the | |
335 | (temporary) file where foo() was previously defined: |
|
335 | (temporary) file where foo() was previously defined: | |
336 |
|
336 | |||
337 | In [3]: ed foo |
|
337 | In [3]: ed foo | |
338 | Editing... done. Executing edited code... |
|
338 | Editing... done. Executing edited code... | |
339 |
|
339 | |||
340 | And if we call foo() again we get the modified version: |
|
340 | And if we call foo() again we get the modified version: | |
341 |
|
341 | |||
342 | In [4]: foo() |
|
342 | In [4]: foo() | |
343 | foo() has now been changed! |
|
343 | foo() has now been changed! | |
344 |
|
344 | |||
345 | Here is an example of how to edit a code snippet successive |
|
345 | Here is an example of how to edit a code snippet successive | |
346 | times. First we call the editor: |
|
346 | times. First we call the editor: | |
347 |
|
347 | |||
348 | In [5]: ed |
|
348 | In [5]: ed | |
349 | Editing... done. Executing edited code... |
|
349 | Editing... done. Executing edited code... | |
350 | hello |
|
350 | hello | |
351 | Out[5]: "print 'hello'n" |
|
351 | Out[5]: "print 'hello'n" | |
352 |
|
352 | |||
353 | Now we call it again with the previous output (stored in _): |
|
353 | Now we call it again with the previous output (stored in _): | |
354 |
|
354 | |||
355 | In [6]: ed _ |
|
355 | In [6]: ed _ | |
356 | Editing... done. Executing edited code... |
|
356 | Editing... done. Executing edited code... | |
357 | hello world |
|
357 | hello world | |
358 | Out[6]: "print 'hello world'n" |
|
358 | Out[6]: "print 'hello world'n" | |
359 |
|
359 | |||
360 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
360 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
361 |
|
361 | |||
362 | In [7]: ed _8 |
|
362 | In [7]: ed _8 | |
363 | Editing... done. Executing edited code... |
|
363 | Editing... done. Executing edited code... | |
364 | hello again |
|
364 | hello again | |
365 | Out[7]: "print 'hello again'n" |
|
365 | Out[7]: "print 'hello again'n" | |
366 |
|
366 | |||
367 |
|
367 | |||
368 | Changing the default editor hook: |
|
368 | Changing the default editor hook: | |
369 |
|
369 | |||
370 | If you wish to write your own editor hook, you can put it in a |
|
370 | If you wish to write your own editor hook, you can put it in a | |
371 | configuration file which you load at startup time. The default hook |
|
371 | configuration file which you load at startup time. The default hook | |
372 | is defined in the IPython.core.hooks module, and you can use that as a |
|
372 | is defined in the IPython.core.hooks module, and you can use that as a | |
373 | starting example for further modifications. That file also has |
|
373 | starting example for further modifications. That file also has | |
374 | general instructions on how to set a new hook for use once you've |
|
374 | general instructions on how to set a new hook for use once you've | |
375 | defined it.""" |
|
375 | defined it.""" | |
376 |
|
376 | |||
377 | opts,args = self.parse_options(parameter_s,'prn:') |
|
377 | opts,args = self.parse_options(parameter_s,'prn:') | |
378 |
|
378 | |||
379 | try: |
|
379 | try: | |
380 | filename, lineno, _ = self._find_edit_target(args, opts, last_call) |
|
380 | filename, lineno, _ = self._find_edit_target(args, opts, last_call) | |
381 | except MacroToEdit as e: |
|
381 | except MacroToEdit as e: | |
382 | # TODO: Implement macro editing over 2 processes. |
|
382 | # TODO: Implement macro editing over 2 processes. | |
383 | print("Macro editing not yet implemented in 2-process model.") |
|
383 | print("Macro editing not yet implemented in 2-process model.") | |
384 | return |
|
384 | return | |
385 |
|
385 | |||
386 | # Make sure we send to the client an absolute path, in case the working |
|
386 | # Make sure we send to the client an absolute path, in case the working | |
387 | # directory of client and kernel don't match |
|
387 | # directory of client and kernel don't match | |
388 | filename = os.path.abspath(filename) |
|
388 | filename = os.path.abspath(filename) | |
389 |
|
389 | |||
390 | payload = { |
|
390 | payload = { | |
391 | 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic', |
|
391 | 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic', | |
392 | 'filename' : filename, |
|
392 | 'filename' : filename, | |
393 | 'line_number' : lineno |
|
393 | 'line_number' : lineno | |
394 | } |
|
394 | } | |
395 | self.payload_manager.write_payload(payload) |
|
395 | self.payload_manager.write_payload(payload) | |
396 |
|
396 | |||
397 | def magic_gui(self, *args, **kwargs): |
|
397 | def magic_gui(self, *args, **kwargs): | |
398 | raise NotImplementedError( |
|
398 | raise NotImplementedError( | |
399 | 'Kernel GUI support is not implemented yet, except for --pylab.') |
|
399 | 'Kernel GUI support is not implemented yet, except for --pylab.') | |
400 |
|
400 | |||
401 | def magic_pylab(self, *args, **kwargs): |
|
401 | def magic_pylab(self, *args, **kwargs): | |
402 | raise NotImplementedError( |
|
402 | raise NotImplementedError( | |
403 | 'pylab support must be enabled in command line options.') |
|
403 | 'pylab support must be enabled in command line options.') | |
404 |
|
404 | |||
405 | # A few magics that are adapted to the specifics of using pexpect and a |
|
405 | # A few magics that are adapted to the specifics of using pexpect and a | |
406 | # remote terminal |
|
406 | # remote terminal | |
407 |
|
407 | |||
408 | def magic_clear(self, arg_s): |
|
408 | def magic_clear(self, arg_s): | |
409 | """Clear the terminal.""" |
|
409 | """Clear the terminal.""" | |
410 | if os.name == 'posix': |
|
410 | if os.name == 'posix': | |
411 | self.shell.system("clear") |
|
411 | self.shell.system("clear") | |
412 | else: |
|
412 | else: | |
413 | self.shell.system("cls") |
|
413 | self.shell.system("cls") | |
414 |
|
414 | |||
415 | if os.name == 'nt': |
|
415 | if os.name == 'nt': | |
416 | # This is the usual name in windows |
|
416 | # This is the usual name in windows | |
417 | magic_cls = magic_clear |
|
417 | magic_cls = magic_clear | |
418 |
|
418 | |||
419 | # Terminal pagers won't work over pexpect, but we do have our own pager |
|
419 | # Terminal pagers won't work over pexpect, but we do have our own pager | |
420 |
|
420 | |||
421 | def magic_less(self, arg_s): |
|
421 | def magic_less(self, arg_s): | |
422 | """Show a file through the pager. |
|
422 | """Show a file through the pager. | |
423 |
|
423 | |||
424 | Files ending in .py are syntax-highlighted.""" |
|
424 | Files ending in .py are syntax-highlighted.""" | |
425 | cont = open(arg_s).read() |
|
425 | cont = open(arg_s).read() | |
426 | if arg_s.endswith('.py'): |
|
426 | if arg_s.endswith('.py'): | |
427 | cont = self.shell.pycolorize(cont) |
|
427 | cont = self.shell.pycolorize(cont) | |
428 | page.page(cont) |
|
428 | page.page(cont) | |
429 |
|
429 | |||
430 | magic_more = magic_less |
|
430 | magic_more = magic_less | |
431 |
|
431 | |||
432 | # Man calls a pager, so we also need to redefine it |
|
432 | # Man calls a pager, so we also need to redefine it | |
433 | if os.name == 'posix': |
|
433 | if os.name == 'posix': | |
434 | def magic_man(self, arg_s): |
|
434 | def magic_man(self, arg_s): | |
435 | """Find the man page for the given command and display in pager.""" |
|
435 | """Find the man page for the given command and display in pager.""" | |
436 | page.page(self.shell.getoutput('man %s | col -b' % arg_s, |
|
436 | page.page(self.shell.getoutput('man %s | col -b' % arg_s, | |
437 | split=False)) |
|
437 | split=False)) | |
438 |
|
438 | |||
439 | # FIXME: this is specific to the GUI, so we should let the gui app load |
|
439 | # FIXME: this is specific to the GUI, so we should let the gui app load | |
440 | # magics at startup that are only for the gui. Once the gui app has proper |
|
440 | # magics at startup that are only for the gui. Once the gui app has proper | |
441 | # profile and configuration management, we can have it initialize a kernel |
|
441 | # profile and configuration management, we can have it initialize a kernel | |
442 | # with a special config file that provides these. |
|
442 | # with a special config file that provides these. | |
443 | def magic_guiref(self, arg_s): |
|
443 | def magic_guiref(self, arg_s): | |
444 | """Show a basic reference about the GUI console.""" |
|
444 | """Show a basic reference about the GUI console.""" | |
445 | from IPython.core.usage import gui_reference |
|
445 | from IPython.core.usage import gui_reference | |
446 | page.page(gui_reference, auto_html=True) |
|
446 | page.page(gui_reference, auto_html=True) | |
447 |
|
447 | |||
448 | def set_next_input(self, text): |
|
448 | def set_next_input(self, text): | |
449 | """Send the specified text to the frontend to be presented at the next |
|
449 | """Send the specified text to the frontend to be presented at the next | |
450 | input cell.""" |
|
450 | input cell.""" | |
451 | payload = dict( |
|
451 | payload = dict( | |
452 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.set_next_input', |
|
452 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.set_next_input', | |
453 | text=text |
|
453 | text=text | |
454 | ) |
|
454 | ) | |
455 | self.payload_manager.write_payload(payload) |
|
455 | self.payload_manager.write_payload(payload) | |
456 |
|
456 | |||
457 | InteractiveShellABC.register(ZMQInteractiveShell) |
|
457 | InteractiveShellABC.register(ZMQInteractiveShell) |
General Comments 0
You need to be logged in to leave comments.
Login now