##// END OF EJS Templates
Finishing display system work....
Brian E. Granger -
Show More
@@ -1,274 +1,373 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Top-level display functions for displaying object in different formats.
3 3
4 4 Authors:
5 5
6 6 * Brian Granger
7 7 """
8 8
9 9 #-----------------------------------------------------------------------------
10 10 # Copyright (C) 2008-2010 The IPython Development Team
11 11 #
12 12 # Distributed under the terms of the BSD License. The full license is in
13 13 # the file COPYING, distributed as part of this software.
14 14 #-----------------------------------------------------------------------------
15 15
16 16 #-----------------------------------------------------------------------------
17 17 # Imports
18 18 #-----------------------------------------------------------------------------
19 19
20 20 from .displaypub import (
21 21 publish_pretty, publish_html,
22 22 publish_latex, publish_svg,
23 23 publish_png, publish_json,
24 publish_javascript
24 publish_javascript, publish_jpeg
25 25 )
26 26
27 27 #-----------------------------------------------------------------------------
28 28 # Main functions
29 29 #-----------------------------------------------------------------------------
30 30
31 31 def display(*objs, **kwargs):
32 32 """Display a Python object in all frontends.
33 33
34 34 By default all representations will be computed and sent to the frontends.
35 35 Frontends can decide which representation is used and how.
36 36
37 37 Parameters
38 38 ----------
39 39 objs : tuple of objects
40 40 The Python objects to display.
41 41 include : list or tuple, optional
42 42 A list of format type strings (MIME types) to include in the
43 43 format data dict. If this is set *only* the format types included
44 44 in this list will be computed.
45 45 exclude : list or tuple, optional
46 46 A list of format type string (MIME types) to exclue in the format
47 47 data dict. If this is set all format types will be computed,
48 48 except for those included in this argument.
49 49 """
50 50 include = kwargs.get('include')
51 51 exclude = kwargs.get('exclude')
52 52
53 53 from IPython.core.interactiveshell import InteractiveShell
54 54 inst = InteractiveShell.instance()
55 55 format = inst.display_formatter.format
56 56 publish = inst.display_pub.publish
57 57
58 58 for obj in objs:
59 59 format_dict = format(obj, include=include, exclude=exclude)
60 60 publish('IPython.core.display.display', format_dict)
61 61
62 62
63 63 def display_pretty(*objs, **kwargs):
64 64 """Display the pretty (default) representation of an object.
65 65
66 66 Parameters
67 67 ----------
68 68 objs : tuple of objects
69 69 The Python objects to display, or if raw=True raw text data to
70 70 display.
71 71 raw : bool
72 72 Are the data objects raw data or Python objects that need to be
73 73 formatted before display? [default: False]
74 74 """
75 75 raw = kwargs.pop('raw',False)
76 76 if raw:
77 77 for obj in objs:
78 78 publish_pretty(obj)
79 79 else:
80 80 display(*objs, include=['text/plain'])
81 81
82 82
83 83 def display_html(*objs, **kwargs):
84 84 """Display the HTML representation of an object.
85 85
86 86 Parameters
87 87 ----------
88 88 objs : tuple of objects
89 The Python objects to display, or if raw=True raw html data to
89 The Python objects to display, or if raw=True raw HTML data to
90 90 display.
91 91 raw : bool
92 92 Are the data objects raw data or Python objects that need to be
93 93 formatted before display? [default: False]
94 94 """
95 95 raw = kwargs.pop('raw',False)
96 96 if raw:
97 97 for obj in objs:
98 98 publish_html(obj)
99 99 else:
100 100 display(*objs, include=['text/plain','text/html'])
101 101
102 102
103 103 def display_svg(*objs, **kwargs):
104 104 """Display the SVG representation of an object.
105 105
106 106 Parameters
107 107 ----------
108 108 objs : tuple of objects
109 109 The Python objects to display, or if raw=True raw svg data to
110 110 display.
111 111 raw : bool
112 112 Are the data objects raw data or Python objects that need to be
113 113 formatted before display? [default: False]
114 114 """
115 115 raw = kwargs.pop('raw',False)
116 116 if raw:
117 117 for obj in objs:
118 118 publish_svg(obj)
119 119 else:
120 120 display(*objs, include=['text/plain','image/svg+xml'])
121 121
122 122
123 123 def display_png(*objs, **kwargs):
124 124 """Display the PNG representation of an object.
125 125
126 126 Parameters
127 127 ----------
128 128 objs : tuple of objects
129 129 The Python objects to display, or if raw=True raw png data to
130 130 display.
131 131 raw : bool
132 132 Are the data objects raw data or Python objects that need to be
133 133 formatted before display? [default: False]
134 134 """
135 135 raw = kwargs.pop('raw',False)
136 136 if raw:
137 137 for obj in objs:
138 138 publish_png(obj)
139 139 else:
140 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 163 def display_latex(*objs, **kwargs):
144 164 """Display the LaTeX representation of an object.
145 165
146 166 Parameters
147 167 ----------
148 168 objs : tuple of objects
149 169 The Python objects to display, or if raw=True raw latex data to
150 170 display.
151 171 raw : bool
152 172 Are the data objects raw data or Python objects that need to be
153 173 formatted before display? [default: False]
154 174 """
155 175 raw = kwargs.pop('raw',False)
156 176 if raw:
157 177 for obj in objs:
158 178 publish_latex(obj)
159 179 else:
160 180 display(*objs, include=['text/plain','text/latex'])
161 181
162 182
163 183 def display_json(*objs, **kwargs):
164 184 """Display the JSON representation of an object.
165 185
166 186 Parameters
167 187 ----------
168 188 objs : tuple of objects
169 189 The Python objects to display, or if raw=True raw json data to
170 190 display.
171 191 raw : bool
172 192 Are the data objects raw data or Python objects that need to be
173 193 formatted before display? [default: False]
174 194 """
175 195 raw = kwargs.pop('raw',False)
176 196 if raw:
177 197 for obj in objs:
178 198 publish_json(obj)
179 199 else:
180 200 display(*objs, include=['text/plain','application/json'])
181 201
182 202
183 203 def display_javascript(*objs, **kwargs):
184 204 """Display the Javascript representation of an object.
185 205
186 206 Parameters
187 207 ----------
188 208 objs : tuple of objects
189 209 The Python objects to display, or if raw=True raw javascript data to
190 210 display.
191 211 raw : bool
192 212 Are the data objects raw data or Python objects that need to be
193 213 formatted before display? [default: False]
194 214 """
195 215 raw = kwargs.pop('raw',False)
196 216 if raw:
197 217 for obj in objs:
198 218 publish_javascript(obj)
199 219 else:
200 220 display(*objs, include=['text/plain','application/javascript'])
201 221
202 222 #-----------------------------------------------------------------------------
203 223 # Smart classes
204 224 #-----------------------------------------------------------------------------
205 225
206 226
207 227 class DisplayObject(object):
208 228 """An object that wraps data to be displayed."""
209 229
210 def __init__(self, data):
211 """Create a display object given raw data of a MIME type or a URL.
230 _read_flags = 'r'
231
232 def __init__(self, data=None, url=None, filename=None):
233 """Create a display object given raw data.
212 234
213 235 When this object is returned by an expression or passed to the
214 236 display function, it will result in the data being displayed
215 237 in the frontend. The MIME type of the data should match the
216 238 subclasses used, so the Png subclass should be used for 'image/png'
217 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 242 Parameters
221 243 ----------
222 244 data : unicode, str or bytes
223 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'):
226 import urllib2
227 response = urllib2.urlopen(data)
228 self.data = response.read()
251 if data is not None and data.startswith('http'):
252 self.url = data
253 self.filename = None
254 self.data = None
229 255 else:
230 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 274 class Pretty(DisplayObject):
234 275
235 276 def _repr_pretty_(self):
236 277 return self.data
237 278
238 279
239 class Html(DisplayObject):
280 class HTML(DisplayObject):
240 281
241 282 def _repr_html_(self):
242 283 return self.data
243 284
244 285
245 class Latex(DisplayObject):
286 class Math(DisplayObject):
246 287
247 288 def _repr_latex_(self):
248 289 return self.data
249 290
250 291
251 class Png(DisplayObject):
292 class SVG(DisplayObject):
252 293
253 def _repr_png_(self):
294 def _repr_svg_(self):
254 295 return self.data
255 296
256 297
257 class Svg(DisplayObject):
298 class JSON(DisplayObject):
258 299
259 def _repr_svg_(self):
300 def _repr_json_(self):
260 301 return self.data
261 302
262 303
263 class Json(DisplayObject):
304 class Javascript(DisplayObject):
264 305
265 def _repr_json_(self):
306 def _repr_javascript_(self):
266 307 return self.data
267 308
268 309
269 class Javscript(DisplayObject):
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 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 1 """An interface for publishing rich data to frontends.
2 2
3 3 There are two components of the display system:
4 4
5 5 * Display formatters, which take a Python object and compute the
6 6 representation of the object in various formats (text, HTML, SVg, etc.).
7 7 * The display publisher that is used to send the representation data to the
8 8 various frontends.
9 9
10 10 This module defines the logic display publishing. The display publisher uses
11 11 the ``display_data`` message type that is defined in the IPython messaging
12 12 spec.
13 13
14 14 Authors:
15 15
16 16 * Brian Granger
17 17 """
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Copyright (C) 2008-2010 The IPython Development Team
21 21 #
22 22 # Distributed under the terms of the BSD License. The full license is in
23 23 # the file COPYING, distributed as part of this software.
24 24 #-----------------------------------------------------------------------------
25 25
26 26 #-----------------------------------------------------------------------------
27 27 # Imports
28 28 #-----------------------------------------------------------------------------
29 29
30 30 from __future__ import print_function
31 31
32 32 from IPython.config.configurable import Configurable
33 33
34 34 #-----------------------------------------------------------------------------
35 35 # Main payload class
36 36 #-----------------------------------------------------------------------------
37 37
38 38 class DisplayPublisher(Configurable):
39 39 """A traited class that publishes display data to frontends.
40 40
41 41 Instances of this class are created by the main IPython object and should
42 42 be accessed there.
43 43 """
44 44
45 45 def _validate_data(self, source, data, metadata=None):
46 46 """Validate the display data.
47 47
48 48 Parameters
49 49 ----------
50 50 source : str
51 51 The fully dotted name of the callable that created the data, like
52 52 :func:`foo.bar.my_formatter`.
53 53 data : dict
54 54 The formata data dictionary.
55 55 metadata : dict
56 56 Any metadata for the data.
57 57 """
58 58
59 59 if not isinstance(source, (str,unicode)):
60 60 raise TypeError('source must be a str, got: %r' % source)
61 61 if not isinstance(data, dict):
62 62 raise TypeError('data must be a dict, got: %r' % data)
63 63 if metadata is not None:
64 64 if not isinstance(metadata, dict):
65 65 raise TypeError('metadata must be a dict, got: %r' % data)
66 66
67 67 def publish(self, source, data, metadata=None):
68 68 """Publish data and metadata to all frontends.
69 69
70 70 See the ``display_data`` message in the messaging documentation for
71 71 more details about this message type.
72 72
73 73 The following MIME types are currently implemented:
74 74
75 75 * text/plain
76 76 * text/html
77 77 * text/latex
78 78 * application/json
79 79 * application/javascript
80 80 * image/png
81 * image/jpeg
81 82 * image/svg+xml
82 83
83 84 Parameters
84 85 ----------
85 86 source : str
86 87 A string that give the function or method that created the data,
87 88 such as 'IPython.core.page'.
88 89 data : dict
89 90 A dictionary having keys that are valid MIME types (like
90 91 'text/plain' or 'image/svg+xml') and values that are the data for
91 92 that MIME type. The data itself must be a JSON'able data
92 93 structure. Minimally all data should have the 'text/plain' data,
93 94 which can be displayed by all frontends. If more than the plain
94 95 text is given, it is up to the frontend to decide which
95 96 representation to use.
96 97 metadata : dict
97 98 A dictionary for metadata related to the data. This can contain
98 99 arbitrary key, value pairs that frontends can use to interpret
99 100 the data.
100 101 """
101 102 from IPython.utils import io
102 103 # The default is to simply write the plain text data using io.stdout.
103 104 if data.has_key('text/plain'):
104 105 print(data['text/plain'], file=io.stdout)
105 106
106 107
107 108 def publish_display_data(source, data, metadata=None):
108 109 """Publish data and metadata to all frontends.
109 110
110 111 See the ``display_data`` message in the messaging documentation for
111 112 more details about this message type.
112 113
113 114 The following MIME types are currently implemented:
114 115
115 116 * text/plain
116 117 * text/html
117 118 * text/latex
118 119 * application/json
119 120 * application/javascript
120 121 * image/png
122 * image/jpeg
121 123 * image/svg+xml
122 124
123 125 Parameters
124 126 ----------
125 127 source : str
126 128 A string that give the function or method that created the data,
127 129 such as 'IPython.core.page'.
128 130 data : dict
129 131 A dictionary having keys that are valid MIME types (like
130 132 'text/plain' or 'image/svg+xml') and values that are the data for
131 133 that MIME type. The data itself must be a JSON'able data
132 134 structure. Minimally all data should have the 'text/plain' data,
133 135 which can be displayed by all frontends. If more than the plain
134 136 text is given, it is up to the frontend to decide which
135 137 representation to use.
136 138 metadata : dict
137 139 A dictionary for metadata related to the data. This can contain
138 140 arbitrary key, value pairs that frontends can use to interpret
139 141 the data.
140 142 """
141 143 from IPython.core.interactiveshell import InteractiveShell
142 144 InteractiveShell.instance().display_pub.publish(
143 145 source,
144 146 data,
145 147 metadata
146 148 )
147 149
148 150
149 151 def publish_pretty(data, metadata=None):
150 152 """Publish raw text data to all frontends.
151 153
152 154 Parameters
153 155 ----------
154 156 data : unicode
155 157 The raw text data to publish.
156 158 metadata : dict
157 159 A dictionary for metadata related to the data. This can contain
158 160 arbitrary key, value pairs that frontends can use to interpret
159 161 the data.
160 162 """
161 163 publish_display_data(
162 164 u'IPython.core.displaypub.publish_pretty',
163 165 {'text/plain':data},
164 166 metadata=metadata
165 167 )
166 168
167 169
168 170 def publish_html(data, metadata=None):
169 """Publish raw html data to all frontends.
171 """Publish raw HTML data to all frontends.
170 172
171 173 Parameters
172 174 ----------
173 175 data : unicode
174 The raw html data to publish.
176 The raw HTML data to publish.
175 177 metadata : dict
176 178 A dictionary for metadata related to the data. This can contain
177 179 arbitrary key, value pairs that frontends can use to interpret
178 180 the data.
179 181 """
180 182 publish_display_data(
181 183 u'IPython.core.displaypub.publish_html',
182 184 {'text/html':data},
183 185 metadata=metadata
184 186 )
185 187
186 188
187 189 def publish_latex(data, metadata=None):
188 """Publish raw latex data to all frontends.
190 """Publish raw LaTeX data to all frontends.
189 191
190 192 Parameters
191 193 ----------
192 194 data : unicode
193 The raw latex data to publish.
195 The raw LaTeX data to publish.
194 196 metadata : dict
195 197 A dictionary for metadata related to the data. This can contain
196 198 arbitrary key, value pairs that frontends can use to interpret
197 199 the data.
198 200 """
199 201 publish_display_data(
200 202 u'IPython.core.displaypub.publish_latex',
201 203 {'text/latex':data},
202 204 metadata=metadata
203 205 )
204 206
205 207 def publish_png(data, metadata=None):
206 """Publish raw binary png data to all frontends.
208 """Publish raw binary PNG data to all frontends.
207 209
208 210 Parameters
209 211 ----------
210 212 data : str/bytes
211 The raw binary png data to publish.
213 The raw binary PNG data to publish.
212 214 metadata : dict
213 215 A dictionary for metadata related to the data. This can contain
214 216 arbitrary key, value pairs that frontends can use to interpret
215 217 the data.
216 218 """
217 219 publish_display_data(
218 220 u'IPython.core.displaypub.publish_png',
219 221 {'image/png':data},
220 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 245 def publish_svg(data, metadata=None):
224 """Publish raw svg data to all frontends.
246 """Publish raw SVG data to all frontends.
225 247
226 248 Parameters
227 249 ----------
228 250 data : unicode
229 The raw svg data to publish.
251 The raw SVG data to publish.
230 252 metadata : dict
231 253 A dictionary for metadata related to the data. This can contain
232 254 arbitrary key, value pairs that frontends can use to interpret
233 255 the data.
234 256 """
235 257 publish_display_data(
236 258 u'IPython.core.displaypub.publish_svg',
237 259 {'image/svg+xml':data},
238 260 metadata=metadata
239 261 )
240 262
241 263 def publish_json(data, metadata=None):
242 """Publish raw json data to all frontends.
264 """Publish raw JSON data to all frontends.
243 265
244 266 Parameters
245 267 ----------
246 268 data : unicode
247 The raw json data to publish.
269 The raw JSON data to publish.
248 270 metadata : dict
249 271 A dictionary for metadata related to the data. This can contain
250 272 arbitrary key, value pairs that frontends can use to interpret
251 273 the data.
252 274 """
253 275 publish_display_data(
254 276 u'IPython.core.displaypub.publish_json',
255 277 {'application/json':data},
256 278 metadata=metadata
257 279 )
258 280
259 281 def publish_javascript(data, metadata=None):
260 """Publish raw javascript data to all frontends.
282 """Publish raw Javascript data to all frontends.
261 283
262 284 Parameters
263 285 ----------
264 286 data : unicode
265 The raw javascript data to publish.
287 The raw Javascript data to publish.
266 288 metadata : dict
267 289 A dictionary for metadata related to the data. This can contain
268 290 arbitrary key, value pairs that frontends can use to interpret
269 291 the data.
270 292 """
271 293 publish_display_data(
272 294 u'IPython.core.displaypub.publish_javascript',
273 295 {'application/javascript':data},
274 296 metadata=metadata
275 297 )
276 298
@@ -1,598 +1,619 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Display formatters.
3 3
4 4
5 5 Authors:
6 6
7 7 * Robert Kern
8 8 * Brian Granger
9 9 """
10 10 #-----------------------------------------------------------------------------
11 11 # Copyright (c) 2010, IPython Development Team.
12 12 #
13 13 # Distributed under the terms of the Modified BSD License.
14 14 #
15 15 # The full license is in the file COPYING.txt, distributed with this software.
16 16 #-----------------------------------------------------------------------------
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 21
22 22 # Stdlib imports
23 23 import abc
24 24 import sys
25 25 # We must use StringIO, as cStringIO doesn't handle unicode properly.
26 26 from StringIO import StringIO
27 27
28 28 # Our own imports
29 29 from IPython.config.configurable import Configurable
30 30 from IPython.lib import pretty
31 31 from IPython.utils.traitlets import Bool, Dict, Int, Unicode, CUnicode, ObjectName
32 32
33 33
34 34 #-----------------------------------------------------------------------------
35 35 # The main DisplayFormatter class
36 36 #-----------------------------------------------------------------------------
37 37
38 38
39 39 class DisplayFormatter(Configurable):
40 40
41 41 # When set to true only the default plain text formatter will be used.
42 42 plain_text_only = Bool(False, config=True)
43 43
44 44 # A dict of formatter whose keys are format types (MIME types) and whose
45 45 # values are subclasses of BaseFormatter.
46 46 formatters = Dict(config=True)
47 47 def _formatters_default(self):
48 48 """Activate the default formatters."""
49 49 formatter_classes = [
50 50 PlainTextFormatter,
51 51 HTMLFormatter,
52 52 SVGFormatter,
53 53 PNGFormatter,
54 JPEGFormatter,
54 55 LatexFormatter,
55 56 JSONFormatter,
56 57 JavascriptFormatter
57 58 ]
58 59 d = {}
59 60 for cls in formatter_classes:
60 61 f = cls(config=self.config)
61 62 d[f.format_type] = f
62 63 return d
63 64
64 65 def format(self, obj, include=None, exclude=None):
65 66 """Return a format data dict for an object.
66 67
67 68 By default all format types will be computed.
68 69
69 70 The following MIME types are currently implemented:
70 71
71 72 * text/plain
72 73 * text/html
73 74 * text/latex
74 75 * application/json
75 76 * application/javascript
76 77 * image/png
78 * image/jpeg
77 79 * image/svg+xml
78 80
79 81 Parameters
80 82 ----------
81 83 obj : object
82 84 The Python object whose format data will be computed.
83 85 include : list or tuple, optional
84 86 A list of format type strings (MIME types) to include in the
85 87 format data dict. If this is set *only* the format types included
86 88 in this list will be computed.
87 89 exclude : list or tuple, optional
88 90 A list of format type string (MIME types) to exclue in the format
89 91 data dict. If this is set all format types will be computed,
90 92 except for those included in this argument.
91 93
92 94 Returns
93 95 -------
94 96 format_dict : dict
95 97 A dictionary of key/value pairs, one or each format that was
96 98 generated for the object. The keys are the format types, which
97 99 will usually be MIME type strings and the values and JSON'able
98 100 data structure containing the raw data for the representation in
99 101 that format.
100 102 """
101 103 format_dict = {}
102 104
103 105 # If plain text only is active
104 106 if self.plain_text_only:
105 107 formatter = self.formatters['text/plain']
106 108 try:
107 109 data = formatter(obj)
108 110 except:
109 111 # FIXME: log the exception
110 112 raise
111 113 if data is not None:
112 114 format_dict['text/plain'] = data
113 115 return format_dict
114 116
115 117 for format_type, formatter in self.formatters.items():
116 118 if include is not None:
117 119 if format_type not in include:
118 120 continue
119 121 if exclude is not None:
120 122 if format_type in exclude:
121 123 continue
122 124 try:
123 125 data = formatter(obj)
124 126 except:
125 127 # FIXME: log the exception
126 128 raise
127 129 if data is not None:
128 130 format_dict[format_type] = data
129 131 return format_dict
130 132
131 133 @property
132 134 def format_types(self):
133 135 """Return the format types (MIME types) of the active formatters."""
134 136 return self.formatters.keys()
135 137
136 138
137 139 #-----------------------------------------------------------------------------
138 140 # Formatters for specific format types (text, html, svg, etc.)
139 141 #-----------------------------------------------------------------------------
140 142
141 143
142 144 class FormatterABC(object):
143 145 """ Abstract base class for Formatters.
144 146
145 147 A formatter is a callable class that is responsible for computing the
146 148 raw format data for a particular format type (MIME type). For example,
147 149 an HTML formatter would have a format type of `text/html` and would return
148 150 the HTML representation of the object when called.
149 151 """
150 152 __metaclass__ = abc.ABCMeta
151 153
152 154 # The format type of the data returned, usually a MIME type.
153 155 format_type = 'text/plain'
154 156
155 157 # Is the formatter enabled...
156 158 enabled = True
157 159
158 160 @abc.abstractmethod
159 161 def __call__(self, obj):
160 162 """Return a JSON'able representation of the object.
161 163
162 164 If the object cannot be formatted by this formatter, then return None
163 165 """
164 166 try:
165 167 return repr(obj)
166 168 except TypeError:
167 169 return None
168 170
169 171
170 172 class BaseFormatter(Configurable):
171 173 """A base formatter class that is configurable.
172 174
173 175 This formatter should usually be used as the base class of all formatters.
174 176 It is a traited :class:`Configurable` class and includes an extensible
175 177 API for users to determine how their objects are formatted. The following
176 178 logic is used to find a function to format an given object.
177 179
178 180 1. The object is introspected to see if it has a method with the name
179 181 :attr:`print_method`. If is does, that object is passed to that method
180 182 for formatting.
181 183 2. If no print method is found, three internal dictionaries are consulted
182 184 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
183 185 and :attr:`deferred_printers`.
184 186
185 187 Users should use these dictionaries to register functions that will be
186 188 used to compute the format data for their objects (if those objects don't
187 189 have the special print methods). The easiest way of using these
188 190 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
189 191 methods.
190 192
191 193 If no function/callable is found to compute the format data, ``None`` is
192 194 returned and this format type is not used.
193 195 """
194 196
195 197 format_type = Unicode('text/plain')
196 198
197 199 enabled = Bool(True, config=True)
198 200
199 201 print_method = ObjectName('__repr__')
200 202
201 203 # The singleton printers.
202 204 # Maps the IDs of the builtin singleton objects to the format functions.
203 205 singleton_printers = Dict(config=True)
204 206 def _singleton_printers_default(self):
205 207 return {}
206 208
207 209 # The type-specific printers.
208 210 # Map type objects to the format functions.
209 211 type_printers = Dict(config=True)
210 212 def _type_printers_default(self):
211 213 return {}
212 214
213 215 # The deferred-import type-specific printers.
214 216 # Map (modulename, classname) pairs to the format functions.
215 217 deferred_printers = Dict(config=True)
216 218 def _deferred_printers_default(self):
217 219 return {}
218 220
219 221 def __call__(self, obj):
220 222 """Compute the format for an object."""
221 223 if self.enabled:
222 224 obj_id = id(obj)
223 225 try:
224 226 obj_class = getattr(obj, '__class__', None) or type(obj)
225 227 # First try to find registered singleton printers for the type.
226 228 try:
227 229 printer = self.singleton_printers[obj_id]
228 230 except (TypeError, KeyError):
229 231 pass
230 232 else:
231 233 return printer(obj)
232 234 # Next look for type_printers.
233 235 for cls in pretty._get_mro(obj_class):
234 236 if cls in self.type_printers:
235 237 return self.type_printers[cls](obj)
236 238 else:
237 239 printer = self._in_deferred_types(cls)
238 240 if printer is not None:
239 241 return printer(obj)
240 242 # Finally look for special method names.
241 243 if hasattr(obj_class, self.print_method):
242 244 printer = getattr(obj_class, self.print_method)
243 245 return printer(obj)
244 246 return None
245 247 except Exception:
246 248 pass
247 249 else:
248 250 return None
249 251
250 252 def for_type(self, typ, func):
251 253 """Add a format function for a given type.
252 254
253 255 Parameters
254 256 -----------
255 257 typ : class
256 258 The class of the object that will be formatted using `func`.
257 259 func : callable
258 260 The callable that will be called to compute the format data. The
259 261 call signature of this function is simple, it must take the
260 262 object to be formatted and return the raw data for the given
261 263 format. Subclasses may use a different call signature for the
262 264 `func` argument.
263 265 """
264 266 oldfunc = self.type_printers.get(typ, None)
265 267 if func is not None:
266 268 # To support easy restoration of old printers, we need to ignore
267 269 # Nones.
268 270 self.type_printers[typ] = func
269 271 return oldfunc
270 272
271 273 def for_type_by_name(self, type_module, type_name, func):
272 274 """Add a format function for a type specified by the full dotted
273 275 module and name of the type, rather than the type of the object.
274 276
275 277 Parameters
276 278 ----------
277 279 type_module : str
278 280 The full dotted name of the module the type is defined in, like
279 281 ``numpy``.
280 282 type_name : str
281 283 The name of the type (the class name), like ``dtype``
282 284 func : callable
283 285 The callable that will be called to compute the format data. The
284 286 call signature of this function is simple, it must take the
285 287 object to be formatted and return the raw data for the given
286 288 format. Subclasses may use a different call signature for the
287 289 `func` argument.
288 290 """
289 291 key = (type_module, type_name)
290 292 oldfunc = self.deferred_printers.get(key, None)
291 293 if func is not None:
292 294 # To support easy restoration of old printers, we need to ignore
293 295 # Nones.
294 296 self.deferred_printers[key] = func
295 297 return oldfunc
296 298
297 299 def _in_deferred_types(self, cls):
298 300 """
299 301 Check if the given class is specified in the deferred type registry.
300 302
301 303 Returns the printer from the registry if it exists, and None if the
302 304 class is not in the registry. Successful matches will be moved to the
303 305 regular type registry for future use.
304 306 """
305 307 mod = getattr(cls, '__module__', None)
306 308 name = getattr(cls, '__name__', None)
307 309 key = (mod, name)
308 310 printer = None
309 311 if key in self.deferred_printers:
310 312 # Move the printer over to the regular registry.
311 313 printer = self.deferred_printers.pop(key)
312 314 self.type_printers[cls] = printer
313 315 return printer
314 316
315 317
316 318 class PlainTextFormatter(BaseFormatter):
317 319 """The default pretty-printer.
318 320
319 321 This uses :mod:`IPython.external.pretty` to compute the format data of
320 322 the object. If the object cannot be pretty printed, :func:`repr` is used.
321 323 See the documentation of :mod:`IPython.external.pretty` for details on
322 324 how to write pretty printers. Here is a simple example::
323 325
324 326 def dtype_pprinter(obj, p, cycle):
325 327 if cycle:
326 328 return p.text('dtype(...)')
327 329 if hasattr(obj, 'fields'):
328 330 if obj.fields is None:
329 331 p.text(repr(obj))
330 332 else:
331 333 p.begin_group(7, 'dtype([')
332 334 for i, field in enumerate(obj.descr):
333 335 if i > 0:
334 336 p.text(',')
335 337 p.breakable()
336 338 p.pretty(field)
337 339 p.end_group(7, '])')
338 340 """
339 341
340 342 # The format type of data returned.
341 343 format_type = Unicode('text/plain')
342 344
343 345 # This subclass ignores this attribute as it always need to return
344 346 # something.
345 347 enabled = Bool(True, config=False)
346 348
347 349 # Look for a _repr_pretty_ methods to use for pretty printing.
348 350 print_method = ObjectName('_repr_pretty_')
349 351
350 352 # Whether to pretty-print or not.
351 353 pprint = Bool(True, config=True)
352 354
353 355 # Whether to be verbose or not.
354 356 verbose = Bool(False, config=True)
355 357
356 358 # The maximum width.
357 359 max_width = Int(79, config=True)
358 360
359 361 # The newline character.
360 362 newline = Unicode('\n', config=True)
361 363
362 364 # format-string for pprinting floats
363 365 float_format = Unicode('%r')
364 366 # setter for float precision, either int or direct format-string
365 367 float_precision = CUnicode('', config=True)
366 368
367 369 def _float_precision_changed(self, name, old, new):
368 370 """float_precision changed, set float_format accordingly.
369 371
370 372 float_precision can be set by int or str.
371 373 This will set float_format, after interpreting input.
372 374 If numpy has been imported, numpy print precision will also be set.
373 375
374 376 integer `n` sets format to '%.nf', otherwise, format set directly.
375 377
376 378 An empty string returns to defaults (repr for float, 8 for numpy).
377 379
378 380 This parameter can be set via the '%precision' magic.
379 381 """
380 382
381 383 if '%' in new:
382 384 # got explicit format string
383 385 fmt = new
384 386 try:
385 387 fmt%3.14159
386 388 except Exception:
387 389 raise ValueError("Precision must be int or format string, not %r"%new)
388 390 elif new:
389 391 # otherwise, should be an int
390 392 try:
391 393 i = int(new)
392 394 assert i >= 0
393 395 except ValueError:
394 396 raise ValueError("Precision must be int or format string, not %r"%new)
395 397 except AssertionError:
396 398 raise ValueError("int precision must be non-negative, not %r"%i)
397 399
398 400 fmt = '%%.%if'%i
399 401 if 'numpy' in sys.modules:
400 402 # set numpy precision if it has been imported
401 403 import numpy
402 404 numpy.set_printoptions(precision=i)
403 405 else:
404 406 # default back to repr
405 407 fmt = '%r'
406 408 if 'numpy' in sys.modules:
407 409 import numpy
408 410 # numpy default is 8
409 411 numpy.set_printoptions(precision=8)
410 412 self.float_format = fmt
411 413
412 414 # Use the default pretty printers from IPython.external.pretty.
413 415 def _singleton_printers_default(self):
414 416 return pretty._singleton_pprinters.copy()
415 417
416 418 def _type_printers_default(self):
417 419 d = pretty._type_pprinters.copy()
418 420 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
419 421 return d
420 422
421 423 def _deferred_printers_default(self):
422 424 return pretty._deferred_type_pprinters.copy()
423 425
424 426 #### FormatterABC interface ####
425 427
426 428 def __call__(self, obj):
427 429 """Compute the pretty representation of the object."""
428 430 if not self.pprint:
429 431 try:
430 432 return repr(obj)
431 433 except TypeError:
432 434 return ''
433 435 else:
434 436 # This uses use StringIO, as cStringIO doesn't handle unicode.
435 437 stream = StringIO()
436 438 # self.newline.encode() is a quick fix for issue gh-597. We need to
437 439 # ensure that stream does not get a mix of unicode and bytestrings,
438 440 # or it will cause trouble.
439 441 printer = pretty.RepresentationPrinter(stream, self.verbose,
440 442 self.max_width, self.newline.encode(),
441 443 singleton_pprinters=self.singleton_printers,
442 444 type_pprinters=self.type_printers,
443 445 deferred_pprinters=self.deferred_printers)
444 446 printer.pretty(obj)
445 447 printer.flush()
446 448 return stream.getvalue()
447 449
448 450
449 451 class HTMLFormatter(BaseFormatter):
450 452 """An HTML formatter.
451 453
452 454 To define the callables that compute the HTML representation of your
453 455 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
454 456 or :meth:`for_type_by_name` methods to register functions that handle
455 457 this.
456 458
457 459 The return value of this formatter should be a valid HTML snippet that
458 460 could be injected into an existing DOM. It should *not* include the
459 461 ```<html>`` or ```<body>`` tags.
460 462 """
461 463 format_type = Unicode('text/html')
462 464
463 465 print_method = ObjectName('_repr_html_')
464 466
465 467
466 468 class SVGFormatter(BaseFormatter):
467 469 """An SVG formatter.
468 470
469 471 To define the callables that compute the SVG representation of your
470 472 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
471 473 or :meth:`for_type_by_name` methods to register functions that handle
472 474 this.
473 475
474 476 The return value of this formatter should be valid SVG enclosed in
475 477 ```<svg>``` tags, that could be injected into an existing DOM. It should
476 478 *not* include the ```<html>`` or ```<body>`` tags.
477 479 """
478 480 format_type = Unicode('image/svg+xml')
479 481
480 482 print_method = ObjectName('_repr_svg_')
481 483
482 484
483 485 class PNGFormatter(BaseFormatter):
484 486 """A PNG formatter.
485 487
486 488 To define the callables that compute the PNG representation of your
487 489 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
488 490 or :meth:`for_type_by_name` methods to register functions that handle
489 491 this.
490 492
491 493 The return value of this formatter should be raw PNG data, *not*
492 494 base64 encoded.
493 495 """
494 496 format_type = Unicode('image/png')
495 497
496 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 517 class LatexFormatter(BaseFormatter):
500 518 """A LaTeX formatter.
501 519
502 520 To define the callables that compute the LaTeX representation of your
503 521 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
504 522 or :meth:`for_type_by_name` methods to register functions that handle
505 523 this.
506 524
507 525 The return value of this formatter should be a valid LaTeX equation,
508 526 enclosed in either ```$``` or ```$$```.
509 527 """
510 528 format_type = Unicode('text/latex')
511 529
512 530 print_method = ObjectName('_repr_latex_')
513 531
514 532
515 533 class JSONFormatter(BaseFormatter):
516 534 """A JSON string formatter.
517 535
518 536 To define the callables that compute the JSON string representation of
519 537 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
520 538 or :meth:`for_type_by_name` methods to register functions that handle
521 539 this.
522 540
523 541 The return value of this formatter should be a valid JSON string.
524 542 """
525 543 format_type = Unicode('application/json')
526 544
527 545 print_method = ObjectName('_repr_json_')
528 546
529 547
530 548 class JavascriptFormatter(BaseFormatter):
531 549 """A Javascript formatter.
532 550
533 551 To define the callables that compute the Javascript representation of
534 552 your objects, define a :meth:`_repr_javascript_` method or use the
535 553 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
536 554 that handle this.
537 555
538 556 The return value of this formatter should be valid Javascript code and
539 557 should *not* be enclosed in ```<script>``` tags.
540 558 """
541 559 format_type = Unicode('application/javascript')
542 560
543 561 print_method = ObjectName('_repr_javascript_')
544 562
545 563 FormatterABC.register(BaseFormatter)
546 564 FormatterABC.register(PlainTextFormatter)
547 565 FormatterABC.register(HTMLFormatter)
548 566 FormatterABC.register(SVGFormatter)
549 567 FormatterABC.register(PNGFormatter)
568 FormatterABC.register(JPEGFormatter)
550 569 FormatterABC.register(LatexFormatter)
551 570 FormatterABC.register(JSONFormatter)
552 571 FormatterABC.register(JavascriptFormatter)
553 572
554 573
555 574 def format_display_data(obj, include=None, exclude=None):
556 575 """Return a format data dict for an object.
557 576
558 577 By default all format types will be computed.
559 578
560 579 The following MIME types are currently implemented:
561 580
562 581 * text/plain
563 582 * text/html
564 583 * text/latex
565 584 * application/json
566 585 * application/javascript
567 586 * image/png
587 * image/jpeg
568 588 * image/svg+xml
569 589
570 590 Parameters
571 591 ----------
572 592 obj : object
573 593 The Python object whose format data will be computed.
574 594
575 595 Returns
576 596 -------
577 597 format_dict : dict
578 598 A dictionary of key/value pairs, one or each format that was
579 599 generated for the object. The keys are the format types, which
580 600 will usually be MIME type strings and the values and JSON'able
581 601 data structure containing the raw data for the representation in
582 602 that format.
583 603 include : list or tuple, optional
584 604 A list of format type strings (MIME types) to include in the
585 605 format data dict. If this is set *only* the format types included
586 606 in this list will be computed.
587 607 exclude : list or tuple, optional
588 608 A list of format type string (MIME types) to exclue in the format
589 609 data dict. If this is set all format types will be computed,
590 610 except for those included in this argument.
591 611 """
592 612 from IPython.core.interactiveshell import InteractiveShell
593 613
594 614 InteractiveShell.instance().display_formatter.format(
595 615 obj,
596 616 include,
597 617 exclude
598 618 )
619
@@ -1,3563 +1,3564 b''
1 1 # encoding: utf-8
2 2 """Magic functions for InteractiveShell.
3 3 """
4 4
5 5 #-----------------------------------------------------------------------------
6 6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 8 # Copyright (C) 2008-2009 The IPython Development Team
9 9
10 10 # Distributed under the terms of the BSD License. The full license is in
11 11 # the file COPYING, distributed as part of this software.
12 12 #-----------------------------------------------------------------------------
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Imports
16 16 #-----------------------------------------------------------------------------
17 17
18 18 import __builtin__
19 19 import __future__
20 20 import bdb
21 21 import inspect
22 22 import os
23 23 import sys
24 24 import shutil
25 25 import re
26 26 import time
27 27 import textwrap
28 28 from cStringIO import StringIO
29 29 from getopt import getopt,GetoptError
30 30 from pprint import pformat
31 31 from xmlrpclib import ServerProxy
32 32
33 33 # cProfile was added in Python2.5
34 34 try:
35 35 import cProfile as profile
36 36 import pstats
37 37 except ImportError:
38 38 # profile isn't bundled by default in Debian for license reasons
39 39 try:
40 40 import profile,pstats
41 41 except ImportError:
42 42 profile = pstats = None
43 43
44 44 import IPython
45 45 from IPython.core import debugger, oinspect
46 46 from IPython.core.error import TryNext
47 47 from IPython.core.error import UsageError
48 48 from IPython.core.fakemodule import FakeModule
49 49 from IPython.core.profiledir import ProfileDir
50 50 from IPython.core.macro import Macro
51 51 from IPython.core import magic_arguments
52 52 from IPython.core import page
53 53 from IPython.core.prefilter import ESC_MAGIC
54 54 from IPython.lib.pylabtools import mpl_runner
55 55 from IPython.testing.skipdoctest import skip_doctest
56 56 from IPython.utils.io import file_read, nlprint
57 57 from IPython.utils.path import get_py_filename
58 58 from IPython.utils.process import arg_split, abbrev_cwd
59 59 from IPython.utils.terminal import set_term_title
60 60 from IPython.utils.text import LSString, SList, format_screen
61 61 from IPython.utils.timing import clock, clock2
62 62 from IPython.utils.warn import warn, error
63 63 from IPython.utils.ipstruct import Struct
64 64 import IPython.utils.generics
65 65
66 66 #-----------------------------------------------------------------------------
67 67 # Utility functions
68 68 #-----------------------------------------------------------------------------
69 69
70 70 def on_off(tag):
71 71 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
72 72 return ['OFF','ON'][tag]
73 73
74 74 class Bunch: pass
75 75
76 76 def compress_dhist(dh):
77 77 head, tail = dh[:-10], dh[-10:]
78 78
79 79 newhead = []
80 80 done = set()
81 81 for h in head:
82 82 if h in done:
83 83 continue
84 84 newhead.append(h)
85 85 done.add(h)
86 86
87 87 return newhead + tail
88 88
89 89 def needs_local_scope(func):
90 90 """Decorator to mark magic functions which need to local scope to run."""
91 91 func.needs_local_scope = True
92 92 return func
93 93
94 94 # Used for exception handling in magic_edit
95 95 class MacroToEdit(ValueError): pass
96 96
97 97 #***************************************************************************
98 98 # Main class implementing Magic functionality
99 99
100 100 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
101 101 # on construction of the main InteractiveShell object. Something odd is going
102 102 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
103 103 # eventually this needs to be clarified.
104 104 # BG: This is because InteractiveShell inherits from this, but is itself a
105 105 # Configurable. This messes up the MRO in some way. The fix is that we need to
106 106 # make Magic a configurable that InteractiveShell does not subclass.
107 107
108 108 class Magic:
109 109 """Magic functions for InteractiveShell.
110 110
111 111 Shell functions which can be reached as %function_name. All magic
112 112 functions should accept a string, which they can parse for their own
113 113 needs. This can make some functions easier to type, eg `%cd ../`
114 114 vs. `%cd("../")`
115 115
116 116 ALL definitions MUST begin with the prefix magic_. The user won't need it
117 117 at the command line, but it is is needed in the definition. """
118 118
119 119 # class globals
120 120 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
121 121 'Automagic is ON, % prefix NOT needed for magic functions.']
122 122
123 123 #......................................................................
124 124 # some utility functions
125 125
126 126 def __init__(self,shell):
127 127
128 128 self.options_table = {}
129 129 if profile is None:
130 130 self.magic_prun = self.profile_missing_notice
131 131 self.shell = shell
132 132
133 133 # namespace for holding state we may need
134 134 self._magic_state = Bunch()
135 135
136 136 def profile_missing_notice(self, *args, **kwargs):
137 137 error("""\
138 138 The profile module could not be found. It has been removed from the standard
139 139 python packages because of its non-free license. To use profiling, install the
140 140 python-profiler package from non-free.""")
141 141
142 142 def default_option(self,fn,optstr):
143 143 """Make an entry in the options_table for fn, with value optstr"""
144 144
145 145 if fn not in self.lsmagic():
146 146 error("%s is not a magic function" % fn)
147 147 self.options_table[fn] = optstr
148 148
149 149 def lsmagic(self):
150 150 """Return a list of currently available magic functions.
151 151
152 152 Gives a list of the bare names after mangling (['ls','cd', ...], not
153 153 ['magic_ls','magic_cd',...]"""
154 154
155 155 # FIXME. This needs a cleanup, in the way the magics list is built.
156 156
157 157 # magics in class definition
158 158 class_magic = lambda fn: fn.startswith('magic_') and \
159 159 callable(Magic.__dict__[fn])
160 160 # in instance namespace (run-time user additions)
161 161 inst_magic = lambda fn: fn.startswith('magic_') and \
162 162 callable(self.__dict__[fn])
163 163 # and bound magics by user (so they can access self):
164 164 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
165 165 callable(self.__class__.__dict__[fn])
166 166 magics = filter(class_magic,Magic.__dict__.keys()) + \
167 167 filter(inst_magic,self.__dict__.keys()) + \
168 168 filter(inst_bound_magic,self.__class__.__dict__.keys())
169 169 out = []
170 170 for fn in set(magics):
171 171 out.append(fn.replace('magic_','',1))
172 172 out.sort()
173 173 return out
174 174
175 175 def extract_input_lines(self, range_str, raw=False):
176 176 """Return as a string a set of input history slices.
177 177
178 178 Inputs:
179 179
180 180 - range_str: the set of slices is given as a string, like
181 181 "~5/6-~4/2 4:8 9", since this function is for use by magic functions
182 182 which get their arguments as strings. The number before the / is the
183 183 session number: ~n goes n back from the current session.
184 184
185 185 Optional inputs:
186 186
187 187 - raw(False): by default, the processed input is used. If this is
188 188 true, the raw input history is used instead.
189 189
190 190 Note that slices can be called with two notations:
191 191
192 192 N:M -> standard python form, means including items N...(M-1).
193 193
194 194 N-M -> include items N..M (closed endpoint)."""
195 195 lines = self.shell.history_manager.\
196 196 get_range_by_str(range_str, raw=raw)
197 197 return "\n".join(x for _, _, x in lines)
198 198
199 199 def arg_err(self,func):
200 200 """Print docstring if incorrect arguments were passed"""
201 201 print 'Error in arguments:'
202 202 print oinspect.getdoc(func)
203 203
204 204 def format_latex(self,strng):
205 205 """Format a string for latex inclusion."""
206 206
207 207 # Characters that need to be escaped for latex:
208 208 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
209 209 # Magic command names as headers:
210 210 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
211 211 re.MULTILINE)
212 212 # Magic commands
213 213 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
214 214 re.MULTILINE)
215 215 # Paragraph continue
216 216 par_re = re.compile(r'\\$',re.MULTILINE)
217 217
218 218 # The "\n" symbol
219 219 newline_re = re.compile(r'\\n')
220 220
221 221 # Now build the string for output:
222 222 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
223 223 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
224 224 strng)
225 225 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
226 226 strng = par_re.sub(r'\\\\',strng)
227 227 strng = escape_re.sub(r'\\\1',strng)
228 228 strng = newline_re.sub(r'\\textbackslash{}n',strng)
229 229 return strng
230 230
231 231 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
232 232 """Parse options passed to an argument string.
233 233
234 234 The interface is similar to that of getopt(), but it returns back a
235 235 Struct with the options as keys and the stripped argument string still
236 236 as a string.
237 237
238 238 arg_str is quoted as a true sys.argv vector by using shlex.split.
239 239 This allows us to easily expand variables, glob files, quote
240 240 arguments, etc.
241 241
242 242 Options:
243 243 -mode: default 'string'. If given as 'list', the argument string is
244 244 returned as a list (split on whitespace) instead of a string.
245 245
246 246 -list_all: put all option values in lists. Normally only options
247 247 appearing more than once are put in a list.
248 248
249 249 -posix (True): whether to split the input line in POSIX mode or not,
250 250 as per the conventions outlined in the shlex module from the
251 251 standard library."""
252 252
253 253 # inject default options at the beginning of the input line
254 254 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
255 255 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
256 256
257 257 mode = kw.get('mode','string')
258 258 if mode not in ['string','list']:
259 259 raise ValueError,'incorrect mode given: %s' % mode
260 260 # Get options
261 261 list_all = kw.get('list_all',0)
262 262 posix = kw.get('posix', os.name == 'posix')
263 263
264 264 # Check if we have more than one argument to warrant extra processing:
265 265 odict = {} # Dictionary with options
266 266 args = arg_str.split()
267 267 if len(args) >= 1:
268 268 # If the list of inputs only has 0 or 1 thing in it, there's no
269 269 # need to look for options
270 270 argv = arg_split(arg_str,posix)
271 271 # Do regular option processing
272 272 try:
273 273 opts,args = getopt(argv,opt_str,*long_opts)
274 274 except GetoptError,e:
275 275 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
276 276 " ".join(long_opts)))
277 277 for o,a in opts:
278 278 if o.startswith('--'):
279 279 o = o[2:]
280 280 else:
281 281 o = o[1:]
282 282 try:
283 283 odict[o].append(a)
284 284 except AttributeError:
285 285 odict[o] = [odict[o],a]
286 286 except KeyError:
287 287 if list_all:
288 288 odict[o] = [a]
289 289 else:
290 290 odict[o] = a
291 291
292 292 # Prepare opts,args for return
293 293 opts = Struct(odict)
294 294 if mode == 'string':
295 295 args = ' '.join(args)
296 296
297 297 return opts,args
298 298
299 299 #......................................................................
300 300 # And now the actual magic functions
301 301
302 302 # Functions for IPython shell work (vars,funcs, config, etc)
303 303 def magic_lsmagic(self, parameter_s = ''):
304 304 """List currently available magic functions."""
305 305 mesc = ESC_MAGIC
306 306 print 'Available magic functions:\n'+mesc+\
307 307 (' '+mesc).join(self.lsmagic())
308 308 print '\n' + Magic.auto_status[self.shell.automagic]
309 309 return None
310 310
311 311 def magic_magic(self, parameter_s = ''):
312 312 """Print information about the magic function system.
313 313
314 314 Supported formats: -latex, -brief, -rest
315 315 """
316 316
317 317 mode = ''
318 318 try:
319 319 if parameter_s.split()[0] == '-latex':
320 320 mode = 'latex'
321 321 if parameter_s.split()[0] == '-brief':
322 322 mode = 'brief'
323 323 if parameter_s.split()[0] == '-rest':
324 324 mode = 'rest'
325 325 rest_docs = []
326 326 except:
327 327 pass
328 328
329 329 magic_docs = []
330 330 for fname in self.lsmagic():
331 331 mname = 'magic_' + fname
332 332 for space in (Magic,self,self.__class__):
333 333 try:
334 334 fn = space.__dict__[mname]
335 335 except KeyError:
336 336 pass
337 337 else:
338 338 break
339 339 if mode == 'brief':
340 340 # only first line
341 341 if fn.__doc__:
342 342 fndoc = fn.__doc__.split('\n',1)[0]
343 343 else:
344 344 fndoc = 'No documentation'
345 345 else:
346 346 if fn.__doc__:
347 347 fndoc = fn.__doc__.rstrip()
348 348 else:
349 349 fndoc = 'No documentation'
350 350
351 351
352 352 if mode == 'rest':
353 353 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
354 354 fname,fndoc))
355 355
356 356 else:
357 357 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
358 358 fname,fndoc))
359 359
360 360 magic_docs = ''.join(magic_docs)
361 361
362 362 if mode == 'rest':
363 363 return "".join(rest_docs)
364 364
365 365 if mode == 'latex':
366 366 print self.format_latex(magic_docs)
367 367 return
368 368 else:
369 369 magic_docs = format_screen(magic_docs)
370 370 if mode == 'brief':
371 371 return magic_docs
372 372
373 373 outmsg = """
374 374 IPython's 'magic' functions
375 375 ===========================
376 376
377 377 The magic function system provides a series of functions which allow you to
378 378 control the behavior of IPython itself, plus a lot of system-type
379 379 features. All these functions are prefixed with a % character, but parameters
380 380 are given without parentheses or quotes.
381 381
382 382 NOTE: If you have 'automagic' enabled (via the command line option or with the
383 383 %automagic function), you don't need to type in the % explicitly. By default,
384 384 IPython ships with automagic on, so you should only rarely need the % escape.
385 385
386 386 Example: typing '%cd mydir' (without the quotes) changes you working directory
387 387 to 'mydir', if it exists.
388 388
389 389 For a list of the available magic functions, use %lsmagic. For a description
390 390 of any of them, type %magic_name?, e.g. '%cd?'.
391 391
392 392 Currently the magic system has the following functions:\n"""
393 393
394 394 mesc = ESC_MAGIC
395 395 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
396 396 "\n\n%s%s\n\n%s" % (outmsg,
397 397 magic_docs,mesc,mesc,
398 398 (' '+mesc).join(self.lsmagic()),
399 399 Magic.auto_status[self.shell.automagic] ) )
400 400 page.page(outmsg)
401 401
402 402 def magic_automagic(self, parameter_s = ''):
403 403 """Make magic functions callable without having to type the initial %.
404 404
405 405 Without argumentsl toggles on/off (when off, you must call it as
406 406 %automagic, of course). With arguments it sets the value, and you can
407 407 use any of (case insensitive):
408 408
409 409 - on,1,True: to activate
410 410
411 411 - off,0,False: to deactivate.
412 412
413 413 Note that magic functions have lowest priority, so if there's a
414 414 variable whose name collides with that of a magic fn, automagic won't
415 415 work for that function (you get the variable instead). However, if you
416 416 delete the variable (del var), the previously shadowed magic function
417 417 becomes visible to automagic again."""
418 418
419 419 arg = parameter_s.lower()
420 420 if parameter_s in ('on','1','true'):
421 421 self.shell.automagic = True
422 422 elif parameter_s in ('off','0','false'):
423 423 self.shell.automagic = False
424 424 else:
425 425 self.shell.automagic = not self.shell.automagic
426 426 print '\n' + Magic.auto_status[self.shell.automagic]
427 427
428 428 @skip_doctest
429 429 def magic_autocall(self, parameter_s = ''):
430 430 """Make functions callable without having to type parentheses.
431 431
432 432 Usage:
433 433
434 434 %autocall [mode]
435 435
436 436 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
437 437 value is toggled on and off (remembering the previous state).
438 438
439 439 In more detail, these values mean:
440 440
441 441 0 -> fully disabled
442 442
443 443 1 -> active, but do not apply if there are no arguments on the line.
444 444
445 445 In this mode, you get:
446 446
447 447 In [1]: callable
448 448 Out[1]: <built-in function callable>
449 449
450 450 In [2]: callable 'hello'
451 451 ------> callable('hello')
452 452 Out[2]: False
453 453
454 454 2 -> Active always. Even if no arguments are present, the callable
455 455 object is called:
456 456
457 457 In [2]: float
458 458 ------> float()
459 459 Out[2]: 0.0
460 460
461 461 Note that even with autocall off, you can still use '/' at the start of
462 462 a line to treat the first argument on the command line as a function
463 463 and add parentheses to it:
464 464
465 465 In [8]: /str 43
466 466 ------> str(43)
467 467 Out[8]: '43'
468 468
469 469 # all-random (note for auto-testing)
470 470 """
471 471
472 472 if parameter_s:
473 473 arg = int(parameter_s)
474 474 else:
475 475 arg = 'toggle'
476 476
477 477 if not arg in (0,1,2,'toggle'):
478 478 error('Valid modes: (0->Off, 1->Smart, 2->Full')
479 479 return
480 480
481 481 if arg in (0,1,2):
482 482 self.shell.autocall = arg
483 483 else: # toggle
484 484 if self.shell.autocall:
485 485 self._magic_state.autocall_save = self.shell.autocall
486 486 self.shell.autocall = 0
487 487 else:
488 488 try:
489 489 self.shell.autocall = self._magic_state.autocall_save
490 490 except AttributeError:
491 491 self.shell.autocall = self._magic_state.autocall_save = 1
492 492
493 493 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
494 494
495 495
496 496 def magic_page(self, parameter_s=''):
497 497 """Pretty print the object and display it through a pager.
498 498
499 499 %page [options] OBJECT
500 500
501 501 If no object is given, use _ (last output).
502 502
503 503 Options:
504 504
505 505 -r: page str(object), don't pretty-print it."""
506 506
507 507 # After a function contributed by Olivier Aubert, slightly modified.
508 508
509 509 # Process options/args
510 510 opts,args = self.parse_options(parameter_s,'r')
511 511 raw = 'r' in opts
512 512
513 513 oname = args and args or '_'
514 514 info = self._ofind(oname)
515 515 if info['found']:
516 516 txt = (raw and str or pformat)( info['obj'] )
517 517 page.page(txt)
518 518 else:
519 519 print 'Object `%s` not found' % oname
520 520
521 521 def magic_profile(self, parameter_s=''):
522 522 """Print your currently active IPython profile."""
523 523 print self.shell.profile
524 524
525 525 def magic_pinfo(self, parameter_s='', namespaces=None):
526 526 """Provide detailed information about an object.
527 527
528 528 '%pinfo object' is just a synonym for object? or ?object."""
529 529
530 530 #print 'pinfo par: <%s>' % parameter_s # dbg
531 531
532 532
533 533 # detail_level: 0 -> obj? , 1 -> obj??
534 534 detail_level = 0
535 535 # We need to detect if we got called as 'pinfo pinfo foo', which can
536 536 # happen if the user types 'pinfo foo?' at the cmd line.
537 537 pinfo,qmark1,oname,qmark2 = \
538 538 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
539 539 if pinfo or qmark1 or qmark2:
540 540 detail_level = 1
541 541 if "*" in oname:
542 542 self.magic_psearch(oname)
543 543 else:
544 544 self.shell._inspect('pinfo', oname, detail_level=detail_level,
545 545 namespaces=namespaces)
546 546
547 547 def magic_pinfo2(self, parameter_s='', namespaces=None):
548 548 """Provide extra detailed information about an object.
549 549
550 550 '%pinfo2 object' is just a synonym for object?? or ??object."""
551 551 self.shell._inspect('pinfo', parameter_s, detail_level=1,
552 552 namespaces=namespaces)
553 553
554 554 @skip_doctest
555 555 def magic_pdef(self, parameter_s='', namespaces=None):
556 556 """Print the definition header for any callable object.
557 557
558 558 If the object is a class, print the constructor information.
559 559
560 560 Examples
561 561 --------
562 562 ::
563 563
564 564 In [3]: %pdef urllib.urlopen
565 565 urllib.urlopen(url, data=None, proxies=None)
566 566 """
567 567 self._inspect('pdef',parameter_s, namespaces)
568 568
569 569 def magic_pdoc(self, parameter_s='', namespaces=None):
570 570 """Print the docstring for an object.
571 571
572 572 If the given object is a class, it will print both the class and the
573 573 constructor docstrings."""
574 574 self._inspect('pdoc',parameter_s, namespaces)
575 575
576 576 def magic_psource(self, parameter_s='', namespaces=None):
577 577 """Print (or run through pager) the source code for an object."""
578 578 self._inspect('psource',parameter_s, namespaces)
579 579
580 580 def magic_pfile(self, parameter_s=''):
581 581 """Print (or run through pager) the file where an object is defined.
582 582
583 583 The file opens at the line where the object definition begins. IPython
584 584 will honor the environment variable PAGER if set, and otherwise will
585 585 do its best to print the file in a convenient form.
586 586
587 587 If the given argument is not an object currently defined, IPython will
588 588 try to interpret it as a filename (automatically adding a .py extension
589 589 if needed). You can thus use %pfile as a syntax highlighting code
590 590 viewer."""
591 591
592 592 # first interpret argument as an object name
593 593 out = self._inspect('pfile',parameter_s)
594 594 # if not, try the input as a filename
595 595 if out == 'not found':
596 596 try:
597 597 filename = get_py_filename(parameter_s)
598 598 except IOError,msg:
599 599 print msg
600 600 return
601 601 page.page(self.shell.inspector.format(file(filename).read()))
602 602
603 603 def magic_psearch(self, parameter_s=''):
604 604 """Search for object in namespaces by wildcard.
605 605
606 606 %psearch [options] PATTERN [OBJECT TYPE]
607 607
608 608 Note: ? can be used as a synonym for %psearch, at the beginning or at
609 609 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
610 610 rest of the command line must be unchanged (options come first), so
611 611 for example the following forms are equivalent
612 612
613 613 %psearch -i a* function
614 614 -i a* function?
615 615 ?-i a* function
616 616
617 617 Arguments:
618 618
619 619 PATTERN
620 620
621 621 where PATTERN is a string containing * as a wildcard similar to its
622 622 use in a shell. The pattern is matched in all namespaces on the
623 623 search path. By default objects starting with a single _ are not
624 624 matched, many IPython generated objects have a single
625 625 underscore. The default is case insensitive matching. Matching is
626 626 also done on the attributes of objects and not only on the objects
627 627 in a module.
628 628
629 629 [OBJECT TYPE]
630 630
631 631 Is the name of a python type from the types module. The name is
632 632 given in lowercase without the ending type, ex. StringType is
633 633 written string. By adding a type here only objects matching the
634 634 given type are matched. Using all here makes the pattern match all
635 635 types (this is the default).
636 636
637 637 Options:
638 638
639 639 -a: makes the pattern match even objects whose names start with a
640 640 single underscore. These names are normally ommitted from the
641 641 search.
642 642
643 643 -i/-c: make the pattern case insensitive/sensitive. If neither of
644 644 these options is given, the default is read from your ipythonrc
645 645 file. The option name which sets this value is
646 646 'wildcards_case_sensitive'. If this option is not specified in your
647 647 ipythonrc file, IPython's internal default is to do a case sensitive
648 648 search.
649 649
650 650 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
651 651 specifiy can be searched in any of the following namespaces:
652 652 'builtin', 'user', 'user_global','internal', 'alias', where
653 653 'builtin' and 'user' are the search defaults. Note that you should
654 654 not use quotes when specifying namespaces.
655 655
656 656 'Builtin' contains the python module builtin, 'user' contains all
657 657 user data, 'alias' only contain the shell aliases and no python
658 658 objects, 'internal' contains objects used by IPython. The
659 659 'user_global' namespace is only used by embedded IPython instances,
660 660 and it contains module-level globals. You can add namespaces to the
661 661 search with -s or exclude them with -e (these options can be given
662 662 more than once).
663 663
664 664 Examples:
665 665
666 666 %psearch a* -> objects beginning with an a
667 667 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
668 668 %psearch a* function -> all functions beginning with an a
669 669 %psearch re.e* -> objects beginning with an e in module re
670 670 %psearch r*.e* -> objects that start with e in modules starting in r
671 671 %psearch r*.* string -> all strings in modules beginning with r
672 672
673 673 Case sensitve search:
674 674
675 675 %psearch -c a* list all object beginning with lower case a
676 676
677 677 Show objects beginning with a single _:
678 678
679 679 %psearch -a _* list objects beginning with a single underscore"""
680 680 try:
681 681 parameter_s = parameter_s.encode('ascii')
682 682 except UnicodeEncodeError:
683 683 print 'Python identifiers can only contain ascii characters.'
684 684 return
685 685
686 686 # default namespaces to be searched
687 687 def_search = ['user','builtin']
688 688
689 689 # Process options/args
690 690 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
691 691 opt = opts.get
692 692 shell = self.shell
693 693 psearch = shell.inspector.psearch
694 694
695 695 # select case options
696 696 if opts.has_key('i'):
697 697 ignore_case = True
698 698 elif opts.has_key('c'):
699 699 ignore_case = False
700 700 else:
701 701 ignore_case = not shell.wildcards_case_sensitive
702 702
703 703 # Build list of namespaces to search from user options
704 704 def_search.extend(opt('s',[]))
705 705 ns_exclude = ns_exclude=opt('e',[])
706 706 ns_search = [nm for nm in def_search if nm not in ns_exclude]
707 707
708 708 # Call the actual search
709 709 try:
710 710 psearch(args,shell.ns_table,ns_search,
711 711 show_all=opt('a'),ignore_case=ignore_case)
712 712 except:
713 713 shell.showtraceback()
714 714
715 715 @skip_doctest
716 716 def magic_who_ls(self, parameter_s=''):
717 717 """Return a sorted list of all interactive variables.
718 718
719 719 If arguments are given, only variables of types matching these
720 720 arguments are returned.
721 721
722 722 Examples
723 723 --------
724 724
725 725 Define two variables and list them with who_ls::
726 726
727 727 In [1]: alpha = 123
728 728
729 729 In [2]: beta = 'test'
730 730
731 731 In [3]: %who_ls
732 732 Out[3]: ['alpha', 'beta']
733 733
734 734 In [4]: %who_ls int
735 735 Out[4]: ['alpha']
736 736
737 737 In [5]: %who_ls str
738 738 Out[5]: ['beta']
739 739 """
740 740
741 741 user_ns = self.shell.user_ns
742 742 internal_ns = self.shell.internal_ns
743 743 user_ns_hidden = self.shell.user_ns_hidden
744 744 out = [ i for i in user_ns
745 745 if not i.startswith('_') \
746 746 and not (i in internal_ns or i in user_ns_hidden) ]
747 747
748 748 typelist = parameter_s.split()
749 749 if typelist:
750 750 typeset = set(typelist)
751 751 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
752 752
753 753 out.sort()
754 754 return out
755 755
756 756 @skip_doctest
757 757 def magic_who(self, parameter_s=''):
758 758 """Print all interactive variables, with some minimal formatting.
759 759
760 760 If any arguments are given, only variables whose type matches one of
761 761 these are printed. For example:
762 762
763 763 %who function str
764 764
765 765 will only list functions and strings, excluding all other types of
766 766 variables. To find the proper type names, simply use type(var) at a
767 767 command line to see how python prints type names. For example:
768 768
769 769 In [1]: type('hello')\\
770 770 Out[1]: <type 'str'>
771 771
772 772 indicates that the type name for strings is 'str'.
773 773
774 774 %who always excludes executed names loaded through your configuration
775 775 file and things which are internal to IPython.
776 776
777 777 This is deliberate, as typically you may load many modules and the
778 778 purpose of %who is to show you only what you've manually defined.
779 779
780 780 Examples
781 781 --------
782 782
783 783 Define two variables and list them with who::
784 784
785 785 In [1]: alpha = 123
786 786
787 787 In [2]: beta = 'test'
788 788
789 789 In [3]: %who
790 790 alpha beta
791 791
792 792 In [4]: %who int
793 793 alpha
794 794
795 795 In [5]: %who str
796 796 beta
797 797 """
798 798
799 799 varlist = self.magic_who_ls(parameter_s)
800 800 if not varlist:
801 801 if parameter_s:
802 802 print 'No variables match your requested type.'
803 803 else:
804 804 print 'Interactive namespace is empty.'
805 805 return
806 806
807 807 # if we have variables, move on...
808 808 count = 0
809 809 for i in varlist:
810 810 print i+'\t',
811 811 count += 1
812 812 if count > 8:
813 813 count = 0
814 814 print
815 815 print
816 816
817 817 @skip_doctest
818 818 def magic_whos(self, parameter_s=''):
819 819 """Like %who, but gives some extra information about each variable.
820 820
821 821 The same type filtering of %who can be applied here.
822 822
823 823 For all variables, the type is printed. Additionally it prints:
824 824
825 825 - For {},[],(): their length.
826 826
827 827 - For numpy arrays, a summary with shape, number of
828 828 elements, typecode and size in memory.
829 829
830 830 - Everything else: a string representation, snipping their middle if
831 831 too long.
832 832
833 833 Examples
834 834 --------
835 835
836 836 Define two variables and list them with whos::
837 837
838 838 In [1]: alpha = 123
839 839
840 840 In [2]: beta = 'test'
841 841
842 842 In [3]: %whos
843 843 Variable Type Data/Info
844 844 --------------------------------
845 845 alpha int 123
846 846 beta str test
847 847 """
848 848
849 849 varnames = self.magic_who_ls(parameter_s)
850 850 if not varnames:
851 851 if parameter_s:
852 852 print 'No variables match your requested type.'
853 853 else:
854 854 print 'Interactive namespace is empty.'
855 855 return
856 856
857 857 # if we have variables, move on...
858 858
859 859 # for these types, show len() instead of data:
860 860 seq_types = ['dict', 'list', 'tuple']
861 861
862 862 # for numpy/Numeric arrays, display summary info
863 863 try:
864 864 import numpy
865 865 except ImportError:
866 866 ndarray_type = None
867 867 else:
868 868 ndarray_type = numpy.ndarray.__name__
869 869 try:
870 870 import Numeric
871 871 except ImportError:
872 872 array_type = None
873 873 else:
874 874 array_type = Numeric.ArrayType.__name__
875 875
876 876 # Find all variable names and types so we can figure out column sizes
877 877 def get_vars(i):
878 878 return self.shell.user_ns[i]
879 879
880 880 # some types are well known and can be shorter
881 881 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
882 882 def type_name(v):
883 883 tn = type(v).__name__
884 884 return abbrevs.get(tn,tn)
885 885
886 886 varlist = map(get_vars,varnames)
887 887
888 888 typelist = []
889 889 for vv in varlist:
890 890 tt = type_name(vv)
891 891
892 892 if tt=='instance':
893 893 typelist.append( abbrevs.get(str(vv.__class__),
894 894 str(vv.__class__)))
895 895 else:
896 896 typelist.append(tt)
897 897
898 898 # column labels and # of spaces as separator
899 899 varlabel = 'Variable'
900 900 typelabel = 'Type'
901 901 datalabel = 'Data/Info'
902 902 colsep = 3
903 903 # variable format strings
904 904 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
905 905 aformat = "%s: %s elems, type `%s`, %s bytes"
906 906 # find the size of the columns to format the output nicely
907 907 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
908 908 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
909 909 # table header
910 910 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
911 911 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
912 912 # and the table itself
913 913 kb = 1024
914 914 Mb = 1048576 # kb**2
915 915 for vname,var,vtype in zip(varnames,varlist,typelist):
916 916 print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth),
917 917 if vtype in seq_types:
918 918 print "n="+str(len(var))
919 919 elif vtype in [array_type,ndarray_type]:
920 920 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
921 921 if vtype==ndarray_type:
922 922 # numpy
923 923 vsize = var.size
924 924 vbytes = vsize*var.itemsize
925 925 vdtype = var.dtype
926 926 else:
927 927 # Numeric
928 928 vsize = Numeric.size(var)
929 929 vbytes = vsize*var.itemsize()
930 930 vdtype = var.typecode()
931 931
932 932 if vbytes < 100000:
933 933 print aformat % (vshape,vsize,vdtype,vbytes)
934 934 else:
935 935 print aformat % (vshape,vsize,vdtype,vbytes),
936 936 if vbytes < Mb:
937 937 print '(%s kb)' % (vbytes/kb,)
938 938 else:
939 939 print '(%s Mb)' % (vbytes/Mb,)
940 940 else:
941 941 try:
942 942 vstr = str(var)
943 943 except UnicodeEncodeError:
944 944 vstr = unicode(var).encode(sys.getdefaultencoding(),
945 945 'backslashreplace')
946 946 vstr = vstr.replace('\n','\\n')
947 947 if len(vstr) < 50:
948 948 print vstr
949 949 else:
950 950 print vstr[:25] + "<...>" + vstr[-25:]
951 951
952 952 def magic_reset(self, parameter_s=''):
953 953 """Resets the namespace by removing all names defined by the user.
954 954
955 955 Parameters
956 956 ----------
957 957 -f : force reset without asking for confirmation.
958 958
959 959 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
960 960 References to objects may be kept. By default (without this option),
961 961 we do a 'hard' reset, giving you a new session and removing all
962 962 references to objects from the current session.
963 963
964 964 Examples
965 965 --------
966 966 In [6]: a = 1
967 967
968 968 In [7]: a
969 969 Out[7]: 1
970 970
971 971 In [8]: 'a' in _ip.user_ns
972 972 Out[8]: True
973 973
974 974 In [9]: %reset -f
975 975
976 976 In [1]: 'a' in _ip.user_ns
977 977 Out[1]: False
978 978 """
979 979 opts, args = self.parse_options(parameter_s,'sf')
980 980 if 'f' in opts:
981 981 ans = True
982 982 else:
983 983 ans = self.shell.ask_yes_no(
984 984 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
985 985 if not ans:
986 986 print 'Nothing done.'
987 987 return
988 988
989 989 if 's' in opts: # Soft reset
990 990 user_ns = self.shell.user_ns
991 991 for i in self.magic_who_ls():
992 992 del(user_ns[i])
993 993
994 994 else: # Hard reset
995 995 self.shell.reset(new_session = False)
996 996
997 997
998 998
999 999 def magic_reset_selective(self, parameter_s=''):
1000 1000 """Resets the namespace by removing names defined by the user.
1001 1001
1002 1002 Input/Output history are left around in case you need them.
1003 1003
1004 1004 %reset_selective [-f] regex
1005 1005
1006 1006 No action is taken if regex is not included
1007 1007
1008 1008 Options
1009 1009 -f : force reset without asking for confirmation.
1010 1010
1011 1011 Examples
1012 1012 --------
1013 1013
1014 1014 We first fully reset the namespace so your output looks identical to
1015 1015 this example for pedagogical reasons; in practice you do not need a
1016 1016 full reset.
1017 1017
1018 1018 In [1]: %reset -f
1019 1019
1020 1020 Now, with a clean namespace we can make a few variables and use
1021 1021 %reset_selective to only delete names that match our regexp:
1022 1022
1023 1023 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1024 1024
1025 1025 In [3]: who_ls
1026 1026 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1027 1027
1028 1028 In [4]: %reset_selective -f b[2-3]m
1029 1029
1030 1030 In [5]: who_ls
1031 1031 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1032 1032
1033 1033 In [6]: %reset_selective -f d
1034 1034
1035 1035 In [7]: who_ls
1036 1036 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1037 1037
1038 1038 In [8]: %reset_selective -f c
1039 1039
1040 1040 In [9]: who_ls
1041 1041 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1042 1042
1043 1043 In [10]: %reset_selective -f b
1044 1044
1045 1045 In [11]: who_ls
1046 1046 Out[11]: ['a']
1047 1047 """
1048 1048
1049 1049 opts, regex = self.parse_options(parameter_s,'f')
1050 1050
1051 1051 if opts.has_key('f'):
1052 1052 ans = True
1053 1053 else:
1054 1054 ans = self.shell.ask_yes_no(
1055 1055 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1056 1056 if not ans:
1057 1057 print 'Nothing done.'
1058 1058 return
1059 1059 user_ns = self.shell.user_ns
1060 1060 if not regex:
1061 1061 print 'No regex pattern specified. Nothing done.'
1062 1062 return
1063 1063 else:
1064 1064 try:
1065 1065 m = re.compile(regex)
1066 1066 except TypeError:
1067 1067 raise TypeError('regex must be a string or compiled pattern')
1068 1068 for i in self.magic_who_ls():
1069 1069 if m.search(i):
1070 1070 del(user_ns[i])
1071 1071
1072 1072 def magic_xdel(self, parameter_s=''):
1073 1073 """Delete a variable, trying to clear it from anywhere that
1074 1074 IPython's machinery has references to it. By default, this uses
1075 1075 the identity of the named object in the user namespace to remove
1076 1076 references held under other names. The object is also removed
1077 1077 from the output history.
1078 1078
1079 1079 Options
1080 1080 -n : Delete the specified name from all namespaces, without
1081 1081 checking their identity.
1082 1082 """
1083 1083 opts, varname = self.parse_options(parameter_s,'n')
1084 1084 try:
1085 1085 self.shell.del_var(varname, ('n' in opts))
1086 1086 except (NameError, ValueError) as e:
1087 1087 print type(e).__name__ +": "+ str(e)
1088 1088
1089 1089 def magic_logstart(self,parameter_s=''):
1090 1090 """Start logging anywhere in a session.
1091 1091
1092 1092 %logstart [-o|-r|-t] [log_name [log_mode]]
1093 1093
1094 1094 If no name is given, it defaults to a file named 'ipython_log.py' in your
1095 1095 current directory, in 'rotate' mode (see below).
1096 1096
1097 1097 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1098 1098 history up to that point and then continues logging.
1099 1099
1100 1100 %logstart takes a second optional parameter: logging mode. This can be one
1101 1101 of (note that the modes are given unquoted):\\
1102 1102 append: well, that says it.\\
1103 1103 backup: rename (if exists) to name~ and start name.\\
1104 1104 global: single logfile in your home dir, appended to.\\
1105 1105 over : overwrite existing log.\\
1106 1106 rotate: create rotating logs name.1~, name.2~, etc.
1107 1107
1108 1108 Options:
1109 1109
1110 1110 -o: log also IPython's output. In this mode, all commands which
1111 1111 generate an Out[NN] prompt are recorded to the logfile, right after
1112 1112 their corresponding input line. The output lines are always
1113 1113 prepended with a '#[Out]# ' marker, so that the log remains valid
1114 1114 Python code.
1115 1115
1116 1116 Since this marker is always the same, filtering only the output from
1117 1117 a log is very easy, using for example a simple awk call:
1118 1118
1119 1119 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1120 1120
1121 1121 -r: log 'raw' input. Normally, IPython's logs contain the processed
1122 1122 input, so that user lines are logged in their final form, converted
1123 1123 into valid Python. For example, %Exit is logged as
1124 1124 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1125 1125 exactly as typed, with no transformations applied.
1126 1126
1127 1127 -t: put timestamps before each input line logged (these are put in
1128 1128 comments)."""
1129 1129
1130 1130 opts,par = self.parse_options(parameter_s,'ort')
1131 1131 log_output = 'o' in opts
1132 1132 log_raw_input = 'r' in opts
1133 1133 timestamp = 't' in opts
1134 1134
1135 1135 logger = self.shell.logger
1136 1136
1137 1137 # if no args are given, the defaults set in the logger constructor by
1138 1138 # ipytohn remain valid
1139 1139 if par:
1140 1140 try:
1141 1141 logfname,logmode = par.split()
1142 1142 except:
1143 1143 logfname = par
1144 1144 logmode = 'backup'
1145 1145 else:
1146 1146 logfname = logger.logfname
1147 1147 logmode = logger.logmode
1148 1148 # put logfname into rc struct as if it had been called on the command
1149 1149 # line, so it ends up saved in the log header Save it in case we need
1150 1150 # to restore it...
1151 1151 old_logfile = self.shell.logfile
1152 1152 if logfname:
1153 1153 logfname = os.path.expanduser(logfname)
1154 1154 self.shell.logfile = logfname
1155 1155
1156 1156 loghead = '# IPython log file\n\n'
1157 1157 try:
1158 1158 started = logger.logstart(logfname,loghead,logmode,
1159 1159 log_output,timestamp,log_raw_input)
1160 1160 except:
1161 1161 self.shell.logfile = old_logfile
1162 1162 warn("Couldn't start log: %s" % sys.exc_info()[1])
1163 1163 else:
1164 1164 # log input history up to this point, optionally interleaving
1165 1165 # output if requested
1166 1166
1167 1167 if timestamp:
1168 1168 # disable timestamping for the previous history, since we've
1169 1169 # lost those already (no time machine here).
1170 1170 logger.timestamp = False
1171 1171
1172 1172 if log_raw_input:
1173 1173 input_hist = self.shell.history_manager.input_hist_raw
1174 1174 else:
1175 1175 input_hist = self.shell.history_manager.input_hist_parsed
1176 1176
1177 1177 if log_output:
1178 1178 log_write = logger.log_write
1179 1179 output_hist = self.shell.history_manager.output_hist
1180 1180 for n in range(1,len(input_hist)-1):
1181 1181 log_write(input_hist[n].rstrip() + '\n')
1182 1182 if n in output_hist:
1183 1183 log_write(repr(output_hist[n]),'output')
1184 1184 else:
1185 1185 logger.log_write('\n'.join(input_hist[1:]))
1186 1186 logger.log_write('\n')
1187 1187 if timestamp:
1188 1188 # re-enable timestamping
1189 1189 logger.timestamp = True
1190 1190
1191 1191 print ('Activating auto-logging. '
1192 1192 'Current session state plus future input saved.')
1193 1193 logger.logstate()
1194 1194
1195 1195 def magic_logstop(self,parameter_s=''):
1196 1196 """Fully stop logging and close log file.
1197 1197
1198 1198 In order to start logging again, a new %logstart call needs to be made,
1199 1199 possibly (though not necessarily) with a new filename, mode and other
1200 1200 options."""
1201 1201 self.logger.logstop()
1202 1202
1203 1203 def magic_logoff(self,parameter_s=''):
1204 1204 """Temporarily stop logging.
1205 1205
1206 1206 You must have previously started logging."""
1207 1207 self.shell.logger.switch_log(0)
1208 1208
1209 1209 def magic_logon(self,parameter_s=''):
1210 1210 """Restart logging.
1211 1211
1212 1212 This function is for restarting logging which you've temporarily
1213 1213 stopped with %logoff. For starting logging for the first time, you
1214 1214 must use the %logstart function, which allows you to specify an
1215 1215 optional log filename."""
1216 1216
1217 1217 self.shell.logger.switch_log(1)
1218 1218
1219 1219 def magic_logstate(self,parameter_s=''):
1220 1220 """Print the status of the logging system."""
1221 1221
1222 1222 self.shell.logger.logstate()
1223 1223
1224 1224 def magic_pdb(self, parameter_s=''):
1225 1225 """Control the automatic calling of the pdb interactive debugger.
1226 1226
1227 1227 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1228 1228 argument it works as a toggle.
1229 1229
1230 1230 When an exception is triggered, IPython can optionally call the
1231 1231 interactive pdb debugger after the traceback printout. %pdb toggles
1232 1232 this feature on and off.
1233 1233
1234 1234 The initial state of this feature is set in your ipythonrc
1235 1235 configuration file (the variable is called 'pdb').
1236 1236
1237 1237 If you want to just activate the debugger AFTER an exception has fired,
1238 1238 without having to type '%pdb on' and rerunning your code, you can use
1239 1239 the %debug magic."""
1240 1240
1241 1241 par = parameter_s.strip().lower()
1242 1242
1243 1243 if par:
1244 1244 try:
1245 1245 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1246 1246 except KeyError:
1247 1247 print ('Incorrect argument. Use on/1, off/0, '
1248 1248 'or nothing for a toggle.')
1249 1249 return
1250 1250 else:
1251 1251 # toggle
1252 1252 new_pdb = not self.shell.call_pdb
1253 1253
1254 1254 # set on the shell
1255 1255 self.shell.call_pdb = new_pdb
1256 1256 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1257 1257
1258 1258 def magic_debug(self, parameter_s=''):
1259 1259 """Activate the interactive debugger in post-mortem mode.
1260 1260
1261 1261 If an exception has just occurred, this lets you inspect its stack
1262 1262 frames interactively. Note that this will always work only on the last
1263 1263 traceback that occurred, so you must call this quickly after an
1264 1264 exception that you wish to inspect has fired, because if another one
1265 1265 occurs, it clobbers the previous one.
1266 1266
1267 1267 If you want IPython to automatically do this on every exception, see
1268 1268 the %pdb magic for more details.
1269 1269 """
1270 1270 self.shell.debugger(force=True)
1271 1271
1272 1272 @skip_doctest
1273 1273 def magic_prun(self, parameter_s ='',user_mode=1,
1274 1274 opts=None,arg_lst=None,prog_ns=None):
1275 1275
1276 1276 """Run a statement through the python code profiler.
1277 1277
1278 1278 Usage:
1279 1279 %prun [options] statement
1280 1280
1281 1281 The given statement (which doesn't require quote marks) is run via the
1282 1282 python profiler in a manner similar to the profile.run() function.
1283 1283 Namespaces are internally managed to work correctly; profile.run
1284 1284 cannot be used in IPython because it makes certain assumptions about
1285 1285 namespaces which do not hold under IPython.
1286 1286
1287 1287 Options:
1288 1288
1289 1289 -l <limit>: you can place restrictions on what or how much of the
1290 1290 profile gets printed. The limit value can be:
1291 1291
1292 1292 * A string: only information for function names containing this string
1293 1293 is printed.
1294 1294
1295 1295 * An integer: only these many lines are printed.
1296 1296
1297 1297 * A float (between 0 and 1): this fraction of the report is printed
1298 1298 (for example, use a limit of 0.4 to see the topmost 40% only).
1299 1299
1300 1300 You can combine several limits with repeated use of the option. For
1301 1301 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1302 1302 information about class constructors.
1303 1303
1304 1304 -r: return the pstats.Stats object generated by the profiling. This
1305 1305 object has all the information about the profile in it, and you can
1306 1306 later use it for further analysis or in other functions.
1307 1307
1308 1308 -s <key>: sort profile by given key. You can provide more than one key
1309 1309 by using the option several times: '-s key1 -s key2 -s key3...'. The
1310 1310 default sorting key is 'time'.
1311 1311
1312 1312 The following is copied verbatim from the profile documentation
1313 1313 referenced below:
1314 1314
1315 1315 When more than one key is provided, additional keys are used as
1316 1316 secondary criteria when the there is equality in all keys selected
1317 1317 before them.
1318 1318
1319 1319 Abbreviations can be used for any key names, as long as the
1320 1320 abbreviation is unambiguous. The following are the keys currently
1321 1321 defined:
1322 1322
1323 1323 Valid Arg Meaning
1324 1324 "calls" call count
1325 1325 "cumulative" cumulative time
1326 1326 "file" file name
1327 1327 "module" file name
1328 1328 "pcalls" primitive call count
1329 1329 "line" line number
1330 1330 "name" function name
1331 1331 "nfl" name/file/line
1332 1332 "stdname" standard name
1333 1333 "time" internal time
1334 1334
1335 1335 Note that all sorts on statistics are in descending order (placing
1336 1336 most time consuming items first), where as name, file, and line number
1337 1337 searches are in ascending order (i.e., alphabetical). The subtle
1338 1338 distinction between "nfl" and "stdname" is that the standard name is a
1339 1339 sort of the name as printed, which means that the embedded line
1340 1340 numbers get compared in an odd way. For example, lines 3, 20, and 40
1341 1341 would (if the file names were the same) appear in the string order
1342 1342 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1343 1343 line numbers. In fact, sort_stats("nfl") is the same as
1344 1344 sort_stats("name", "file", "line").
1345 1345
1346 1346 -T <filename>: save profile results as shown on screen to a text
1347 1347 file. The profile is still shown on screen.
1348 1348
1349 1349 -D <filename>: save (via dump_stats) profile statistics to given
1350 1350 filename. This data is in a format understod by the pstats module, and
1351 1351 is generated by a call to the dump_stats() method of profile
1352 1352 objects. The profile is still shown on screen.
1353 1353
1354 1354 If you want to run complete programs under the profiler's control, use
1355 1355 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1356 1356 contains profiler specific options as described here.
1357 1357
1358 1358 You can read the complete documentation for the profile module with::
1359 1359
1360 1360 In [1]: import profile; profile.help()
1361 1361 """
1362 1362
1363 1363 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1364 1364 # protect user quote marks
1365 1365 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1366 1366
1367 1367 if user_mode: # regular user call
1368 1368 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1369 1369 list_all=1)
1370 1370 namespace = self.shell.user_ns
1371 1371 else: # called to run a program by %run -p
1372 1372 try:
1373 1373 filename = get_py_filename(arg_lst[0])
1374 1374 except IOError,msg:
1375 1375 error(msg)
1376 1376 return
1377 1377
1378 1378 arg_str = 'execfile(filename,prog_ns)'
1379 1379 namespace = locals()
1380 1380
1381 1381 opts.merge(opts_def)
1382 1382
1383 1383 prof = profile.Profile()
1384 1384 try:
1385 1385 prof = prof.runctx(arg_str,namespace,namespace)
1386 1386 sys_exit = ''
1387 1387 except SystemExit:
1388 1388 sys_exit = """*** SystemExit exception caught in code being profiled."""
1389 1389
1390 1390 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1391 1391
1392 1392 lims = opts.l
1393 1393 if lims:
1394 1394 lims = [] # rebuild lims with ints/floats/strings
1395 1395 for lim in opts.l:
1396 1396 try:
1397 1397 lims.append(int(lim))
1398 1398 except ValueError:
1399 1399 try:
1400 1400 lims.append(float(lim))
1401 1401 except ValueError:
1402 1402 lims.append(lim)
1403 1403
1404 1404 # Trap output.
1405 1405 stdout_trap = StringIO()
1406 1406
1407 1407 if hasattr(stats,'stream'):
1408 1408 # In newer versions of python, the stats object has a 'stream'
1409 1409 # attribute to write into.
1410 1410 stats.stream = stdout_trap
1411 1411 stats.print_stats(*lims)
1412 1412 else:
1413 1413 # For older versions, we manually redirect stdout during printing
1414 1414 sys_stdout = sys.stdout
1415 1415 try:
1416 1416 sys.stdout = stdout_trap
1417 1417 stats.print_stats(*lims)
1418 1418 finally:
1419 1419 sys.stdout = sys_stdout
1420 1420
1421 1421 output = stdout_trap.getvalue()
1422 1422 output = output.rstrip()
1423 1423
1424 1424 page.page(output)
1425 1425 print sys_exit,
1426 1426
1427 1427 dump_file = opts.D[0]
1428 1428 text_file = opts.T[0]
1429 1429 if dump_file:
1430 1430 prof.dump_stats(dump_file)
1431 1431 print '\n*** Profile stats marshalled to file',\
1432 1432 `dump_file`+'.',sys_exit
1433 1433 if text_file:
1434 1434 pfile = file(text_file,'w')
1435 1435 pfile.write(output)
1436 1436 pfile.close()
1437 1437 print '\n*** Profile printout saved to text file',\
1438 1438 `text_file`+'.',sys_exit
1439 1439
1440 1440 if opts.has_key('r'):
1441 1441 return stats
1442 1442 else:
1443 1443 return None
1444 1444
1445 1445 @skip_doctest
1446 1446 def magic_run(self, parameter_s ='',runner=None,
1447 1447 file_finder=get_py_filename):
1448 1448 """Run the named file inside IPython as a program.
1449 1449
1450 1450 Usage:\\
1451 1451 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1452 1452
1453 1453 Parameters after the filename are passed as command-line arguments to
1454 1454 the program (put in sys.argv). Then, control returns to IPython's
1455 1455 prompt.
1456 1456
1457 1457 This is similar to running at a system prompt:\\
1458 1458 $ python file args\\
1459 1459 but with the advantage of giving you IPython's tracebacks, and of
1460 1460 loading all variables into your interactive namespace for further use
1461 1461 (unless -p is used, see below).
1462 1462
1463 1463 The file is executed in a namespace initially consisting only of
1464 1464 __name__=='__main__' and sys.argv constructed as indicated. It thus
1465 1465 sees its environment as if it were being run as a stand-alone program
1466 1466 (except for sharing global objects such as previously imported
1467 1467 modules). But after execution, the IPython interactive namespace gets
1468 1468 updated with all variables defined in the program (except for __name__
1469 1469 and sys.argv). This allows for very convenient loading of code for
1470 1470 interactive work, while giving each program a 'clean sheet' to run in.
1471 1471
1472 1472 Options:
1473 1473
1474 1474 -n: __name__ is NOT set to '__main__', but to the running file's name
1475 1475 without extension (as python does under import). This allows running
1476 1476 scripts and reloading the definitions in them without calling code
1477 1477 protected by an ' if __name__ == "__main__" ' clause.
1478 1478
1479 1479 -i: run the file in IPython's namespace instead of an empty one. This
1480 1480 is useful if you are experimenting with code written in a text editor
1481 1481 which depends on variables defined interactively.
1482 1482
1483 1483 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1484 1484 being run. This is particularly useful if IPython is being used to
1485 1485 run unittests, which always exit with a sys.exit() call. In such
1486 1486 cases you are interested in the output of the test results, not in
1487 1487 seeing a traceback of the unittest module.
1488 1488
1489 1489 -t: print timing information at the end of the run. IPython will give
1490 1490 you an estimated CPU time consumption for your script, which under
1491 1491 Unix uses the resource module to avoid the wraparound problems of
1492 1492 time.clock(). Under Unix, an estimate of time spent on system tasks
1493 1493 is also given (for Windows platforms this is reported as 0.0).
1494 1494
1495 1495 If -t is given, an additional -N<N> option can be given, where <N>
1496 1496 must be an integer indicating how many times you want the script to
1497 1497 run. The final timing report will include total and per run results.
1498 1498
1499 1499 For example (testing the script uniq_stable.py):
1500 1500
1501 1501 In [1]: run -t uniq_stable
1502 1502
1503 1503 IPython CPU timings (estimated):\\
1504 1504 User : 0.19597 s.\\
1505 1505 System: 0.0 s.\\
1506 1506
1507 1507 In [2]: run -t -N5 uniq_stable
1508 1508
1509 1509 IPython CPU timings (estimated):\\
1510 1510 Total runs performed: 5\\
1511 1511 Times : Total Per run\\
1512 1512 User : 0.910862 s, 0.1821724 s.\\
1513 1513 System: 0.0 s, 0.0 s.
1514 1514
1515 1515 -d: run your program under the control of pdb, the Python debugger.
1516 1516 This allows you to execute your program step by step, watch variables,
1517 1517 etc. Internally, what IPython does is similar to calling:
1518 1518
1519 1519 pdb.run('execfile("YOURFILENAME")')
1520 1520
1521 1521 with a breakpoint set on line 1 of your file. You can change the line
1522 1522 number for this automatic breakpoint to be <N> by using the -bN option
1523 1523 (where N must be an integer). For example:
1524 1524
1525 1525 %run -d -b40 myscript
1526 1526
1527 1527 will set the first breakpoint at line 40 in myscript.py. Note that
1528 1528 the first breakpoint must be set on a line which actually does
1529 1529 something (not a comment or docstring) for it to stop execution.
1530 1530
1531 1531 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1532 1532 first enter 'c' (without qoutes) to start execution up to the first
1533 1533 breakpoint.
1534 1534
1535 1535 Entering 'help' gives information about the use of the debugger. You
1536 1536 can easily see pdb's full documentation with "import pdb;pdb.help()"
1537 1537 at a prompt.
1538 1538
1539 1539 -p: run program under the control of the Python profiler module (which
1540 1540 prints a detailed report of execution times, function calls, etc).
1541 1541
1542 1542 You can pass other options after -p which affect the behavior of the
1543 1543 profiler itself. See the docs for %prun for details.
1544 1544
1545 1545 In this mode, the program's variables do NOT propagate back to the
1546 1546 IPython interactive namespace (because they remain in the namespace
1547 1547 where the profiler executes them).
1548 1548
1549 1549 Internally this triggers a call to %prun, see its documentation for
1550 1550 details on the options available specifically for profiling.
1551 1551
1552 1552 There is one special usage for which the text above doesn't apply:
1553 1553 if the filename ends with .ipy, the file is run as ipython script,
1554 1554 just as if the commands were written on IPython prompt.
1555 1555 """
1556 1556
1557 1557 # get arguments and set sys.argv for program to be run.
1558 1558 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1559 1559 mode='list',list_all=1)
1560 1560
1561 1561 try:
1562 1562 filename = file_finder(arg_lst[0])
1563 1563 except IndexError:
1564 1564 warn('you must provide at least a filename.')
1565 1565 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1566 1566 return
1567 1567 except IOError,msg:
1568 1568 error(msg)
1569 1569 return
1570 1570
1571 1571 if filename.lower().endswith('.ipy'):
1572 1572 self.shell.safe_execfile_ipy(filename)
1573 1573 return
1574 1574
1575 1575 # Control the response to exit() calls made by the script being run
1576 1576 exit_ignore = opts.has_key('e')
1577 1577
1578 1578 # Make sure that the running script gets a proper sys.argv as if it
1579 1579 # were run from a system shell.
1580 1580 save_argv = sys.argv # save it for later restoring
1581 1581
1582 1582 # simulate shell expansion on arguments, at least tilde expansion
1583 1583 args = [ os.path.expanduser(a) for a in arg_lst[1:] ]
1584 1584
1585 1585 sys.argv = [filename]+ args # put in the proper filename
1586 1586
1587 1587 if opts.has_key('i'):
1588 1588 # Run in user's interactive namespace
1589 1589 prog_ns = self.shell.user_ns
1590 1590 __name__save = self.shell.user_ns['__name__']
1591 1591 prog_ns['__name__'] = '__main__'
1592 1592 main_mod = self.shell.new_main_mod(prog_ns)
1593 1593 else:
1594 1594 # Run in a fresh, empty namespace
1595 1595 if opts.has_key('n'):
1596 1596 name = os.path.splitext(os.path.basename(filename))[0]
1597 1597 else:
1598 1598 name = '__main__'
1599 1599
1600 1600 main_mod = self.shell.new_main_mod()
1601 1601 prog_ns = main_mod.__dict__
1602 1602 prog_ns['__name__'] = name
1603 1603
1604 1604 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1605 1605 # set the __file__ global in the script's namespace
1606 1606 prog_ns['__file__'] = filename
1607 1607
1608 1608 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1609 1609 # that, if we overwrite __main__, we replace it at the end
1610 1610 main_mod_name = prog_ns['__name__']
1611 1611
1612 1612 if main_mod_name == '__main__':
1613 1613 restore_main = sys.modules['__main__']
1614 1614 else:
1615 1615 restore_main = False
1616 1616
1617 1617 # This needs to be undone at the end to prevent holding references to
1618 1618 # every single object ever created.
1619 1619 sys.modules[main_mod_name] = main_mod
1620 1620
1621 1621 try:
1622 1622 stats = None
1623 1623 with self.readline_no_record:
1624 1624 if opts.has_key('p'):
1625 1625 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1626 1626 else:
1627 1627 if opts.has_key('d'):
1628 1628 deb = debugger.Pdb(self.shell.colors)
1629 1629 # reset Breakpoint state, which is moronically kept
1630 1630 # in a class
1631 1631 bdb.Breakpoint.next = 1
1632 1632 bdb.Breakpoint.bplist = {}
1633 1633 bdb.Breakpoint.bpbynumber = [None]
1634 1634 # Set an initial breakpoint to stop execution
1635 1635 maxtries = 10
1636 1636 bp = int(opts.get('b',[1])[0])
1637 1637 checkline = deb.checkline(filename,bp)
1638 1638 if not checkline:
1639 1639 for bp in range(bp+1,bp+maxtries+1):
1640 1640 if deb.checkline(filename,bp):
1641 1641 break
1642 1642 else:
1643 1643 msg = ("\nI failed to find a valid line to set "
1644 1644 "a breakpoint\n"
1645 1645 "after trying up to line: %s.\n"
1646 1646 "Please set a valid breakpoint manually "
1647 1647 "with the -b option." % bp)
1648 1648 error(msg)
1649 1649 return
1650 1650 # if we find a good linenumber, set the breakpoint
1651 1651 deb.do_break('%s:%s' % (filename,bp))
1652 1652 # Start file run
1653 1653 print "NOTE: Enter 'c' at the",
1654 1654 print "%s prompt to start your script." % deb.prompt
1655 1655 try:
1656 1656 deb.run('execfile("%s")' % filename,prog_ns)
1657 1657
1658 1658 except:
1659 1659 etype, value, tb = sys.exc_info()
1660 1660 # Skip three frames in the traceback: the %run one,
1661 1661 # one inside bdb.py, and the command-line typed by the
1662 1662 # user (run by exec in pdb itself).
1663 1663 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1664 1664 else:
1665 1665 if runner is None:
1666 1666 runner = self.shell.safe_execfile
1667 1667 if opts.has_key('t'):
1668 1668 # timed execution
1669 1669 try:
1670 1670 nruns = int(opts['N'][0])
1671 1671 if nruns < 1:
1672 1672 error('Number of runs must be >=1')
1673 1673 return
1674 1674 except (KeyError):
1675 1675 nruns = 1
1676 1676 twall0 = time.time()
1677 1677 if nruns == 1:
1678 1678 t0 = clock2()
1679 1679 runner(filename,prog_ns,prog_ns,
1680 1680 exit_ignore=exit_ignore)
1681 1681 t1 = clock2()
1682 1682 t_usr = t1[0]-t0[0]
1683 1683 t_sys = t1[1]-t0[1]
1684 1684 print "\nIPython CPU timings (estimated):"
1685 1685 print " User : %10.2f s." % t_usr
1686 1686 print " System : %10.2f s." % t_sys
1687 1687 else:
1688 1688 runs = range(nruns)
1689 1689 t0 = clock2()
1690 1690 for nr in runs:
1691 1691 runner(filename,prog_ns,prog_ns,
1692 1692 exit_ignore=exit_ignore)
1693 1693 t1 = clock2()
1694 1694 t_usr = t1[0]-t0[0]
1695 1695 t_sys = t1[1]-t0[1]
1696 1696 print "\nIPython CPU timings (estimated):"
1697 1697 print "Total runs performed:",nruns
1698 1698 print " Times : %10.2f %10.2f" % ('Total','Per run')
1699 1699 print " User : %10.2f s, %10.2f s." % (t_usr,t_usr/nruns)
1700 1700 print " System : %10.2f s, %10.2f s." % (t_sys,t_sys/nruns)
1701 1701 twall1 = time.time()
1702 1702 print "Wall time: %10.2f s." % (twall1-twall0)
1703 1703
1704 1704 else:
1705 1705 # regular execution
1706 1706 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1707 1707
1708 1708 if opts.has_key('i'):
1709 1709 self.shell.user_ns['__name__'] = __name__save
1710 1710 else:
1711 1711 # The shell MUST hold a reference to prog_ns so after %run
1712 1712 # exits, the python deletion mechanism doesn't zero it out
1713 1713 # (leaving dangling references).
1714 1714 self.shell.cache_main_mod(prog_ns,filename)
1715 1715 # update IPython interactive namespace
1716 1716
1717 1717 # Some forms of read errors on the file may mean the
1718 1718 # __name__ key was never set; using pop we don't have to
1719 1719 # worry about a possible KeyError.
1720 1720 prog_ns.pop('__name__', None)
1721 1721
1722 1722 self.shell.user_ns.update(prog_ns)
1723 1723 finally:
1724 1724 # It's a bit of a mystery why, but __builtins__ can change from
1725 1725 # being a module to becoming a dict missing some key data after
1726 1726 # %run. As best I can see, this is NOT something IPython is doing
1727 1727 # at all, and similar problems have been reported before:
1728 1728 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1729 1729 # Since this seems to be done by the interpreter itself, the best
1730 1730 # we can do is to at least restore __builtins__ for the user on
1731 1731 # exit.
1732 1732 self.shell.user_ns['__builtins__'] = __builtin__
1733 1733
1734 1734 # Ensure key global structures are restored
1735 1735 sys.argv = save_argv
1736 1736 if restore_main:
1737 1737 sys.modules['__main__'] = restore_main
1738 1738 else:
1739 1739 # Remove from sys.modules the reference to main_mod we'd
1740 1740 # added. Otherwise it will trap references to objects
1741 1741 # contained therein.
1742 1742 del sys.modules[main_mod_name]
1743 1743
1744 1744 return stats
1745 1745
1746 1746 @skip_doctest
1747 1747 def magic_timeit(self, parameter_s =''):
1748 1748 """Time execution of a Python statement or expression
1749 1749
1750 1750 Usage:\\
1751 1751 %timeit [-n<N> -r<R> [-t|-c]] statement
1752 1752
1753 1753 Time execution of a Python statement or expression using the timeit
1754 1754 module.
1755 1755
1756 1756 Options:
1757 1757 -n<N>: execute the given statement <N> times in a loop. If this value
1758 1758 is not given, a fitting value is chosen.
1759 1759
1760 1760 -r<R>: repeat the loop iteration <R> times and take the best result.
1761 1761 Default: 3
1762 1762
1763 1763 -t: use time.time to measure the time, which is the default on Unix.
1764 1764 This function measures wall time.
1765 1765
1766 1766 -c: use time.clock to measure the time, which is the default on
1767 1767 Windows and measures wall time. On Unix, resource.getrusage is used
1768 1768 instead and returns the CPU user time.
1769 1769
1770 1770 -p<P>: use a precision of <P> digits to display the timing result.
1771 1771 Default: 3
1772 1772
1773 1773
1774 1774 Examples:
1775 1775
1776 1776 In [1]: %timeit pass
1777 1777 10000000 loops, best of 3: 53.3 ns per loop
1778 1778
1779 1779 In [2]: u = None
1780 1780
1781 1781 In [3]: %timeit u is None
1782 1782 10000000 loops, best of 3: 184 ns per loop
1783 1783
1784 1784 In [4]: %timeit -r 4 u == None
1785 1785 1000000 loops, best of 4: 242 ns per loop
1786 1786
1787 1787 In [5]: import time
1788 1788
1789 1789 In [6]: %timeit -n1 time.sleep(2)
1790 1790 1 loops, best of 3: 2 s per loop
1791 1791
1792 1792
1793 1793 The times reported by %timeit will be slightly higher than those
1794 1794 reported by the timeit.py script when variables are accessed. This is
1795 1795 due to the fact that %timeit executes the statement in the namespace
1796 1796 of the shell, compared with timeit.py, which uses a single setup
1797 1797 statement to import function or create variables. Generally, the bias
1798 1798 does not matter as long as results from timeit.py are not mixed with
1799 1799 those from %timeit."""
1800 1800
1801 1801 import timeit
1802 1802 import math
1803 1803
1804 1804 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1805 1805 # certain terminals. Until we figure out a robust way of
1806 1806 # auto-detecting if the terminal can deal with it, use plain 'us' for
1807 1807 # microseconds. I am really NOT happy about disabling the proper
1808 1808 # 'micro' prefix, but crashing is worse... If anyone knows what the
1809 1809 # right solution for this is, I'm all ears...
1810 1810 #
1811 1811 # Note: using
1812 1812 #
1813 1813 # s = u'\xb5'
1814 1814 # s.encode(sys.getdefaultencoding())
1815 1815 #
1816 1816 # is not sufficient, as I've seen terminals where that fails but
1817 1817 # print s
1818 1818 #
1819 1819 # succeeds
1820 1820 #
1821 1821 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1822 1822
1823 1823 #units = [u"s", u"ms",u'\xb5',"ns"]
1824 1824 units = [u"s", u"ms",u'us',"ns"]
1825 1825
1826 1826 scaling = [1, 1e3, 1e6, 1e9]
1827 1827
1828 1828 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1829 1829 posix=False)
1830 1830 if stmt == "":
1831 1831 return
1832 1832 timefunc = timeit.default_timer
1833 1833 number = int(getattr(opts, "n", 0))
1834 1834 repeat = int(getattr(opts, "r", timeit.default_repeat))
1835 1835 precision = int(getattr(opts, "p", 3))
1836 1836 if hasattr(opts, "t"):
1837 1837 timefunc = time.time
1838 1838 if hasattr(opts, "c"):
1839 1839 timefunc = clock
1840 1840
1841 1841 timer = timeit.Timer(timer=timefunc)
1842 1842 # this code has tight coupling to the inner workings of timeit.Timer,
1843 1843 # but is there a better way to achieve that the code stmt has access
1844 1844 # to the shell namespace?
1845 1845
1846 1846 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1847 1847 'setup': "pass"}
1848 1848 # Track compilation time so it can be reported if too long
1849 1849 # Minimum time above which compilation time will be reported
1850 1850 tc_min = 0.1
1851 1851
1852 1852 t0 = clock()
1853 1853 code = compile(src, "<magic-timeit>", "exec")
1854 1854 tc = clock()-t0
1855 1855
1856 1856 ns = {}
1857 1857 exec code in self.shell.user_ns, ns
1858 1858 timer.inner = ns["inner"]
1859 1859
1860 1860 if number == 0:
1861 1861 # determine number so that 0.2 <= total time < 2.0
1862 1862 number = 1
1863 1863 for i in range(1, 10):
1864 1864 if timer.timeit(number) >= 0.2:
1865 1865 break
1866 1866 number *= 10
1867 1867
1868 1868 best = min(timer.repeat(repeat, number)) / number
1869 1869
1870 1870 if best > 0.0 and best < 1000.0:
1871 1871 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1872 1872 elif best >= 1000.0:
1873 1873 order = 0
1874 1874 else:
1875 1875 order = 3
1876 1876 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1877 1877 precision,
1878 1878 best * scaling[order],
1879 1879 units[order])
1880 1880 if tc > tc_min:
1881 1881 print "Compiler time: %.2f s" % tc
1882 1882
1883 1883 @skip_doctest
1884 1884 @needs_local_scope
1885 1885 def magic_time(self,parameter_s = ''):
1886 1886 """Time execution of a Python statement or expression.
1887 1887
1888 1888 The CPU and wall clock times are printed, and the value of the
1889 1889 expression (if any) is returned. Note that under Win32, system time
1890 1890 is always reported as 0, since it can not be measured.
1891 1891
1892 1892 This function provides very basic timing functionality. In Python
1893 1893 2.3, the timeit module offers more control and sophistication, so this
1894 1894 could be rewritten to use it (patches welcome).
1895 1895
1896 1896 Some examples:
1897 1897
1898 1898 In [1]: time 2**128
1899 1899 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1900 1900 Wall time: 0.00
1901 1901 Out[1]: 340282366920938463463374607431768211456L
1902 1902
1903 1903 In [2]: n = 1000000
1904 1904
1905 1905 In [3]: time sum(range(n))
1906 1906 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1907 1907 Wall time: 1.37
1908 1908 Out[3]: 499999500000L
1909 1909
1910 1910 In [4]: time print 'hello world'
1911 1911 hello world
1912 1912 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1913 1913 Wall time: 0.00
1914 1914
1915 1915 Note that the time needed by Python to compile the given expression
1916 1916 will be reported if it is more than 0.1s. In this example, the
1917 1917 actual exponentiation is done by Python at compilation time, so while
1918 1918 the expression can take a noticeable amount of time to compute, that
1919 1919 time is purely due to the compilation:
1920 1920
1921 1921 In [5]: time 3**9999;
1922 1922 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1923 1923 Wall time: 0.00 s
1924 1924
1925 1925 In [6]: time 3**999999;
1926 1926 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1927 1927 Wall time: 0.00 s
1928 1928 Compiler : 0.78 s
1929 1929 """
1930 1930
1931 1931 # fail immediately if the given expression can't be compiled
1932 1932
1933 1933 expr = self.shell.prefilter(parameter_s,False)
1934 1934
1935 1935 # Minimum time above which compilation time will be reported
1936 1936 tc_min = 0.1
1937 1937
1938 1938 try:
1939 1939 mode = 'eval'
1940 1940 t0 = clock()
1941 1941 code = compile(expr,'<timed eval>',mode)
1942 1942 tc = clock()-t0
1943 1943 except SyntaxError:
1944 1944 mode = 'exec'
1945 1945 t0 = clock()
1946 1946 code = compile(expr,'<timed exec>',mode)
1947 1947 tc = clock()-t0
1948 1948 # skew measurement as little as possible
1949 1949 glob = self.shell.user_ns
1950 1950 locs = self._magic_locals
1951 1951 clk = clock2
1952 1952 wtime = time.time
1953 1953 # time execution
1954 1954 wall_st = wtime()
1955 1955 if mode=='eval':
1956 1956 st = clk()
1957 1957 out = eval(code, glob, locs)
1958 1958 end = clk()
1959 1959 else:
1960 1960 st = clk()
1961 1961 exec code in glob, locs
1962 1962 end = clk()
1963 1963 out = None
1964 1964 wall_end = wtime()
1965 1965 # Compute actual times and report
1966 1966 wall_time = wall_end-wall_st
1967 1967 cpu_user = end[0]-st[0]
1968 1968 cpu_sys = end[1]-st[1]
1969 1969 cpu_tot = cpu_user+cpu_sys
1970 1970 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1971 1971 (cpu_user,cpu_sys,cpu_tot)
1972 1972 print "Wall time: %.2f s" % wall_time
1973 1973 if tc > tc_min:
1974 1974 print "Compiler : %.2f s" % tc
1975 1975 return out
1976 1976
1977 1977 @skip_doctest
1978 1978 def magic_macro(self,parameter_s = ''):
1979 1979 """Define a macro for future re-execution. It accepts ranges of history,
1980 1980 filenames or string objects.
1981 1981
1982 1982 Usage:\\
1983 1983 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1984 1984
1985 1985 Options:
1986 1986
1987 1987 -r: use 'raw' input. By default, the 'processed' history is used,
1988 1988 so that magics are loaded in their transformed version to valid
1989 1989 Python. If this option is given, the raw input as typed as the
1990 1990 command line is used instead.
1991 1991
1992 1992 This will define a global variable called `name` which is a string
1993 1993 made of joining the slices and lines you specify (n1,n2,... numbers
1994 1994 above) from your input history into a single string. This variable
1995 1995 acts like an automatic function which re-executes those lines as if
1996 1996 you had typed them. You just type 'name' at the prompt and the code
1997 1997 executes.
1998 1998
1999 1999 The syntax for indicating input ranges is described in %history.
2000 2000
2001 2001 Note: as a 'hidden' feature, you can also use traditional python slice
2002 2002 notation, where N:M means numbers N through M-1.
2003 2003
2004 2004 For example, if your history contains (%hist prints it):
2005 2005
2006 2006 44: x=1
2007 2007 45: y=3
2008 2008 46: z=x+y
2009 2009 47: print x
2010 2010 48: a=5
2011 2011 49: print 'x',x,'y',y
2012 2012
2013 2013 you can create a macro with lines 44 through 47 (included) and line 49
2014 2014 called my_macro with:
2015 2015
2016 2016 In [55]: %macro my_macro 44-47 49
2017 2017
2018 2018 Now, typing `my_macro` (without quotes) will re-execute all this code
2019 2019 in one pass.
2020 2020
2021 2021 You don't need to give the line-numbers in order, and any given line
2022 2022 number can appear multiple times. You can assemble macros with any
2023 2023 lines from your input history in any order.
2024 2024
2025 2025 The macro is a simple object which holds its value in an attribute,
2026 2026 but IPython's display system checks for macros and executes them as
2027 2027 code instead of printing them when you type their name.
2028 2028
2029 2029 You can view a macro's contents by explicitly printing it with:
2030 2030
2031 2031 'print macro_name'.
2032 2032
2033 2033 """
2034 2034 opts,args = self.parse_options(parameter_s,'r',mode='list')
2035 2035 if not args: # List existing macros
2036 2036 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2037 2037 isinstance(v, Macro))
2038 2038 if len(args) == 1:
2039 2039 raise UsageError(
2040 2040 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2041 2041 name, codefrom = args[0], " ".join(args[1:])
2042 2042
2043 2043 #print 'rng',ranges # dbg
2044 2044 try:
2045 2045 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2046 2046 except (ValueError, TypeError) as e:
2047 2047 print e.args[0]
2048 2048 return
2049 2049 macro = Macro(lines)
2050 2050 self.shell.define_macro(name, macro)
2051 2051 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2052 2052 print '=== Macro contents: ==='
2053 2053 print macro,
2054 2054
2055 2055 def magic_save(self,parameter_s = ''):
2056 2056 """Save a set of lines or a macro to a given filename.
2057 2057
2058 2058 Usage:\\
2059 2059 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2060 2060
2061 2061 Options:
2062 2062
2063 2063 -r: use 'raw' input. By default, the 'processed' history is used,
2064 2064 so that magics are loaded in their transformed version to valid
2065 2065 Python. If this option is given, the raw input as typed as the
2066 2066 command line is used instead.
2067 2067
2068 2068 This function uses the same syntax as %history for input ranges,
2069 2069 then saves the lines to the filename you specify.
2070 2070
2071 2071 It adds a '.py' extension to the file if you don't do so yourself, and
2072 2072 it asks for confirmation before overwriting existing files."""
2073 2073
2074 2074 opts,args = self.parse_options(parameter_s,'r',mode='list')
2075 2075 fname, codefrom = args[0], " ".join(args[1:])
2076 2076 if not fname.endswith('.py'):
2077 2077 fname += '.py'
2078 2078 if os.path.isfile(fname):
2079 2079 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2080 2080 if ans.lower() not in ['y','yes']:
2081 2081 print 'Operation cancelled.'
2082 2082 return
2083 2083 try:
2084 2084 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2085 2085 except (TypeError, ValueError) as e:
2086 2086 print e.args[0]
2087 2087 return
2088 2088 if isinstance(cmds, unicode):
2089 2089 cmds = cmds.encode("utf-8")
2090 2090 with open(fname,'w') as f:
2091 2091 f.write("# coding: utf-8\n")
2092 2092 f.write(cmds)
2093 2093 print 'The following commands were written to file `%s`:' % fname
2094 2094 print cmds
2095 2095
2096 2096 def magic_pastebin(self, parameter_s = ''):
2097 2097 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2098 2098 try:
2099 2099 code = self.shell.find_user_code(parameter_s)
2100 2100 except (ValueError, TypeError) as e:
2101 2101 print e.args[0]
2102 2102 return
2103 2103 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2104 2104 id = pbserver.pastes.newPaste("python", code)
2105 2105 return "http://paste.pocoo.org/show/" + id
2106 2106
2107 2107 def magic_loadpy(self, arg_s):
2108 2108 """Load a .py python script into the GUI console.
2109 2109
2110 2110 This magic command can either take a local filename or a url::
2111 2111
2112 2112 %loadpy myscript.py
2113 2113 %loadpy http://www.example.com/myscript.py
2114 2114 """
2115 2115 if not arg_s.endswith('.py'):
2116 2116 raise ValueError('%%load only works with .py files: %s' % arg_s)
2117 2117 if arg_s.startswith('http'):
2118 2118 import urllib2
2119 2119 response = urllib2.urlopen(arg_s)
2120 2120 content = response.read()
2121 2121 else:
2122 content = open(arg_s).read()
2122 with open(arg_s) as f:
2123 content = f.read()
2123 2124 self.set_next_input(content)
2124 2125
2125 2126 def _find_edit_target(self, args, opts, last_call):
2126 2127 """Utility method used by magic_edit to find what to edit."""
2127 2128
2128 2129 def make_filename(arg):
2129 2130 "Make a filename from the given args"
2130 2131 try:
2131 2132 filename = get_py_filename(arg)
2132 2133 except IOError:
2133 2134 # If it ends with .py but doesn't already exist, assume we want
2134 2135 # a new file.
2135 2136 if args.endswith('.py'):
2136 2137 filename = arg
2137 2138 else:
2138 2139 filename = None
2139 2140 return filename
2140 2141
2141 2142 # Set a few locals from the options for convenience:
2142 2143 opts_prev = 'p' in opts
2143 2144 opts_raw = 'r' in opts
2144 2145
2145 2146 # custom exceptions
2146 2147 class DataIsObject(Exception): pass
2147 2148
2148 2149 # Default line number value
2149 2150 lineno = opts.get('n',None)
2150 2151
2151 2152 if opts_prev:
2152 2153 args = '_%s' % last_call[0]
2153 2154 if not self.shell.user_ns.has_key(args):
2154 2155 args = last_call[1]
2155 2156
2156 2157 # use last_call to remember the state of the previous call, but don't
2157 2158 # let it be clobbered by successive '-p' calls.
2158 2159 try:
2159 2160 last_call[0] = self.shell.displayhook.prompt_count
2160 2161 if not opts_prev:
2161 2162 last_call[1] = parameter_s
2162 2163 except:
2163 2164 pass
2164 2165
2165 2166 # by default this is done with temp files, except when the given
2166 2167 # arg is a filename
2167 2168 use_temp = True
2168 2169
2169 2170 data = ''
2170 2171
2171 2172 # First, see if the arguments should be a filename.
2172 2173 filename = make_filename(args)
2173 2174 if filename:
2174 2175 use_temp = False
2175 2176 elif args:
2176 2177 # Mode where user specifies ranges of lines, like in %macro.
2177 2178 data = self.extract_input_lines(args, opts_raw)
2178 2179 if not data:
2179 2180 try:
2180 2181 # Load the parameter given as a variable. If not a string,
2181 2182 # process it as an object instead (below)
2182 2183
2183 2184 #print '*** args',args,'type',type(args) # dbg
2184 2185 data = eval(args, self.shell.user_ns)
2185 2186 if not isinstance(data, basestring):
2186 2187 raise DataIsObject
2187 2188
2188 2189 except (NameError,SyntaxError):
2189 2190 # given argument is not a variable, try as a filename
2190 2191 filename = make_filename(args)
2191 2192 if filename is None:
2192 2193 warn("Argument given (%s) can't be found as a variable "
2193 2194 "or as a filename." % args)
2194 2195 return
2195 2196 use_temp = False
2196 2197
2197 2198 except DataIsObject:
2198 2199 # macros have a special edit function
2199 2200 if isinstance(data, Macro):
2200 2201 raise MacroToEdit(data)
2201 2202
2202 2203 # For objects, try to edit the file where they are defined
2203 2204 try:
2204 2205 filename = inspect.getabsfile(data)
2205 2206 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2206 2207 # class created by %edit? Try to find source
2207 2208 # by looking for method definitions instead, the
2208 2209 # __module__ in those classes is FakeModule.
2209 2210 attrs = [getattr(data, aname) for aname in dir(data)]
2210 2211 for attr in attrs:
2211 2212 if not inspect.ismethod(attr):
2212 2213 continue
2213 2214 filename = inspect.getabsfile(attr)
2214 2215 if filename and 'fakemodule' not in filename.lower():
2215 2216 # change the attribute to be the edit target instead
2216 2217 data = attr
2217 2218 break
2218 2219
2219 2220 datafile = 1
2220 2221 except TypeError:
2221 2222 filename = make_filename(args)
2222 2223 datafile = 1
2223 2224 warn('Could not find file where `%s` is defined.\n'
2224 2225 'Opening a file named `%s`' % (args,filename))
2225 2226 # Now, make sure we can actually read the source (if it was in
2226 2227 # a temp file it's gone by now).
2227 2228 if datafile:
2228 2229 try:
2229 2230 if lineno is None:
2230 2231 lineno = inspect.getsourcelines(data)[1]
2231 2232 except IOError:
2232 2233 filename = make_filename(args)
2233 2234 if filename is None:
2234 2235 warn('The file `%s` where `%s` was defined cannot '
2235 2236 'be read.' % (filename,data))
2236 2237 return
2237 2238 use_temp = False
2238 2239
2239 2240 if use_temp:
2240 2241 filename = self.shell.mktempfile(data)
2241 2242 print 'IPython will make a temporary file named:',filename
2242 2243
2243 2244 return filename, lineno, use_temp
2244 2245
2245 2246 def _edit_macro(self,mname,macro):
2246 2247 """open an editor with the macro data in a file"""
2247 2248 filename = self.shell.mktempfile(macro.value)
2248 2249 self.shell.hooks.editor(filename)
2249 2250
2250 2251 # and make a new macro object, to replace the old one
2251 2252 mfile = open(filename)
2252 2253 mvalue = mfile.read()
2253 2254 mfile.close()
2254 2255 self.shell.user_ns[mname] = Macro(mvalue)
2255 2256
2256 2257 def magic_ed(self,parameter_s=''):
2257 2258 """Alias to %edit."""
2258 2259 return self.magic_edit(parameter_s)
2259 2260
2260 2261 @skip_doctest
2261 2262 def magic_edit(self,parameter_s='',last_call=['','']):
2262 2263 """Bring up an editor and execute the resulting code.
2263 2264
2264 2265 Usage:
2265 2266 %edit [options] [args]
2266 2267
2267 2268 %edit runs IPython's editor hook. The default version of this hook is
2268 2269 set to call the __IPYTHON__.rc.editor command. This is read from your
2269 2270 environment variable $EDITOR. If this isn't found, it will default to
2270 2271 vi under Linux/Unix and to notepad under Windows. See the end of this
2271 2272 docstring for how to change the editor hook.
2272 2273
2273 2274 You can also set the value of this editor via the command line option
2274 2275 '-editor' or in your ipythonrc file. This is useful if you wish to use
2275 2276 specifically for IPython an editor different from your typical default
2276 2277 (and for Windows users who typically don't set environment variables).
2277 2278
2278 2279 This command allows you to conveniently edit multi-line code right in
2279 2280 your IPython session.
2280 2281
2281 2282 If called without arguments, %edit opens up an empty editor with a
2282 2283 temporary file and will execute the contents of this file when you
2283 2284 close it (don't forget to save it!).
2284 2285
2285 2286
2286 2287 Options:
2287 2288
2288 2289 -n <number>: open the editor at a specified line number. By default,
2289 2290 the IPython editor hook uses the unix syntax 'editor +N filename', but
2290 2291 you can configure this by providing your own modified hook if your
2291 2292 favorite editor supports line-number specifications with a different
2292 2293 syntax.
2293 2294
2294 2295 -p: this will call the editor with the same data as the previous time
2295 2296 it was used, regardless of how long ago (in your current session) it
2296 2297 was.
2297 2298
2298 2299 -r: use 'raw' input. This option only applies to input taken from the
2299 2300 user's history. By default, the 'processed' history is used, so that
2300 2301 magics are loaded in their transformed version to valid Python. If
2301 2302 this option is given, the raw input as typed as the command line is
2302 2303 used instead. When you exit the editor, it will be executed by
2303 2304 IPython's own processor.
2304 2305
2305 2306 -x: do not execute the edited code immediately upon exit. This is
2306 2307 mainly useful if you are editing programs which need to be called with
2307 2308 command line arguments, which you can then do using %run.
2308 2309
2309 2310
2310 2311 Arguments:
2311 2312
2312 2313 If arguments are given, the following possibilites exist:
2313 2314
2314 2315 - If the argument is a filename, IPython will load that into the
2315 2316 editor. It will execute its contents with execfile() when you exit,
2316 2317 loading any code in the file into your interactive namespace.
2317 2318
2318 2319 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2319 2320 The syntax is the same as in the %history magic.
2320 2321
2321 2322 - If the argument is a string variable, its contents are loaded
2322 2323 into the editor. You can thus edit any string which contains
2323 2324 python code (including the result of previous edits).
2324 2325
2325 2326 - If the argument is the name of an object (other than a string),
2326 2327 IPython will try to locate the file where it was defined and open the
2327 2328 editor at the point where it is defined. You can use `%edit function`
2328 2329 to load an editor exactly at the point where 'function' is defined,
2329 2330 edit it and have the file be executed automatically.
2330 2331
2331 2332 If the object is a macro (see %macro for details), this opens up your
2332 2333 specified editor with a temporary file containing the macro's data.
2333 2334 Upon exit, the macro is reloaded with the contents of the file.
2334 2335
2335 2336 Note: opening at an exact line is only supported under Unix, and some
2336 2337 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2337 2338 '+NUMBER' parameter necessary for this feature. Good editors like
2338 2339 (X)Emacs, vi, jed, pico and joe all do.
2339 2340
2340 2341 After executing your code, %edit will return as output the code you
2341 2342 typed in the editor (except when it was an existing file). This way
2342 2343 you can reload the code in further invocations of %edit as a variable,
2343 2344 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2344 2345 the output.
2345 2346
2346 2347 Note that %edit is also available through the alias %ed.
2347 2348
2348 2349 This is an example of creating a simple function inside the editor and
2349 2350 then modifying it. First, start up the editor:
2350 2351
2351 2352 In [1]: ed
2352 2353 Editing... done. Executing edited code...
2353 2354 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2354 2355
2355 2356 We can then call the function foo():
2356 2357
2357 2358 In [2]: foo()
2358 2359 foo() was defined in an editing session
2359 2360
2360 2361 Now we edit foo. IPython automatically loads the editor with the
2361 2362 (temporary) file where foo() was previously defined:
2362 2363
2363 2364 In [3]: ed foo
2364 2365 Editing... done. Executing edited code...
2365 2366
2366 2367 And if we call foo() again we get the modified version:
2367 2368
2368 2369 In [4]: foo()
2369 2370 foo() has now been changed!
2370 2371
2371 2372 Here is an example of how to edit a code snippet successive
2372 2373 times. First we call the editor:
2373 2374
2374 2375 In [5]: ed
2375 2376 Editing... done. Executing edited code...
2376 2377 hello
2377 2378 Out[5]: "print 'hello'n"
2378 2379
2379 2380 Now we call it again with the previous output (stored in _):
2380 2381
2381 2382 In [6]: ed _
2382 2383 Editing... done. Executing edited code...
2383 2384 hello world
2384 2385 Out[6]: "print 'hello world'n"
2385 2386
2386 2387 Now we call it with the output #8 (stored in _8, also as Out[8]):
2387 2388
2388 2389 In [7]: ed _8
2389 2390 Editing... done. Executing edited code...
2390 2391 hello again
2391 2392 Out[7]: "print 'hello again'n"
2392 2393
2393 2394
2394 2395 Changing the default editor hook:
2395 2396
2396 2397 If you wish to write your own editor hook, you can put it in a
2397 2398 configuration file which you load at startup time. The default hook
2398 2399 is defined in the IPython.core.hooks module, and you can use that as a
2399 2400 starting example for further modifications. That file also has
2400 2401 general instructions on how to set a new hook for use once you've
2401 2402 defined it."""
2402 2403 opts,args = self.parse_options(parameter_s,'prxn:')
2403 2404
2404 2405 try:
2405 2406 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2406 2407 except MacroToEdit as e:
2407 2408 self._edit_macro(args, e.args[0])
2408 2409 return
2409 2410
2410 2411 # do actual editing here
2411 2412 print 'Editing...',
2412 2413 sys.stdout.flush()
2413 2414 try:
2414 2415 # Quote filenames that may have spaces in them
2415 2416 if ' ' in filename:
2416 2417 filename = "'%s'" % filename
2417 2418 self.shell.hooks.editor(filename,lineno)
2418 2419 except TryNext:
2419 2420 warn('Could not open editor')
2420 2421 return
2421 2422
2422 2423 # XXX TODO: should this be generalized for all string vars?
2423 2424 # For now, this is special-cased to blocks created by cpaste
2424 2425 if args.strip() == 'pasted_block':
2425 2426 self.shell.user_ns['pasted_block'] = file_read(filename)
2426 2427
2427 2428 if 'x' in opts: # -x prevents actual execution
2428 2429 print
2429 2430 else:
2430 2431 print 'done. Executing edited code...'
2431 2432 if 'r' in opts: # Untranslated IPython code
2432 2433 self.shell.run_cell(file_read(filename),
2433 2434 store_history=False)
2434 2435 else:
2435 2436 self.shell.safe_execfile(filename,self.shell.user_ns,
2436 2437 self.shell.user_ns)
2437 2438
2438 2439 if is_temp:
2439 2440 try:
2440 2441 return open(filename).read()
2441 2442 except IOError,msg:
2442 2443 if msg.filename == filename:
2443 2444 warn('File not found. Did you forget to save?')
2444 2445 return
2445 2446 else:
2446 2447 self.shell.showtraceback()
2447 2448
2448 2449 def magic_xmode(self,parameter_s = ''):
2449 2450 """Switch modes for the exception handlers.
2450 2451
2451 2452 Valid modes: Plain, Context and Verbose.
2452 2453
2453 2454 If called without arguments, acts as a toggle."""
2454 2455
2455 2456 def xmode_switch_err(name):
2456 2457 warn('Error changing %s exception modes.\n%s' %
2457 2458 (name,sys.exc_info()[1]))
2458 2459
2459 2460 shell = self.shell
2460 2461 new_mode = parameter_s.strip().capitalize()
2461 2462 try:
2462 2463 shell.InteractiveTB.set_mode(mode=new_mode)
2463 2464 print 'Exception reporting mode:',shell.InteractiveTB.mode
2464 2465 except:
2465 2466 xmode_switch_err('user')
2466 2467
2467 2468 def magic_colors(self,parameter_s = ''):
2468 2469 """Switch color scheme for prompts, info system and exception handlers.
2469 2470
2470 2471 Currently implemented schemes: NoColor, Linux, LightBG.
2471 2472
2472 2473 Color scheme names are not case-sensitive.
2473 2474
2474 2475 Examples
2475 2476 --------
2476 2477 To get a plain black and white terminal::
2477 2478
2478 2479 %colors nocolor
2479 2480 """
2480 2481
2481 2482 def color_switch_err(name):
2482 2483 warn('Error changing %s color schemes.\n%s' %
2483 2484 (name,sys.exc_info()[1]))
2484 2485
2485 2486
2486 2487 new_scheme = parameter_s.strip()
2487 2488 if not new_scheme:
2488 2489 raise UsageError(
2489 2490 "%colors: you must specify a color scheme. See '%colors?'")
2490 2491 return
2491 2492 # local shortcut
2492 2493 shell = self.shell
2493 2494
2494 2495 import IPython.utils.rlineimpl as readline
2495 2496
2496 2497 if not readline.have_readline and sys.platform == "win32":
2497 2498 msg = """\
2498 2499 Proper color support under MS Windows requires the pyreadline library.
2499 2500 You can find it at:
2500 2501 http://ipython.scipy.org/moin/PyReadline/Intro
2501 2502 Gary's readline needs the ctypes module, from:
2502 2503 http://starship.python.net/crew/theller/ctypes
2503 2504 (Note that ctypes is already part of Python versions 2.5 and newer).
2504 2505
2505 2506 Defaulting color scheme to 'NoColor'"""
2506 2507 new_scheme = 'NoColor'
2507 2508 warn(msg)
2508 2509
2509 2510 # readline option is 0
2510 2511 if not shell.has_readline:
2511 2512 new_scheme = 'NoColor'
2512 2513
2513 2514 # Set prompt colors
2514 2515 try:
2515 2516 shell.displayhook.set_colors(new_scheme)
2516 2517 except:
2517 2518 color_switch_err('prompt')
2518 2519 else:
2519 2520 shell.colors = \
2520 2521 shell.displayhook.color_table.active_scheme_name
2521 2522 # Set exception colors
2522 2523 try:
2523 2524 shell.InteractiveTB.set_colors(scheme = new_scheme)
2524 2525 shell.SyntaxTB.set_colors(scheme = new_scheme)
2525 2526 except:
2526 2527 color_switch_err('exception')
2527 2528
2528 2529 # Set info (for 'object?') colors
2529 2530 if shell.color_info:
2530 2531 try:
2531 2532 shell.inspector.set_active_scheme(new_scheme)
2532 2533 except:
2533 2534 color_switch_err('object inspector')
2534 2535 else:
2535 2536 shell.inspector.set_active_scheme('NoColor')
2536 2537
2537 2538 def magic_pprint(self, parameter_s=''):
2538 2539 """Toggle pretty printing on/off."""
2539 2540 ptformatter = self.shell.display_formatter.formatters['text/plain']
2540 2541 ptformatter.pprint = bool(1 - ptformatter.pprint)
2541 2542 print 'Pretty printing has been turned', \
2542 2543 ['OFF','ON'][ptformatter.pprint]
2543 2544
2544 2545 #......................................................................
2545 2546 # Functions to implement unix shell-type things
2546 2547
2547 2548 @skip_doctest
2548 2549 def magic_alias(self, parameter_s = ''):
2549 2550 """Define an alias for a system command.
2550 2551
2551 2552 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2552 2553
2553 2554 Then, typing 'alias_name params' will execute the system command 'cmd
2554 2555 params' (from your underlying operating system).
2555 2556
2556 2557 Aliases have lower precedence than magic functions and Python normal
2557 2558 variables, so if 'foo' is both a Python variable and an alias, the
2558 2559 alias can not be executed until 'del foo' removes the Python variable.
2559 2560
2560 2561 You can use the %l specifier in an alias definition to represent the
2561 2562 whole line when the alias is called. For example:
2562 2563
2563 2564 In [2]: alias bracket echo "Input in brackets: <%l>"
2564 2565 In [3]: bracket hello world
2565 2566 Input in brackets: <hello world>
2566 2567
2567 2568 You can also define aliases with parameters using %s specifiers (one
2568 2569 per parameter):
2569 2570
2570 2571 In [1]: alias parts echo first %s second %s
2571 2572 In [2]: %parts A B
2572 2573 first A second B
2573 2574 In [3]: %parts A
2574 2575 Incorrect number of arguments: 2 expected.
2575 2576 parts is an alias to: 'echo first %s second %s'
2576 2577
2577 2578 Note that %l and %s are mutually exclusive. You can only use one or
2578 2579 the other in your aliases.
2579 2580
2580 2581 Aliases expand Python variables just like system calls using ! or !!
2581 2582 do: all expressions prefixed with '$' get expanded. For details of
2582 2583 the semantic rules, see PEP-215:
2583 2584 http://www.python.org/peps/pep-0215.html. This is the library used by
2584 2585 IPython for variable expansion. If you want to access a true shell
2585 2586 variable, an extra $ is necessary to prevent its expansion by IPython:
2586 2587
2587 2588 In [6]: alias show echo
2588 2589 In [7]: PATH='A Python string'
2589 2590 In [8]: show $PATH
2590 2591 A Python string
2591 2592 In [9]: show $$PATH
2592 2593 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2593 2594
2594 2595 You can use the alias facility to acess all of $PATH. See the %rehash
2595 2596 and %rehashx functions, which automatically create aliases for the
2596 2597 contents of your $PATH.
2597 2598
2598 2599 If called with no parameters, %alias prints the current alias table."""
2599 2600
2600 2601 par = parameter_s.strip()
2601 2602 if not par:
2602 2603 stored = self.db.get('stored_aliases', {} )
2603 2604 aliases = sorted(self.shell.alias_manager.aliases)
2604 2605 # for k, v in stored:
2605 2606 # atab.append(k, v[0])
2606 2607
2607 2608 print "Total number of aliases:", len(aliases)
2608 2609 sys.stdout.flush()
2609 2610 return aliases
2610 2611
2611 2612 # Now try to define a new one
2612 2613 try:
2613 2614 alias,cmd = par.split(None, 1)
2614 2615 except:
2615 2616 print oinspect.getdoc(self.magic_alias)
2616 2617 else:
2617 2618 self.shell.alias_manager.soft_define_alias(alias, cmd)
2618 2619 # end magic_alias
2619 2620
2620 2621 def magic_unalias(self, parameter_s = ''):
2621 2622 """Remove an alias"""
2622 2623
2623 2624 aname = parameter_s.strip()
2624 2625 self.shell.alias_manager.undefine_alias(aname)
2625 2626 stored = self.db.get('stored_aliases', {} )
2626 2627 if aname in stored:
2627 2628 print "Removing %stored alias",aname
2628 2629 del stored[aname]
2629 2630 self.db['stored_aliases'] = stored
2630 2631
2631 2632 def magic_rehashx(self, parameter_s = ''):
2632 2633 """Update the alias table with all executable files in $PATH.
2633 2634
2634 2635 This version explicitly checks that every entry in $PATH is a file
2635 2636 with execute access (os.X_OK), so it is much slower than %rehash.
2636 2637
2637 2638 Under Windows, it checks executability as a match agains a
2638 2639 '|'-separated string of extensions, stored in the IPython config
2639 2640 variable win_exec_ext. This defaults to 'exe|com|bat'.
2640 2641
2641 2642 This function also resets the root module cache of module completer,
2642 2643 used on slow filesystems.
2643 2644 """
2644 2645 from IPython.core.alias import InvalidAliasError
2645 2646
2646 2647 # for the benefit of module completer in ipy_completers.py
2647 2648 del self.db['rootmodules']
2648 2649
2649 2650 path = [os.path.abspath(os.path.expanduser(p)) for p in
2650 2651 os.environ.get('PATH','').split(os.pathsep)]
2651 2652 path = filter(os.path.isdir,path)
2652 2653
2653 2654 syscmdlist = []
2654 2655 # Now define isexec in a cross platform manner.
2655 2656 if os.name == 'posix':
2656 2657 isexec = lambda fname:os.path.isfile(fname) and \
2657 2658 os.access(fname,os.X_OK)
2658 2659 else:
2659 2660 try:
2660 2661 winext = os.environ['pathext'].replace(';','|').replace('.','')
2661 2662 except KeyError:
2662 2663 winext = 'exe|com|bat|py'
2663 2664 if 'py' not in winext:
2664 2665 winext += '|py'
2665 2666 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2666 2667 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2667 2668 savedir = os.getcwdu()
2668 2669
2669 2670 # Now walk the paths looking for executables to alias.
2670 2671 try:
2671 2672 # write the whole loop for posix/Windows so we don't have an if in
2672 2673 # the innermost part
2673 2674 if os.name == 'posix':
2674 2675 for pdir in path:
2675 2676 os.chdir(pdir)
2676 2677 for ff in os.listdir(pdir):
2677 2678 if isexec(ff):
2678 2679 try:
2679 2680 # Removes dots from the name since ipython
2680 2681 # will assume names with dots to be python.
2681 2682 self.shell.alias_manager.define_alias(
2682 2683 ff.replace('.',''), ff)
2683 2684 except InvalidAliasError:
2684 2685 pass
2685 2686 else:
2686 2687 syscmdlist.append(ff)
2687 2688 else:
2688 2689 no_alias = self.shell.alias_manager.no_alias
2689 2690 for pdir in path:
2690 2691 os.chdir(pdir)
2691 2692 for ff in os.listdir(pdir):
2692 2693 base, ext = os.path.splitext(ff)
2693 2694 if isexec(ff) and base.lower() not in no_alias:
2694 2695 if ext.lower() == '.exe':
2695 2696 ff = base
2696 2697 try:
2697 2698 # Removes dots from the name since ipython
2698 2699 # will assume names with dots to be python.
2699 2700 self.shell.alias_manager.define_alias(
2700 2701 base.lower().replace('.',''), ff)
2701 2702 except InvalidAliasError:
2702 2703 pass
2703 2704 syscmdlist.append(ff)
2704 2705 db = self.db
2705 2706 db['syscmdlist'] = syscmdlist
2706 2707 finally:
2707 2708 os.chdir(savedir)
2708 2709
2709 2710 @skip_doctest
2710 2711 def magic_pwd(self, parameter_s = ''):
2711 2712 """Return the current working directory path.
2712 2713
2713 2714 Examples
2714 2715 --------
2715 2716 ::
2716 2717
2717 2718 In [9]: pwd
2718 2719 Out[9]: '/home/tsuser/sprint/ipython'
2719 2720 """
2720 2721 return os.getcwdu()
2721 2722
2722 2723 @skip_doctest
2723 2724 def magic_cd(self, parameter_s=''):
2724 2725 """Change the current working directory.
2725 2726
2726 2727 This command automatically maintains an internal list of directories
2727 2728 you visit during your IPython session, in the variable _dh. The
2728 2729 command %dhist shows this history nicely formatted. You can also
2729 2730 do 'cd -<tab>' to see directory history conveniently.
2730 2731
2731 2732 Usage:
2732 2733
2733 2734 cd 'dir': changes to directory 'dir'.
2734 2735
2735 2736 cd -: changes to the last visited directory.
2736 2737
2737 2738 cd -<n>: changes to the n-th directory in the directory history.
2738 2739
2739 2740 cd --foo: change to directory that matches 'foo' in history
2740 2741
2741 2742 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2742 2743 (note: cd <bookmark_name> is enough if there is no
2743 2744 directory <bookmark_name>, but a bookmark with the name exists.)
2744 2745 'cd -b <tab>' allows you to tab-complete bookmark names.
2745 2746
2746 2747 Options:
2747 2748
2748 2749 -q: quiet. Do not print the working directory after the cd command is
2749 2750 executed. By default IPython's cd command does print this directory,
2750 2751 since the default prompts do not display path information.
2751 2752
2752 2753 Note that !cd doesn't work for this purpose because the shell where
2753 2754 !command runs is immediately discarded after executing 'command'.
2754 2755
2755 2756 Examples
2756 2757 --------
2757 2758 ::
2758 2759
2759 2760 In [10]: cd parent/child
2760 2761 /home/tsuser/parent/child
2761 2762 """
2762 2763
2763 2764 parameter_s = parameter_s.strip()
2764 2765 #bkms = self.shell.persist.get("bookmarks",{})
2765 2766
2766 2767 oldcwd = os.getcwdu()
2767 2768 numcd = re.match(r'(-)(\d+)$',parameter_s)
2768 2769 # jump in directory history by number
2769 2770 if numcd:
2770 2771 nn = int(numcd.group(2))
2771 2772 try:
2772 2773 ps = self.shell.user_ns['_dh'][nn]
2773 2774 except IndexError:
2774 2775 print 'The requested directory does not exist in history.'
2775 2776 return
2776 2777 else:
2777 2778 opts = {}
2778 2779 elif parameter_s.startswith('--'):
2779 2780 ps = None
2780 2781 fallback = None
2781 2782 pat = parameter_s[2:]
2782 2783 dh = self.shell.user_ns['_dh']
2783 2784 # first search only by basename (last component)
2784 2785 for ent in reversed(dh):
2785 2786 if pat in os.path.basename(ent) and os.path.isdir(ent):
2786 2787 ps = ent
2787 2788 break
2788 2789
2789 2790 if fallback is None and pat in ent and os.path.isdir(ent):
2790 2791 fallback = ent
2791 2792
2792 2793 # if we have no last part match, pick the first full path match
2793 2794 if ps is None:
2794 2795 ps = fallback
2795 2796
2796 2797 if ps is None:
2797 2798 print "No matching entry in directory history"
2798 2799 return
2799 2800 else:
2800 2801 opts = {}
2801 2802
2802 2803
2803 2804 else:
2804 2805 #turn all non-space-escaping backslashes to slashes,
2805 2806 # for c:\windows\directory\names\
2806 2807 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2807 2808 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2808 2809 # jump to previous
2809 2810 if ps == '-':
2810 2811 try:
2811 2812 ps = self.shell.user_ns['_dh'][-2]
2812 2813 except IndexError:
2813 2814 raise UsageError('%cd -: No previous directory to change to.')
2814 2815 # jump to bookmark if needed
2815 2816 else:
2816 2817 if not os.path.isdir(ps) or opts.has_key('b'):
2817 2818 bkms = self.db.get('bookmarks', {})
2818 2819
2819 2820 if bkms.has_key(ps):
2820 2821 target = bkms[ps]
2821 2822 print '(bookmark:%s) -> %s' % (ps,target)
2822 2823 ps = target
2823 2824 else:
2824 2825 if opts.has_key('b'):
2825 2826 raise UsageError("Bookmark '%s' not found. "
2826 2827 "Use '%%bookmark -l' to see your bookmarks." % ps)
2827 2828
2828 2829 # strip extra quotes on Windows, because os.chdir doesn't like them
2829 2830 if sys.platform == 'win32':
2830 2831 ps = ps.strip('\'"')
2831 2832 # at this point ps should point to the target dir
2832 2833 if ps:
2833 2834 try:
2834 2835 os.chdir(os.path.expanduser(ps))
2835 2836 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2836 2837 set_term_title('IPython: ' + abbrev_cwd())
2837 2838 except OSError:
2838 2839 print sys.exc_info()[1]
2839 2840 else:
2840 2841 cwd = os.getcwdu()
2841 2842 dhist = self.shell.user_ns['_dh']
2842 2843 if oldcwd != cwd:
2843 2844 dhist.append(cwd)
2844 2845 self.db['dhist'] = compress_dhist(dhist)[-100:]
2845 2846
2846 2847 else:
2847 2848 os.chdir(self.shell.home_dir)
2848 2849 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2849 2850 set_term_title('IPython: ' + '~')
2850 2851 cwd = os.getcwdu()
2851 2852 dhist = self.shell.user_ns['_dh']
2852 2853
2853 2854 if oldcwd != cwd:
2854 2855 dhist.append(cwd)
2855 2856 self.db['dhist'] = compress_dhist(dhist)[-100:]
2856 2857 if not 'q' in opts and self.shell.user_ns['_dh']:
2857 2858 print self.shell.user_ns['_dh'][-1]
2858 2859
2859 2860
2860 2861 def magic_env(self, parameter_s=''):
2861 2862 """List environment variables."""
2862 2863
2863 2864 return os.environ.data
2864 2865
2865 2866 def magic_pushd(self, parameter_s=''):
2866 2867 """Place the current dir on stack and change directory.
2867 2868
2868 2869 Usage:\\
2869 2870 %pushd ['dirname']
2870 2871 """
2871 2872
2872 2873 dir_s = self.shell.dir_stack
2873 2874 tgt = os.path.expanduser(parameter_s)
2874 2875 cwd = os.getcwdu().replace(self.home_dir,'~')
2875 2876 if tgt:
2876 2877 self.magic_cd(parameter_s)
2877 2878 dir_s.insert(0,cwd)
2878 2879 return self.magic_dirs()
2879 2880
2880 2881 def magic_popd(self, parameter_s=''):
2881 2882 """Change to directory popped off the top of the stack.
2882 2883 """
2883 2884 if not self.shell.dir_stack:
2884 2885 raise UsageError("%popd on empty stack")
2885 2886 top = self.shell.dir_stack.pop(0)
2886 2887 self.magic_cd(top)
2887 2888 print "popd ->",top
2888 2889
2889 2890 def magic_dirs(self, parameter_s=''):
2890 2891 """Return the current directory stack."""
2891 2892
2892 2893 return self.shell.dir_stack
2893 2894
2894 2895 def magic_dhist(self, parameter_s=''):
2895 2896 """Print your history of visited directories.
2896 2897
2897 2898 %dhist -> print full history\\
2898 2899 %dhist n -> print last n entries only\\
2899 2900 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2900 2901
2901 2902 This history is automatically maintained by the %cd command, and
2902 2903 always available as the global list variable _dh. You can use %cd -<n>
2903 2904 to go to directory number <n>.
2904 2905
2905 2906 Note that most of time, you should view directory history by entering
2906 2907 cd -<TAB>.
2907 2908
2908 2909 """
2909 2910
2910 2911 dh = self.shell.user_ns['_dh']
2911 2912 if parameter_s:
2912 2913 try:
2913 2914 args = map(int,parameter_s.split())
2914 2915 except:
2915 2916 self.arg_err(Magic.magic_dhist)
2916 2917 return
2917 2918 if len(args) == 1:
2918 2919 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2919 2920 elif len(args) == 2:
2920 2921 ini,fin = args
2921 2922 else:
2922 2923 self.arg_err(Magic.magic_dhist)
2923 2924 return
2924 2925 else:
2925 2926 ini,fin = 0,len(dh)
2926 2927 nlprint(dh,
2927 2928 header = 'Directory history (kept in _dh)',
2928 2929 start=ini,stop=fin)
2929 2930
2930 2931 @skip_doctest
2931 2932 def magic_sc(self, parameter_s=''):
2932 2933 """Shell capture - execute a shell command and capture its output.
2933 2934
2934 2935 DEPRECATED. Suboptimal, retained for backwards compatibility.
2935 2936
2936 2937 You should use the form 'var = !command' instead. Example:
2937 2938
2938 2939 "%sc -l myfiles = ls ~" should now be written as
2939 2940
2940 2941 "myfiles = !ls ~"
2941 2942
2942 2943 myfiles.s, myfiles.l and myfiles.n still apply as documented
2943 2944 below.
2944 2945
2945 2946 --
2946 2947 %sc [options] varname=command
2947 2948
2948 2949 IPython will run the given command using commands.getoutput(), and
2949 2950 will then update the user's interactive namespace with a variable
2950 2951 called varname, containing the value of the call. Your command can
2951 2952 contain shell wildcards, pipes, etc.
2952 2953
2953 2954 The '=' sign in the syntax is mandatory, and the variable name you
2954 2955 supply must follow Python's standard conventions for valid names.
2955 2956
2956 2957 (A special format without variable name exists for internal use)
2957 2958
2958 2959 Options:
2959 2960
2960 2961 -l: list output. Split the output on newlines into a list before
2961 2962 assigning it to the given variable. By default the output is stored
2962 2963 as a single string.
2963 2964
2964 2965 -v: verbose. Print the contents of the variable.
2965 2966
2966 2967 In most cases you should not need to split as a list, because the
2967 2968 returned value is a special type of string which can automatically
2968 2969 provide its contents either as a list (split on newlines) or as a
2969 2970 space-separated string. These are convenient, respectively, either
2970 2971 for sequential processing or to be passed to a shell command.
2971 2972
2972 2973 For example:
2973 2974
2974 2975 # all-random
2975 2976
2976 2977 # Capture into variable a
2977 2978 In [1]: sc a=ls *py
2978 2979
2979 2980 # a is a string with embedded newlines
2980 2981 In [2]: a
2981 2982 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2982 2983
2983 2984 # which can be seen as a list:
2984 2985 In [3]: a.l
2985 2986 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2986 2987
2987 2988 # or as a whitespace-separated string:
2988 2989 In [4]: a.s
2989 2990 Out[4]: 'setup.py win32_manual_post_install.py'
2990 2991
2991 2992 # a.s is useful to pass as a single command line:
2992 2993 In [5]: !wc -l $a.s
2993 2994 146 setup.py
2994 2995 130 win32_manual_post_install.py
2995 2996 276 total
2996 2997
2997 2998 # while the list form is useful to loop over:
2998 2999 In [6]: for f in a.l:
2999 3000 ...: !wc -l $f
3000 3001 ...:
3001 3002 146 setup.py
3002 3003 130 win32_manual_post_install.py
3003 3004
3004 3005 Similiarly, the lists returned by the -l option are also special, in
3005 3006 the sense that you can equally invoke the .s attribute on them to
3006 3007 automatically get a whitespace-separated string from their contents:
3007 3008
3008 3009 In [7]: sc -l b=ls *py
3009 3010
3010 3011 In [8]: b
3011 3012 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3012 3013
3013 3014 In [9]: b.s
3014 3015 Out[9]: 'setup.py win32_manual_post_install.py'
3015 3016
3016 3017 In summary, both the lists and strings used for ouptut capture have
3017 3018 the following special attributes:
3018 3019
3019 3020 .l (or .list) : value as list.
3020 3021 .n (or .nlstr): value as newline-separated string.
3021 3022 .s (or .spstr): value as space-separated string.
3022 3023 """
3023 3024
3024 3025 opts,args = self.parse_options(parameter_s,'lv')
3025 3026 # Try to get a variable name and command to run
3026 3027 try:
3027 3028 # the variable name must be obtained from the parse_options
3028 3029 # output, which uses shlex.split to strip options out.
3029 3030 var,_ = args.split('=',1)
3030 3031 var = var.strip()
3031 3032 # But the the command has to be extracted from the original input
3032 3033 # parameter_s, not on what parse_options returns, to avoid the
3033 3034 # quote stripping which shlex.split performs on it.
3034 3035 _,cmd = parameter_s.split('=',1)
3035 3036 except ValueError:
3036 3037 var,cmd = '',''
3037 3038 # If all looks ok, proceed
3038 3039 split = 'l' in opts
3039 3040 out = self.shell.getoutput(cmd, split=split)
3040 3041 if opts.has_key('v'):
3041 3042 print '%s ==\n%s' % (var,pformat(out))
3042 3043 if var:
3043 3044 self.shell.user_ns.update({var:out})
3044 3045 else:
3045 3046 return out
3046 3047
3047 3048 def magic_sx(self, parameter_s=''):
3048 3049 """Shell execute - run a shell command and capture its output.
3049 3050
3050 3051 %sx command
3051 3052
3052 3053 IPython will run the given command using commands.getoutput(), and
3053 3054 return the result formatted as a list (split on '\\n'). Since the
3054 3055 output is _returned_, it will be stored in ipython's regular output
3055 3056 cache Out[N] and in the '_N' automatic variables.
3056 3057
3057 3058 Notes:
3058 3059
3059 3060 1) If an input line begins with '!!', then %sx is automatically
3060 3061 invoked. That is, while:
3061 3062 !ls
3062 3063 causes ipython to simply issue system('ls'), typing
3063 3064 !!ls
3064 3065 is a shorthand equivalent to:
3065 3066 %sx ls
3066 3067
3067 3068 2) %sx differs from %sc in that %sx automatically splits into a list,
3068 3069 like '%sc -l'. The reason for this is to make it as easy as possible
3069 3070 to process line-oriented shell output via further python commands.
3070 3071 %sc is meant to provide much finer control, but requires more
3071 3072 typing.
3072 3073
3073 3074 3) Just like %sc -l, this is a list with special attributes:
3074 3075
3075 3076 .l (or .list) : value as list.
3076 3077 .n (or .nlstr): value as newline-separated string.
3077 3078 .s (or .spstr): value as whitespace-separated string.
3078 3079
3079 3080 This is very useful when trying to use such lists as arguments to
3080 3081 system commands."""
3081 3082
3082 3083 if parameter_s:
3083 3084 return self.shell.getoutput(parameter_s)
3084 3085
3085 3086
3086 3087 def magic_bookmark(self, parameter_s=''):
3087 3088 """Manage IPython's bookmark system.
3088 3089
3089 3090 %bookmark <name> - set bookmark to current dir
3090 3091 %bookmark <name> <dir> - set bookmark to <dir>
3091 3092 %bookmark -l - list all bookmarks
3092 3093 %bookmark -d <name> - remove bookmark
3093 3094 %bookmark -r - remove all bookmarks
3094 3095
3095 3096 You can later on access a bookmarked folder with:
3096 3097 %cd -b <name>
3097 3098 or simply '%cd <name>' if there is no directory called <name> AND
3098 3099 there is such a bookmark defined.
3099 3100
3100 3101 Your bookmarks persist through IPython sessions, but they are
3101 3102 associated with each profile."""
3102 3103
3103 3104 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3104 3105 if len(args) > 2:
3105 3106 raise UsageError("%bookmark: too many arguments")
3106 3107
3107 3108 bkms = self.db.get('bookmarks',{})
3108 3109
3109 3110 if opts.has_key('d'):
3110 3111 try:
3111 3112 todel = args[0]
3112 3113 except IndexError:
3113 3114 raise UsageError(
3114 3115 "%bookmark -d: must provide a bookmark to delete")
3115 3116 else:
3116 3117 try:
3117 3118 del bkms[todel]
3118 3119 except KeyError:
3119 3120 raise UsageError(
3120 3121 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3121 3122
3122 3123 elif opts.has_key('r'):
3123 3124 bkms = {}
3124 3125 elif opts.has_key('l'):
3125 3126 bks = bkms.keys()
3126 3127 bks.sort()
3127 3128 if bks:
3128 3129 size = max(map(len,bks))
3129 3130 else:
3130 3131 size = 0
3131 3132 fmt = '%-'+str(size)+'s -> %s'
3132 3133 print 'Current bookmarks:'
3133 3134 for bk in bks:
3134 3135 print fmt % (bk,bkms[bk])
3135 3136 else:
3136 3137 if not args:
3137 3138 raise UsageError("%bookmark: You must specify the bookmark name")
3138 3139 elif len(args)==1:
3139 3140 bkms[args[0]] = os.getcwdu()
3140 3141 elif len(args)==2:
3141 3142 bkms[args[0]] = args[1]
3142 3143 self.db['bookmarks'] = bkms
3143 3144
3144 3145 def magic_pycat(self, parameter_s=''):
3145 3146 """Show a syntax-highlighted file through a pager.
3146 3147
3147 3148 This magic is similar to the cat utility, but it will assume the file
3148 3149 to be Python source and will show it with syntax highlighting. """
3149 3150
3150 3151 try:
3151 3152 filename = get_py_filename(parameter_s)
3152 3153 cont = file_read(filename)
3153 3154 except IOError:
3154 3155 try:
3155 3156 cont = eval(parameter_s,self.user_ns)
3156 3157 except NameError:
3157 3158 cont = None
3158 3159 if cont is None:
3159 3160 print "Error: no such file or variable"
3160 3161 return
3161 3162
3162 3163 page.page(self.shell.pycolorize(cont))
3163 3164
3164 3165 def _rerun_pasted(self):
3165 3166 """ Rerun a previously pasted command.
3166 3167 """
3167 3168 b = self.user_ns.get('pasted_block', None)
3168 3169 if b is None:
3169 3170 raise UsageError('No previous pasted block available')
3170 3171 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3171 3172 exec b in self.user_ns
3172 3173
3173 3174 def _get_pasted_lines(self, sentinel):
3174 3175 """ Yield pasted lines until the user enters the given sentinel value.
3175 3176 """
3176 3177 from IPython.core import interactiveshell
3177 3178 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3178 3179 while True:
3179 3180 l = interactiveshell.raw_input_original(':')
3180 3181 if l == sentinel:
3181 3182 return
3182 3183 else:
3183 3184 yield l
3184 3185
3185 3186 def _strip_pasted_lines_for_code(self, raw_lines):
3186 3187 """ Strip non-code parts of a sequence of lines to return a block of
3187 3188 code.
3188 3189 """
3189 3190 # Regular expressions that declare text we strip from the input:
3190 3191 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3191 3192 r'^\s*(\s?>)+', # Python input prompt
3192 3193 r'^\s*\.{3,}', # Continuation prompts
3193 3194 r'^\++',
3194 3195 ]
3195 3196
3196 3197 strip_from_start = map(re.compile,strip_re)
3197 3198
3198 3199 lines = []
3199 3200 for l in raw_lines:
3200 3201 for pat in strip_from_start:
3201 3202 l = pat.sub('',l)
3202 3203 lines.append(l)
3203 3204
3204 3205 block = "\n".join(lines) + '\n'
3205 3206 #print "block:\n",block
3206 3207 return block
3207 3208
3208 3209 def _execute_block(self, block, par):
3209 3210 """ Execute a block, or store it in a variable, per the user's request.
3210 3211 """
3211 3212 if not par:
3212 3213 b = textwrap.dedent(block)
3213 3214 self.user_ns['pasted_block'] = b
3214 3215 exec b in self.user_ns
3215 3216 else:
3216 3217 self.user_ns[par] = SList(block.splitlines())
3217 3218 print "Block assigned to '%s'" % par
3218 3219
3219 3220 def magic_quickref(self,arg):
3220 3221 """ Show a quick reference sheet """
3221 3222 import IPython.core.usage
3222 3223 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3223 3224
3224 3225 page.page(qr)
3225 3226
3226 3227 def magic_doctest_mode(self,parameter_s=''):
3227 3228 """Toggle doctest mode on and off.
3228 3229
3229 3230 This mode is intended to make IPython behave as much as possible like a
3230 3231 plain Python shell, from the perspective of how its prompts, exceptions
3231 3232 and output look. This makes it easy to copy and paste parts of a
3232 3233 session into doctests. It does so by:
3233 3234
3234 3235 - Changing the prompts to the classic ``>>>`` ones.
3235 3236 - Changing the exception reporting mode to 'Plain'.
3236 3237 - Disabling pretty-printing of output.
3237 3238
3238 3239 Note that IPython also supports the pasting of code snippets that have
3239 3240 leading '>>>' and '...' prompts in them. This means that you can paste
3240 3241 doctests from files or docstrings (even if they have leading
3241 3242 whitespace), and the code will execute correctly. You can then use
3242 3243 '%history -t' to see the translated history; this will give you the
3243 3244 input after removal of all the leading prompts and whitespace, which
3244 3245 can be pasted back into an editor.
3245 3246
3246 3247 With these features, you can switch into this mode easily whenever you
3247 3248 need to do testing and changes to doctests, without having to leave
3248 3249 your existing IPython session.
3249 3250 """
3250 3251
3251 3252 from IPython.utils.ipstruct import Struct
3252 3253
3253 3254 # Shorthands
3254 3255 shell = self.shell
3255 3256 oc = shell.displayhook
3256 3257 meta = shell.meta
3257 3258 disp_formatter = self.shell.display_formatter
3258 3259 ptformatter = disp_formatter.formatters['text/plain']
3259 3260 # dstore is a data store kept in the instance metadata bag to track any
3260 3261 # changes we make, so we can undo them later.
3261 3262 dstore = meta.setdefault('doctest_mode',Struct())
3262 3263 save_dstore = dstore.setdefault
3263 3264
3264 3265 # save a few values we'll need to recover later
3265 3266 mode = save_dstore('mode',False)
3266 3267 save_dstore('rc_pprint',ptformatter.pprint)
3267 3268 save_dstore('xmode',shell.InteractiveTB.mode)
3268 3269 save_dstore('rc_separate_out',shell.separate_out)
3269 3270 save_dstore('rc_separate_out2',shell.separate_out2)
3270 3271 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3271 3272 save_dstore('rc_separate_in',shell.separate_in)
3272 3273 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3273 3274
3274 3275 if mode == False:
3275 3276 # turn on
3276 3277 oc.prompt1.p_template = '>>> '
3277 3278 oc.prompt2.p_template = '... '
3278 3279 oc.prompt_out.p_template = ''
3279 3280
3280 3281 # Prompt separators like plain python
3281 3282 oc.input_sep = oc.prompt1.sep = ''
3282 3283 oc.output_sep = ''
3283 3284 oc.output_sep2 = ''
3284 3285
3285 3286 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3286 3287 oc.prompt_out.pad_left = False
3287 3288
3288 3289 ptformatter.pprint = False
3289 3290 disp_formatter.plain_text_only = True
3290 3291
3291 3292 shell.magic_xmode('Plain')
3292 3293 else:
3293 3294 # turn off
3294 3295 oc.prompt1.p_template = shell.prompt_in1
3295 3296 oc.prompt2.p_template = shell.prompt_in2
3296 3297 oc.prompt_out.p_template = shell.prompt_out
3297 3298
3298 3299 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3299 3300
3300 3301 oc.output_sep = dstore.rc_separate_out
3301 3302 oc.output_sep2 = dstore.rc_separate_out2
3302 3303
3303 3304 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3304 3305 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3305 3306
3306 3307 ptformatter.pprint = dstore.rc_pprint
3307 3308 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3308 3309
3309 3310 shell.magic_xmode(dstore.xmode)
3310 3311
3311 3312 # Store new mode and inform
3312 3313 dstore.mode = bool(1-int(mode))
3313 3314 mode_label = ['OFF','ON'][dstore.mode]
3314 3315 print 'Doctest mode is:', mode_label
3315 3316
3316 3317 def magic_gui(self, parameter_s=''):
3317 3318 """Enable or disable IPython GUI event loop integration.
3318 3319
3319 3320 %gui [GUINAME]
3320 3321
3321 3322 This magic replaces IPython's threaded shells that were activated
3322 3323 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3323 3324 can now be enabled, disabled and changed at runtime and keyboard
3324 3325 interrupts should work without any problems. The following toolkits
3325 3326 are supported: wxPython, PyQt4, PyGTK, and Tk::
3326 3327
3327 3328 %gui wx # enable wxPython event loop integration
3328 3329 %gui qt4|qt # enable PyQt4 event loop integration
3329 3330 %gui gtk # enable PyGTK event loop integration
3330 3331 %gui tk # enable Tk event loop integration
3331 3332 %gui # disable all event loop integration
3332 3333
3333 3334 WARNING: after any of these has been called you can simply create
3334 3335 an application object, but DO NOT start the event loop yourself, as
3335 3336 we have already handled that.
3336 3337 """
3337 3338 from IPython.lib.inputhook import enable_gui
3338 3339 opts, arg = self.parse_options(parameter_s, '')
3339 3340 if arg=='': arg = None
3340 3341 return enable_gui(arg)
3341 3342
3342 3343 def magic_load_ext(self, module_str):
3343 3344 """Load an IPython extension by its module name."""
3344 3345 return self.extension_manager.load_extension(module_str)
3345 3346
3346 3347 def magic_unload_ext(self, module_str):
3347 3348 """Unload an IPython extension by its module name."""
3348 3349 self.extension_manager.unload_extension(module_str)
3349 3350
3350 3351 def magic_reload_ext(self, module_str):
3351 3352 """Reload an IPython extension by its module name."""
3352 3353 self.extension_manager.reload_extension(module_str)
3353 3354
3354 3355 @skip_doctest
3355 3356 def magic_install_profiles(self, s):
3356 3357 """Install the default IPython profiles into the .ipython dir.
3357 3358
3358 3359 If the default profiles have already been installed, they will not
3359 3360 be overwritten. You can force overwriting them by using the ``-o``
3360 3361 option::
3361 3362
3362 3363 In [1]: %install_profiles -o
3363 3364 """
3364 3365 if '-o' in s:
3365 3366 overwrite = True
3366 3367 else:
3367 3368 overwrite = False
3368 3369 from IPython.config import profile
3369 3370 profile_dir = os.path.dirname(profile.__file__)
3370 3371 ipython_dir = self.ipython_dir
3371 3372 print "Installing profiles to: %s [overwrite=%s]"%(ipython_dir,overwrite)
3372 3373 for src in os.listdir(profile_dir):
3373 3374 if src.startswith('profile_'):
3374 3375 name = src.replace('profile_', '')
3375 3376 print " %s"%name
3376 3377 pd = ProfileDir.create_profile_dir_by_name(ipython_dir, name)
3377 3378 pd.copy_config_file('ipython_config.py', path=src,
3378 3379 overwrite=overwrite)
3379 3380
3380 3381 @skip_doctest
3381 3382 def magic_install_default_config(self, s):
3382 3383 """Install IPython's default config file into the .ipython dir.
3383 3384
3384 3385 If the default config file (:file:`ipython_config.py`) is already
3385 3386 installed, it will not be overwritten. You can force overwriting
3386 3387 by using the ``-o`` option::
3387 3388
3388 3389 In [1]: %install_default_config
3389 3390 """
3390 3391 if '-o' in s:
3391 3392 overwrite = True
3392 3393 else:
3393 3394 overwrite = False
3394 3395 pd = self.shell.profile_dir
3395 3396 print "Installing default config file in: %s" % pd.location
3396 3397 pd.copy_config_file('ipython_config.py', overwrite=overwrite)
3397 3398
3398 3399 # Pylab support: simple wrappers that activate pylab, load gui input
3399 3400 # handling and modify slightly %run
3400 3401
3401 3402 @skip_doctest
3402 3403 def _pylab_magic_run(self, parameter_s=''):
3403 3404 Magic.magic_run(self, parameter_s,
3404 3405 runner=mpl_runner(self.shell.safe_execfile))
3405 3406
3406 3407 _pylab_magic_run.__doc__ = magic_run.__doc__
3407 3408
3408 3409 @skip_doctest
3409 3410 def magic_pylab(self, s):
3410 3411 """Load numpy and matplotlib to work interactively.
3411 3412
3412 3413 %pylab [GUINAME]
3413 3414
3414 3415 This function lets you activate pylab (matplotlib, numpy and
3415 3416 interactive support) at any point during an IPython session.
3416 3417
3417 3418 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3418 3419 pylab and mlab, as well as all names from numpy and pylab.
3419 3420
3420 3421 Parameters
3421 3422 ----------
3422 3423 guiname : optional
3423 3424 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or
3424 3425 'tk'). If given, the corresponding Matplotlib backend is used,
3425 3426 otherwise matplotlib's default (which you can override in your
3426 3427 matplotlib config file) is used.
3427 3428
3428 3429 Examples
3429 3430 --------
3430 3431 In this case, where the MPL default is TkAgg:
3431 3432 In [2]: %pylab
3432 3433
3433 3434 Welcome to pylab, a matplotlib-based Python environment.
3434 3435 Backend in use: TkAgg
3435 3436 For more information, type 'help(pylab)'.
3436 3437
3437 3438 But you can explicitly request a different backend:
3438 3439 In [3]: %pylab qt
3439 3440
3440 3441 Welcome to pylab, a matplotlib-based Python environment.
3441 3442 Backend in use: Qt4Agg
3442 3443 For more information, type 'help(pylab)'.
3443 3444 """
3444 3445 self.shell.enable_pylab(s)
3445 3446
3446 3447 def magic_tb(self, s):
3447 3448 """Print the last traceback with the currently active exception mode.
3448 3449
3449 3450 See %xmode for changing exception reporting modes."""
3450 3451 self.shell.showtraceback()
3451 3452
3452 3453 @skip_doctest
3453 3454 def magic_precision(self, s=''):
3454 3455 """Set floating point precision for pretty printing.
3455 3456
3456 3457 Can set either integer precision or a format string.
3457 3458
3458 3459 If numpy has been imported and precision is an int,
3459 3460 numpy display precision will also be set, via ``numpy.set_printoptions``.
3460 3461
3461 3462 If no argument is given, defaults will be restored.
3462 3463
3463 3464 Examples
3464 3465 --------
3465 3466 ::
3466 3467
3467 3468 In [1]: from math import pi
3468 3469
3469 3470 In [2]: %precision 3
3470 3471 Out[2]: u'%.3f'
3471 3472
3472 3473 In [3]: pi
3473 3474 Out[3]: 3.142
3474 3475
3475 3476 In [4]: %precision %i
3476 3477 Out[4]: u'%i'
3477 3478
3478 3479 In [5]: pi
3479 3480 Out[5]: 3
3480 3481
3481 3482 In [6]: %precision %e
3482 3483 Out[6]: u'%e'
3483 3484
3484 3485 In [7]: pi**10
3485 3486 Out[7]: 9.364805e+04
3486 3487
3487 3488 In [8]: %precision
3488 3489 Out[8]: u'%r'
3489 3490
3490 3491 In [9]: pi**10
3491 3492 Out[9]: 93648.047476082982
3492 3493
3493 3494 """
3494 3495
3495 3496 ptformatter = self.shell.display_formatter.formatters['text/plain']
3496 3497 ptformatter.float_precision = s
3497 3498 return ptformatter.float_format
3498 3499
3499 3500
3500 3501 @magic_arguments.magic_arguments()
3501 3502 @magic_arguments.argument(
3502 3503 '-e', '--export', action='store_true', default=False,
3503 3504 help='Export IPython history as a notebook. The filename argument '
3504 3505 'is used to specify the notebook name and format. For example '
3505 3506 'a filename of notebook.ipynb will result in a notebook name '
3506 3507 'of "notebook" and a format of "xml". Likewise using a ".json" '
3507 3508 'or ".py" file extension will write the notebook in the json '
3508 3509 'or py formats.'
3509 3510 )
3510 3511 @magic_arguments.argument(
3511 3512 '-f', '--format',
3512 3513 help='Convert an existing IPython notebook to a new format. This option '
3513 3514 'specifies the new format and can have the values: xml, json, py. '
3514 3515 'The target filename is choosen automatically based on the new '
3515 3516 'format. The filename argument gives the name of the source file.'
3516 3517 )
3517 3518 @magic_arguments.argument(
3518 3519 'filename', type=unicode,
3519 3520 help='Notebook name or filename'
3520 3521 )
3521 3522 def magic_notebook(self, s):
3522 3523 """Export and convert IPython notebooks.
3523 3524
3524 3525 This function can export the current IPython history to a notebook file
3525 3526 or can convert an existing notebook file into a different format. For
3526 3527 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
3527 3528 To export the history to "foo.py" do "%notebook -e foo.py". To convert
3528 3529 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
3529 3530 formats include (xml/ipynb, json, py).
3530 3531 """
3531 3532 args = magic_arguments.parse_argstring(self.magic_notebook, s)
3532 3533 print args
3533 3534
3534 3535 from IPython.nbformat import current
3535 3536 if args.export:
3536 3537 fname, name, format = current.parse_filename(args.filename)
3537 3538 cells = []
3538 3539 hist = list(self.history_manager.get_range())
3539 3540 for session, prompt_number, input in hist[:-1]:
3540 3541 cells.append(current.new_code_cell(prompt_number=prompt_number, input=input))
3541 3542 worksheet = current.new_worksheet(cells=cells)
3542 3543 nb = current.new_notebook(name=name,worksheets=[worksheet])
3543 3544 with open(fname, 'w') as f:
3544 3545 current.write(nb, f, format);
3545 3546 elif args.format is not None:
3546 3547 old_fname, old_name, old_format = current.parse_filename(args.filename)
3547 3548 new_format = args.format
3548 3549 if new_format == u'xml' or new_format == u'ipynb':
3549 3550 new_fname = old_name + u'.ipynb'
3550 3551 new_format = u'xml'
3551 3552 elif new_format == u'py':
3552 3553 new_fname = old_name + u'.py'
3553 3554 elif new_format == u'json':
3554 3555 new_fname = old_name + u'.json'
3555 3556 else:
3556 3557 raise ValueError('Invalid notebook format: %s' % newformat)
3557 3558 with open(old_fname, 'r') as f:
3558 3559 nb = current.read(f, old_format)
3559 3560 with open(new_fname, 'w') as f:
3560 3561 current.write(nb, f, new_format)
3561 3562
3562 3563
3563 3564 # end Magic
@@ -1,397 +1,410 b''
1 1
2 2 //============================================================================
3 3 // CodeCell
4 4 //============================================================================
5 5
6 6 var IPython = (function (IPython) {
7 7
8 8 var utils = IPython.utils;
9 9
10 10 var CodeCell = function (notebook) {
11 11 this.code_mirror = null;
12 12 this.input_prompt_number = ' ';
13 13 this.is_completing = false;
14 14 this.completion_cursor = null;
15 15 this.outputs = [];
16 16 IPython.Cell.apply(this, arguments);
17 17 };
18 18
19 19
20 20 CodeCell.prototype = new IPython.Cell();
21 21
22 22
23 23 CodeCell.prototype.create_element = function () {
24 24 var cell = $('<div></div>').addClass('cell border-box-sizing code_cell vbox');
25 25 var input = $('<div></div>').addClass('input hbox');
26 26 input.append($('<div/>').addClass('prompt input_prompt'));
27 27 var input_area = $('<div/>').addClass('input_area box-flex1');
28 28 this.code_mirror = CodeMirror(input_area.get(0), {
29 29 indentUnit : 4,
30 30 enterMode : 'flat',
31 31 tabMode: 'shift',
32 32 mode: 'python',
33 33 theme: 'ipython',
34 34 onKeyEvent: $.proxy(this.handle_codemirror_keyevent,this)
35 35 });
36 36 input.append(input_area);
37 37 var output = $('<div></div>').addClass('output vbox');
38 38 cell.append(input).append(output);
39 39 this.element = cell;
40 40 this.collapse()
41 41 };
42 42
43 43
44 44 CodeCell.prototype.handle_codemirror_keyevent = function (editor, event) {
45 45 // This method gets called in CodeMirror's onKeyDown/onKeyPress handlers and
46 46 // is used to provide custom key handling. Its return value is used to determine
47 47 // if CodeMirror should ignore the event: true = ignore, false = don't ignore.
48 48 if (event.keyCode === 13 && event.shiftKey) {
49 49 // Always ignore shift-enter in CodeMirror as we handle it.
50 50 return true;
51 51 } else if (event.keyCode === 9) {
52 52 var cur = editor.getCursor();
53 53 var pre_cursor = editor.getRange({line:cur.line,ch:0},cur).trim();
54 54 if (pre_cursor === "") {
55 55 // Don't autocomplete if the part of the line before the cursor is empty.
56 56 // In this case, let CodeMirror handle indentation.
57 57 return false;
58 58 } else {
59 59 // Autocomplete the current line.
60 60 event.stop();
61 61 var line = editor.getLine(cur.line);
62 62 this.is_completing = true;
63 63 this.completion_cursor = cur;
64 64 IPython.notebook.complete_cell(this, line, cur.ch);
65 65 return true;
66 66 }
67 67 } else if (event.keyCode === 8) {
68 68 // If backspace and the line ends with 4 spaces, remove them.
69 69 var cur = editor.getCursor();
70 70 var line = editor.getLine(cur.line);
71 71 var ending = line.slice(-4);
72 72 if (ending === ' ') {
73 73 editor.replaceRange('',
74 74 {line: cur.line, ch: cur.ch-4},
75 75 {line: cur.line, ch: cur.ch}
76 76 );
77 77 event.stop();
78 78 return true;
79 79 } else {
80 80 return false;
81 81 };
82 82 } else {
83 83 if (this.is_completing && this.completion_cursor !== editor.getCursor()) {
84 84 this.is_completing = false;
85 85 this.completion_cursor = null;
86 86 }
87 87 return false;
88 88 };
89 89 };
90 90
91 91
92 92 CodeCell.prototype.finish_completing = function (matched_text, matches) {
93 93 if (!this.is_completing || matches.length === 0) {return;}
94 94 // console.log("Got matches", matched_text, matches);
95 95
96 96 var that = this;
97 97 var cur = this.completion_cursor;
98 98 var complete = $('<div/>').addClass('completions');
99 99 var select = $('<select/>').attr('multiple','true');
100 100 for (var i=0; i<matches.length; ++i) {
101 101 select.append($('<option/>').text(matches[i]));
102 102 }
103 103 select.children().first().attr('selected','true');
104 104 select.attr('size',Math.min(10,matches.length));
105 105 var pos = this.code_mirror.cursorCoords();
106 106 complete.css('left',pos.x+'px');
107 107 complete.css('top',pos.yBot+'px');
108 108 complete.append(select);
109 109
110 110 $('body').append(complete);
111 111 var done = false;
112 112
113 113 var insert = function (selected_text) {
114 114 that.code_mirror.replaceRange(
115 115 selected_text,
116 116 {line: cur.line, ch: (cur.ch-matched_text.length)},
117 117 {line: cur.line, ch: cur.ch}
118 118 );
119 119 };
120 120
121 121 var close = function () {
122 122 if (done) return;
123 123 done = true;
124 124 complete.remove();
125 125 that.is_completing = false;
126 126 that.completion_cursor = null;
127 127 };
128 128
129 129 var pick = function () {
130 130 insert(select.val()[0]);
131 131 close();
132 132 setTimeout(function(){that.code_mirror.focus();}, 50);
133 133 };
134 134
135 135 select.blur(close);
136 136 select.keydown(function (event) {
137 137 var code = event.which;
138 138 if (code === 13 || code === 32) {
139 139 // Pressing SPACE or ENTER will cause a pick
140 140 event.stopPropagation();
141 141 event.preventDefault();
142 142 pick();
143 143 } else if (code === 38 || code === 40) {
144 144 // We don't want the document keydown handler to handle UP/DOWN,
145 145 // but we want the default action.
146 146 event.stopPropagation();
147 147 } else {
148 148 // All other key presses simple exit completion.
149 149 event.stopPropagation();
150 150 event.preventDefault();
151 151 close();
152 152 that.code_mirror.focus();
153 153 }
154 154 });
155 155 // Double click also causes a pick.
156 156 select.dblclick(pick);
157 157 select.focus();
158 158 };
159 159
160 160
161 161 CodeCell.prototype.select = function () {
162 162 IPython.Cell.prototype.select.apply(this);
163 163 // Todo: this dance is needed because as of CodeMirror 2.12, focus is
164 164 // not causing the cursor to blink if the editor is empty initially.
165 165 // While this seems to fix the issue, this should be fixed
166 166 // in CodeMirror proper.
167 167 var s = this.code_mirror.getValue();
168 168 if (s === '') this.code_mirror.setValue('.');
169 169 this.code_mirror.focus();
170 170 if (s === '') this.code_mirror.setValue('');
171 171 };
172 172
173 173
174 174 CodeCell.prototype.append_output = function (json) {
175 175 this.expand();
176 176 if (json.output_type === 'pyout') {
177 177 this.append_pyout(json);
178 178 } else if (json.output_type === 'pyerr') {
179 179 this.append_pyerr(json);
180 180 } else if (json.output_type === 'display_data') {
181 181 this.append_display_data(json);
182 182 } else if (json.output_type === 'stream') {
183 183 this.append_stream(json);
184 184 };
185 185 this.outputs.push(json);
186 186 };
187 187
188 188
189 189 CodeCell.prototype.append_pyout = function (json) {
190 190 n = json.prompt_number || ' ';
191 191 var toinsert = $("<div/>").addClass("output_area output_pyout hbox");
192 192 toinsert.append($('<div/>').
193 193 addClass('prompt output_prompt').
194 194 html('Out[' + n + ']:')
195 195 );
196 196 this.append_mime_type(json, toinsert);
197 197 toinsert.children().last().addClass("box_flex1");
198 198 this.element.find("div.output").append(toinsert);
199 199 // If we just output latex, typeset it.
200 200 if (json.latex !== undefined) {
201 201 MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
202 202 };
203 203 };
204 204
205 205
206 206 CodeCell.prototype.append_pyerr = function (json) {
207 207 var tb = json.traceback;
208 if (tb !== undefined) {
208 209 var s = '';
209 210 var len = tb.length;
210 211 for (var i=0; i<len; i++) {
211 212 s = s + tb[i] + '\n';
212 213 }
213 214 s = s + '\n';
214 215 this.append_text(s);
215 216 };
217 };
216 218
217 219
218 220 CodeCell.prototype.append_stream = function (json) {
219 221 this.append_text(json.text);
220 222 };
221 223
222 224
223 225 CodeCell.prototype.append_display_data = function (json) {
224 226 this.append_mime_type(json);
225 227 };
226 228
227 229
228 230 CodeCell.prototype.append_mime_type = function (json, element) {
229 231 if (json.html !== undefined) {
230 232 this.append_html(json.html, element);
231 233 } else if (json.latex !== undefined) {
232 234 this.append_latex(json.latex, element);
233 235 // If it is undefined, then we just appended to div.output, which
234 236 // makes the latex visible and we can typeset it. The typesetting
235 237 // has to be done after the latex is on the page.
236 238 if (element === undefined) {
237 239 MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
238 240 };
239 241 } else if (json.svg !== undefined) {
240 242 this.append_svg(json.svg, element);
241 243 } else if (json.png !== undefined) {
242 244 this.append_png(json.png, element);
245 } else if (json.jpeg !== undefined) {
246 this.append_jpeg(json.jpeg, element);
243 247 } else if (json.text !== undefined) {
244 248 this.append_text(json.text, element);
245 249 };
246 250 return element;
247 251 };
248 252
249 253
250 254 CodeCell.prototype.append_html = function (html, element) {
251 255 element = element || this.element.find("div.output");
252 256 var toinsert = $("<div/>").addClass("output_area output_html");
253 257 toinsert.append(html);
254 258 element.append(toinsert);
255 259 return element;
256 260 }
257 261
258 262
259 263 CodeCell.prototype.append_text = function (data, element) {
260 264 element = element || this.element.find("div.output");
261 265 var toinsert = $("<div/>").addClass("output_area output_stream");
262 266 toinsert.append($("<pre/>").html(utils.fixConsole(data)));
263 267 element.append(toinsert);
264 268 return element;
265 269 };
266 270
267 271
268 272 CodeCell.prototype.append_svg = function (svg, element) {
269 273 element = element || this.element.find("div.output");
270 274 var toinsert = $("<div/>").addClass("output_area output_svg");
271 275 toinsert.append(svg);
272 276 element.append(toinsert);
273 277 return element;
274 278 };
275 279
276 280
277 281 CodeCell.prototype.append_png = function (png, element) {
278 282 element = element || this.element.find("div.output");
279 283 var toinsert = $("<div/>").addClass("output_area output_png");
280 284 toinsert.append($("<img/>").attr('src','data:image/png;base64,'+png));
281 285 element.append(toinsert);
282 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 299 CodeCell.prototype.append_latex = function (latex, element) {
287 300 // This method cannot do the typesetting because the latex first has to
288 301 // be on the page.
289 302 element = element || this.element.find("div.output");
290 303 var toinsert = $("<div/>").addClass("output_area output_latex");
291 304 toinsert.append(latex);
292 305 element.append(toinsert);
293 306 return element;
294 307 }
295 308
296 309
297 310 CodeCell.prototype.clear_output = function () {
298 311 this.element.find("div.output").html("");
299 312 this.outputs = [];
300 313 };
301 314
302 315
303 316 CodeCell.prototype.clear_input = function () {
304 317 this.code_mirror.setValue('');
305 318 };
306 319
307 320
308 321 CodeCell.prototype.collapse = function () {
309 322 this.element.find('div.output').hide();
310 323 };
311 324
312 325
313 326 CodeCell.prototype.expand = function () {
314 327 this.element.find('div.output').show();
315 328 };
316 329
317 330
318 331 CodeCell.prototype.set_input_prompt = function (number) {
319 332 var n = number || ' ';
320 333 this.input_prompt_number = n
321 334 this.element.find('div.input_prompt').html('In&nbsp;[' + n + ']:');
322 335 };
323 336
324 337
325 338 CodeCell.prototype.get_code = function () {
326 339 return this.code_mirror.getValue();
327 340 };
328 341
329 342
330 343 CodeCell.prototype.set_code = function (code) {
331 344 return this.code_mirror.setValue(code);
332 345 };
333 346
334 347
335 348 CodeCell.prototype.at_top = function () {
336 349 var cursor = this.code_mirror.getCursor();
337 350 if (cursor.line === 0) {
338 351 return true;
339 352 } else {
340 353 return false;
341 354 }
342 355 };
343 356
344 357
345 358 CodeCell.prototype.at_bottom = function () {
346 359 var cursor = this.code_mirror.getCursor();
347 360 if (cursor.line === (this.code_mirror.lineCount()-1)) {
348 361 return true;
349 362 } else {
350 363 return false;
351 364 }
352 365 };
353 366
354 367
355 368 CodeCell.prototype.fromJSON = function (data) {
356 369 // console.log('Import from JSON:', data);
357 370 if (data.cell_type === 'code') {
358 371 if (data.input !== undefined) {
359 372 this.set_code(data.input);
360 373 }
361 374 if (data.prompt_number !== undefined) {
362 375 this.set_input_prompt(data.prompt_number);
363 376 } else {
364 377 this.set_input_prompt();
365 378 };
366 379 var len = data.outputs.length;
367 380 for (var i=0; i<len; i++) {
368 381 this.append_output(data.outputs[i]);
369 382 };
370 383 };
371 384 };
372 385
373 386
374 387 CodeCell.prototype.toJSON = function () {
375 388 var data = {};
376 389 data.input = this.get_code();
377 390 data.cell_type = 'code';
378 391 if (this.input_prompt_number !== ' ') {
379 392 data.prompt_number = this.input_prompt_number
380 393 };
381 394 var outputs = [];
382 395 var len = this.outputs.length;
383 396 for (var i=0; i<len; i++) {
384 397 outputs[i] = this.outputs[i];
385 398 };
386 399 data.outputs = outputs;
387 400 data.language = 'python';
388 401 // console.log('Export to JSON:',data);
389 402 return data;
390 403 };
391 404
392 405
393 406 IPython.CodeCell = CodeCell;
394 407
395 408 return IPython;
396 409 }(IPython));
397 410
@@ -1,729 +1,732 b''
1 1
2 2 //============================================================================
3 3 // Notebook
4 4 //============================================================================
5 5
6 6 var IPython = (function (IPython) {
7 7
8 8 var utils = IPython.utils;
9 9
10 10 var Notebook = function (selector) {
11 11 this.element = $(selector);
12 12 this.element.scroll();
13 13 this.element.data("notebook", this);
14 14 this.next_prompt_number = 1;
15 15 this.kernel = null;
16 16 this.msg_cell_map = {};
17 17 this.style();
18 18 this.create_elements();
19 19 this.bind_events();
20 20 };
21 21
22 22
23 23 Notebook.prototype.style = function () {
24 24 $('div#notebook').addClass('border-box-sizing');
25 25 };
26 26
27 27
28 28 Notebook.prototype.create_elements = function () {
29 29 // We add this end_space div to the end of the notebook div to:
30 30 // i) provide a margin between the last cell and the end of the notebook
31 31 // ii) to prevent the div from scrolling up when the last cell is being
32 32 // edited, but is too low on the page, which browsers will do automatically.
33 33 this.element.append($('<div class="end_space"></div>').height(50));
34 34 $('div#notebook').addClass('border-box-sizing');
35 35 };
36 36
37 37
38 38 Notebook.prototype.bind_events = function () {
39 39 var that = this;
40 40 $(document).keydown(function (event) {
41 41 // console.log(event);
42 42 if (event.which === 38) {
43 43 var cell = that.selected_cell();
44 44 if (cell.at_top()) {
45 45 event.preventDefault();
46 46 that.select_prev();
47 47 };
48 48 } else if (event.which === 40) {
49 49 var cell = that.selected_cell();
50 50 if (cell.at_bottom()) {
51 51 event.preventDefault();
52 52 that.select_next();
53 53 };
54 54 } else if (event.which === 13 && event.shiftKey) {
55 55 that.execute_selected_cell();
56 56 return false;
57 57 } else if (event.which === 13 && event.ctrlKey) {
58 58 that.execute_selected_cell({terminal:true});
59 59 return false;
60 60 };
61 61 });
62 62
63 63 this.element.bind('collapse_pager', function () {
64 64 var app_height = $('div#main_app').height(); // content height
65 65 var splitter_height = $('div#pager_splitter').outerHeight(true);
66 66 var new_height = app_height - splitter_height;
67 67 that.element.animate({height : new_height + 'px'}, 'fast');
68 68 });
69 69
70 70 this.element.bind('expand_pager', function () {
71 71 var app_height = $('div#main_app').height(); // content height
72 72 var splitter_height = $('div#pager_splitter').outerHeight(true);
73 73 var pager_height = $('div#pager').outerHeight(true);
74 74 var new_height = app_height - pager_height - splitter_height;
75 75 that.element.animate({height : new_height + 'px'}, 'fast');
76 76 });
77 77
78 78 this.element.bind('collapse_left_panel', function () {
79 79 var splitter_width = $('div#left_panel_splitter').outerWidth(true);
80 80 var new_margin = splitter_width;
81 81 $('div#notebook_panel').animate({marginLeft : new_margin + 'px'}, 'fast');
82 82 });
83 83
84 84 this.element.bind('expand_left_panel', function () {
85 85 var splitter_width = $('div#left_panel_splitter').outerWidth(true);
86 86 var left_panel_width = IPython.left_panel.width;
87 87 var new_margin = splitter_width + left_panel_width;
88 88 $('div#notebook_panel').animate({marginLeft : new_margin + 'px'}, 'fast');
89 89 });
90 90 };
91 91
92 92
93 93 Notebook.prototype.scroll_to_bottom = function () {
94 94 this.element.animate({scrollTop:this.element.get(0).scrollHeight}, 0);
95 95 };
96 96
97 97
98 98 Notebook.prototype.scroll_to_top = function () {
99 99 this.element.animate({scrollTop:0}, 0);
100 100 };
101 101
102 102
103 103 // Cell indexing, retrieval, etc.
104 104
105 105
106 106 Notebook.prototype.cell_elements = function () {
107 107 return this.element.children("div.cell");
108 108 }
109 109
110 110
111 111 Notebook.prototype.ncells = function (cell) {
112 112 return this.cell_elements().length;
113 113 }
114 114
115 115
116 116 // TODO: we are often calling cells as cells()[i], which we should optimize
117 117 // to cells(i) or a new method.
118 118 Notebook.prototype.cells = function () {
119 119 return this.cell_elements().toArray().map(function (e) {
120 120 return $(e).data("cell");
121 121 });
122 122 }
123 123
124 124
125 125 Notebook.prototype.find_cell_index = function (cell) {
126 126 var result = null;
127 127 this.cell_elements().filter(function (index) {
128 128 if ($(this).data("cell") === cell) {
129 129 result = index;
130 130 };
131 131 });
132 132 return result;
133 133 };
134 134
135 135
136 136 Notebook.prototype.index_or_selected = function (index) {
137 137 return index || this.selected_index() || 0;
138 138 }
139 139
140 140
141 141 Notebook.prototype.select = function (index) {
142 142 if (index !== undefined && index >= 0 && index < this.ncells()) {
143 143 if (this.selected_index() !== null) {
144 144 this.selected_cell().unselect();
145 145 };
146 146 this.cells()[index].select();
147 147 if (index === (this.ncells()-1)) {
148 148 this.scroll_to_bottom();
149 149 };
150 150 };
151 151 return this;
152 152 };
153 153
154 154
155 155 Notebook.prototype.select_next = function () {
156 156 var index = this.selected_index();
157 157 if (index !== null && index >= 0 && (index+1) < this.ncells()) {
158 158 this.select(index+1);
159 159 };
160 160 return this;
161 161 };
162 162
163 163
164 164 Notebook.prototype.select_prev = function () {
165 165 var index = this.selected_index();
166 166 if (index !== null && index >= 0 && (index-1) < this.ncells()) {
167 167 this.select(index-1);
168 168 };
169 169 return this;
170 170 };
171 171
172 172
173 173 Notebook.prototype.selected_index = function () {
174 174 var result = null;
175 175 this.cell_elements().filter(function (index) {
176 176 if ($(this).data("cell").selected === true) {
177 177 result = index;
178 178 };
179 179 });
180 180 return result;
181 181 };
182 182
183 183
184 184 Notebook.prototype.cell_for_msg = function (msg_id) {
185 185 var cell_id = this.msg_cell_map[msg_id];
186 186 var result = null;
187 187 this.cell_elements().filter(function (index) {
188 188 cell = $(this).data("cell");
189 189 if (cell.cell_id === cell_id) {
190 190 result = cell;
191 191 };
192 192 });
193 193 return result;
194 194 };
195 195
196 196
197 197 Notebook.prototype.selected_cell = function () {
198 198 return this.cell_elements().eq(this.selected_index()).data("cell");
199 199 }
200 200
201 201
202 202 // Cell insertion, deletion and moving.
203 203
204 204
205 205 Notebook.prototype.delete_cell = function (index) {
206 206 var i = index || this.selected_index();
207 207 if (i !== null && i >= 0 && i < this.ncells()) {
208 208 this.cell_elements().eq(i).remove();
209 209 if (i === (this.ncells())) {
210 210 this.select(i-1);
211 211 } else {
212 212 this.select(i);
213 213 };
214 214 };
215 215 return this;
216 216 };
217 217
218 218
219 219 Notebook.prototype.append_cell = function (cell) {
220 220 this.element.find('div.end_space').before(cell.element);
221 221 return this;
222 222 };
223 223
224 224
225 225 Notebook.prototype.insert_cell_after = function (cell, index) {
226 226 var ncells = this.ncells();
227 227 if (ncells === 0) {
228 228 this.append_cell(cell);
229 229 return this;
230 230 };
231 231 if (index >= 0 && index < ncells) {
232 232 this.cell_elements().eq(index).after(cell.element);
233 233 };
234 234 return this
235 235 };
236 236
237 237
238 238 Notebook.prototype.insert_cell_before = function (cell, index) {
239 239 var ncells = this.ncells();
240 240 if (ncells === 0) {
241 241 this.append_cell(cell);
242 242 return this;
243 243 };
244 244 if (index >= 0 && index < ncells) {
245 245 this.cell_elements().eq(index).before(cell.element);
246 246 };
247 247 return this;
248 248 };
249 249
250 250
251 251 Notebook.prototype.move_cell_up = function (index) {
252 252 var i = index || this.selected_index();
253 253 if (i !== null && i < this.ncells() && i > 0) {
254 254 var pivot = this.cell_elements().eq(i-1);
255 255 var tomove = this.cell_elements().eq(i);
256 256 if (pivot !== null && tomove !== null) {
257 257 tomove.detach();
258 258 pivot.before(tomove);
259 259 this.select(i-1);
260 260 };
261 261 };
262 262 return this;
263 263 }
264 264
265 265
266 266 Notebook.prototype.move_cell_down = function (index) {
267 267 var i = index || this.selected_index();
268 268 if (i !== null && i < (this.ncells()-1) && i >= 0) {
269 269 var pivot = this.cell_elements().eq(i+1)
270 270 var tomove = this.cell_elements().eq(i)
271 271 if (pivot !== null && tomove !== null) {
272 272 tomove.detach();
273 273 pivot.after(tomove);
274 274 this.select(i+1);
275 275 };
276 276 };
277 277 return this;
278 278 }
279 279
280 280
281 281 Notebook.prototype.sort_cells = function () {
282 282 var ncells = this.ncells();
283 283 var sindex = this.selected_index();
284 284 var swapped;
285 285 do {
286 286 swapped = false
287 287 for (var i=1; i<ncells; i++) {
288 288 current = this.cell_elements().eq(i).data("cell");
289 289 previous = this.cell_elements().eq(i-1).data("cell");
290 290 if (previous.input_prompt_number > current.input_prompt_number) {
291 291 this.move_cell_up(i);
292 292 swapped = true;
293 293 };
294 294 };
295 295 } while (swapped);
296 296 this.select(sindex);
297 297 return this;
298 298 };
299 299
300 300
301 301 Notebook.prototype.insert_code_cell_before = function (index) {
302 302 // TODO: Bounds check for i
303 303 var i = this.index_or_selected(index);
304 304 var cell = new IPython.CodeCell(this);
305 305 cell.set_input_prompt();
306 306 this.insert_cell_before(cell, i);
307 307 this.select(this.find_cell_index(cell));
308 308 return cell;
309 309 }
310 310
311 311
312 312 Notebook.prototype.insert_code_cell_after = function (index) {
313 313 // TODO: Bounds check for i
314 314 var i = this.index_or_selected(index);
315 315 var cell = new IPython.CodeCell(this);
316 316 cell.set_input_prompt();
317 317 this.insert_cell_after(cell, i);
318 318 this.select(this.find_cell_index(cell));
319 319 return cell;
320 320 }
321 321
322 322
323 323 Notebook.prototype.insert_html_cell_before = function (index) {
324 324 // TODO: Bounds check for i
325 325 var i = this.index_or_selected(index);
326 326 var cell = new IPython.HTMLCell(this);
327 327 cell.config_mathjax();
328 328 this.insert_cell_before(cell, i);
329 329 this.select(this.find_cell_index(cell));
330 330 return cell;
331 331 }
332 332
333 333
334 334 Notebook.prototype.insert_html_cell_after = function (index) {
335 335 // TODO: Bounds check for i
336 336 var i = this.index_or_selected(index);
337 337 var cell = new IPython.HTMLCell(this);
338 338 cell.config_mathjax();
339 339 this.insert_cell_after(cell, i);
340 340 this.select(this.find_cell_index(cell));
341 341 return cell;
342 342 }
343 343
344 344
345 345 Notebook.prototype.insert_markdown_cell_before = function (index) {
346 346 // TODO: Bounds check for i
347 347 var i = this.index_or_selected(index);
348 348 var cell = new IPython.MarkdownCell(this);
349 349 cell.config_mathjax();
350 350 this.insert_cell_before(cell, i);
351 351 this.select(this.find_cell_index(cell));
352 352 return cell;
353 353 }
354 354
355 355
356 356 Notebook.prototype.insert_markdown_cell_after = function (index) {
357 357 // TODO: Bounds check for i
358 358 var i = this.index_or_selected(index);
359 359 var cell = new IPython.MarkdownCell(this);
360 360 cell.config_mathjax();
361 361 this.insert_cell_after(cell, i);
362 362 this.select(this.find_cell_index(cell));
363 363 return cell;
364 364 }
365 365
366 366
367 367 Notebook.prototype.to_code = function (index) {
368 368 // TODO: Bounds check for i
369 369 var i = this.index_or_selected(index);
370 370 var source_element = this.cell_elements().eq(i);
371 371 var source_cell = source_element.data("cell");
372 372 if (source_cell instanceof IPython.HTMLCell ||
373 373 source_cell instanceof IPython.MarkdownCell) {
374 374 this.insert_code_cell_after(i);
375 375 var target_cell = this.cells()[i+1];
376 376 target_cell.set_code(source_cell.get_source());
377 377 source_element.remove();
378 378 };
379 379 };
380 380
381 381
382 382 Notebook.prototype.to_markdown = function (index) {
383 383 // TODO: Bounds check for i
384 384 var i = this.index_or_selected(index);
385 385 var source_element = this.cell_elements().eq(i);
386 386 var source_cell = source_element.data("cell");
387 387 var target_cell = null;
388 388 if (source_cell instanceof IPython.CodeCell) {
389 389 this.insert_markdown_cell_after(i);
390 390 var target_cell = this.cells()[i+1];
391 391 var text = source_cell.get_code();
392 392 } else if (source_cell instanceof IPython.HTMLCell) {
393 393 this.insert_markdown_cell_after(i);
394 394 var target_cell = this.cells()[i+1];
395 395 var text = source_cell.get_source();
396 396 if (text === source_cell.placeholder) {
397 397 text = target_cell.placeholder;
398 398 }
399 399 }
400 400 if (target_cell !== null) {
401 401 if (text === "") {text = target_cell.placeholder;};
402 402 target_cell.set_source(text);
403 403 source_element.remove();
404 404 target_cell.edit();
405 405 }
406 406 };
407 407
408 408
409 409 Notebook.prototype.to_html = function (index) {
410 410 // TODO: Bounds check for i
411 411 var i = this.index_or_selected(index);
412 412 var source_element = this.cell_elements().eq(i);
413 413 var source_cell = source_element.data("cell");
414 414 var target_cell = null;
415 415 if (source_cell instanceof IPython.CodeCell) {
416 416 this.insert_html_cell_after(i);
417 417 var target_cell = this.cells()[i+1];
418 418 var text = source_cell.get_code();
419 419 } else if (source_cell instanceof IPython.MarkdownCell) {
420 420 this.insert_html_cell_after(i);
421 421 var target_cell = this.cells()[i+1];
422 422 var text = source_cell.get_source();
423 423 if (text === source_cell.placeholder) {
424 424 text = target_cell.placeholder;
425 425 }
426 426 }
427 427 if (target_cell !== null) {
428 428 if (text === "") {text = target_cell.placeholder;};
429 429 target_cell.set_source(text);
430 430 source_element.remove();
431 431 target_cell.edit();
432 432 }
433 433 };
434 434
435 435
436 436 // Cell collapsing
437 437
438 438 Notebook.prototype.collapse = function (index) {
439 439 var i = this.index_or_selected(index);
440 440 this.cells()[i].collapse();
441 441 };
442 442
443 443
444 444 Notebook.prototype.expand = function (index) {
445 445 var i = this.index_or_selected(index);
446 446 this.cells()[i].expand();
447 447 };
448 448
449 449
450 450 Notebook.prototype.set_autoindent = function (state) {
451 451 var cells = this.cells();
452 452 len = cells.length;
453 453 for (var i=0; i<len; i++) {
454 454 cells[i].set_autoindent(state)
455 455 };
456 456 };
457 457
458 458 // Kernel related things
459 459
460 460 Notebook.prototype.start_kernel = function () {
461 461 this.kernel = new IPython.Kernel();
462 462 var notebook_id = IPython.save_widget.get_notebook_id();
463 463 this.kernel.start_kernel(notebook_id, $.proxy(this.kernel_started, this));
464 464 };
465 465
466 466
467 467 Notebook.prototype.handle_shell_reply = function (e) {
468 468 reply = $.parseJSON(e.data);
469 469 var header = reply.header;
470 470 var content = reply.content;
471 471 var msg_type = header.msg_type;
472 472 // console.log(reply);
473 473 var cell = this.cell_for_msg(reply.parent_header.msg_id);
474 474 if (msg_type === "execute_reply") {
475 475 cell.set_input_prompt(content.execution_count);
476 476 } else if (msg_type === "complete_reply") {
477 477 cell.finish_completing(content.matched_text, content.matches);
478 478 };
479 479 var payload = content.payload || [];
480 480 this.handle_payload(payload);
481 481 };
482 482
483 483
484 484 Notebook.prototype.handle_payload = function (payload) {
485 485 var l = payload.length;
486 486 if (l > 0) {
487 487 IPython.pager.clear();
488 488 IPython.pager.expand();
489 489 };
490 490 for (var i=0; i<l; i++) {
491 491 IPython.pager.append_text(payload[i].text);
492 492 };
493 493 };
494 494
495 495
496 496 Notebook.prototype.handle_iopub_reply = function (e) {
497 497 reply = $.parseJSON(e.data);
498 498 var content = reply.content;
499 499 // console.log(reply);
500 500 var msg_type = reply.header.msg_type;
501 501 var cell = this.cell_for_msg(reply.parent_header.msg_id);
502 502 var output_types = ['stream','display_data','pyout','pyerr'];
503 503 if (output_types.indexOf(msg_type) >= 0) {
504 504 this.handle_output(cell, msg_type, content);
505 505 } else if (msg_type === "status") {
506 506 if (content.execution_state === "busy") {
507 507 IPython.kernel_status_widget.status_busy();
508 508 } else if (content.execution_state === "idle") {
509 509 IPython.kernel_status_widget.status_idle();
510 510 };
511 511 }
512 512 };
513 513
514 514
515 515 Notebook.prototype.handle_output = function (cell, msg_type, content) {
516 516 var json = {};
517 517 json.output_type = msg_type;
518 518 if (msg_type === "stream") {
519 519 json.text = content.data + '\n';
520 520 } else if (msg_type === "display_data") {
521 521 json = this.convert_mime_types(json, content.data);
522 522 } else if (msg_type === "pyout") {
523 523 json.prompt_number = content.execution_count;
524 524 json = this.convert_mime_types(json, content.data);
525 525 } else if (msg_type === "pyerr") {
526 526 json.ename = content.ename;
527 527 json.evalue = content.evalue;
528 528 json.traceback = content.traceback;
529 529 };
530 530 cell.append_output(json);
531 531 };
532 532
533 533
534 534 Notebook.prototype.convert_mime_types = function (json, data) {
535 535 if (data['text/plain'] !== undefined) {
536 536 json.text = data['text/plain'];
537 537 };
538 538 if (data['text/html'] !== undefined) {
539 539 json.html = data['text/html'];
540 540 };
541 541 if (data['image/svg+xml'] !== undefined) {
542 542 json.svg = data['image/svg+xml'];
543 543 };
544 544 if (data['image/png'] !== undefined) {
545 545 json.png = data['image/png'];
546 546 };
547 if (data['image/jpeg'] !== undefined) {
548 json.jpeg = data['image/jpeg'];
549 };
547 550 if (data['text/latex'] !== undefined) {
548 551 json.latex = data['text/latex'];
549 552 };
550 553 if (data['application/json'] !== undefined) {
551 554 json.json = data['application/json'];
552 555 };
553 556 if (data['application/javascript'] !== undefined) {
554 557 json.javascript = data['application/javascript'];
555 558 }
556 559 return json;
557 560 };
558 561
559 562 Notebook.prototype.kernel_started = function () {
560 563 console.log("Kernel started: ", this.kernel.kernel_id);
561 564 this.kernel.shell_channel.onmessage = $.proxy(this.handle_shell_reply,this);
562 565 this.kernel.iopub_channel.onmessage = $.proxy(this.handle_iopub_reply,this);
563 566 };
564 567
565 568
566 569 Notebook.prototype.execute_selected_cell = function (options) {
567 570 // add_new: should a new cell be added if we are at the end of the nb
568 571 // terminal: execute in terminal mode, which stays in the current cell
569 572 default_options = {terminal: false, add_new: true}
570 573 $.extend(default_options, options)
571 574 var that = this;
572 575 var cell = that.selected_cell();
573 576 var cell_index = that.find_cell_index(cell);
574 577 if (cell instanceof IPython.CodeCell) {
575 578 cell.clear_output();
576 579 var code = cell.get_code();
577 580 var msg_id = that.kernel.execute(cell.get_code());
578 581 that.msg_cell_map[msg_id] = cell.cell_id;
579 582 } else if (cell instanceof IPython.HTMLCell) {
580 583 cell.render();
581 584 }
582 585 if (default_options.terminal) {
583 586 cell.clear_input();
584 587 } else {
585 588 if ((cell_index === (that.ncells()-1)) && default_options.add_new) {
586 589 that.insert_code_cell_after();
587 590 // If we are adding a new cell at the end, scroll down to show it.
588 591 that.scroll_to_bottom();
589 592 } else {
590 593 that.select(cell_index+1);
591 594 };
592 595 };
593 596 };
594 597
595 598
596 599 Notebook.prototype.execute_all_cells = function () {
597 600 var ncells = this.ncells();
598 601 for (var i=0; i<ncells; i++) {
599 602 this.select(i);
600 603 this.execute_selected_cell({add_new:false});
601 604 };
602 605 this.scroll_to_bottom();
603 606 };
604 607
605 608
606 609 Notebook.prototype.complete_cell = function (cell, line, cursor_pos) {
607 610 var msg_id = this.kernel.complete(line, cursor_pos);
608 611 this.msg_cell_map[msg_id] = cell.cell_id;
609 612 };
610 613
611 614 // Persistance and loading
612 615
613 616
614 617 Notebook.prototype.fromJSON = function (data) {
615 618 var ncells = this.ncells();
616 619 for (var i=0; i<ncells; i++) {
617 620 // Always delete cell 0 as they get renumbered as they are deleted.
618 621 this.delete_cell(0);
619 622 };
620 623 // Only handle 1 worksheet for now.
621 624 var worksheet = data.worksheets[0];
622 625 if (worksheet !== undefined) {
623 626 var new_cells = worksheet.cells;
624 627 ncells = new_cells.length;
625 628 var cell_data = null;
626 629 var new_cell = null;
627 630 for (var i=0; i<ncells; i++) {
628 631 cell_data = new_cells[i];
629 632 if (cell_data.cell_type == 'code') {
630 633 new_cell = this.insert_code_cell_after();
631 634 new_cell.fromJSON(cell_data);
632 635 } else if (cell_data.cell_type === 'html') {
633 636 new_cell = this.insert_html_cell_after();
634 637 new_cell.fromJSON(cell_data);
635 638 } else if (cell_data.cell_type === 'markdown') {
636 639 new_cell = this.insert_markdown_cell_after();
637 640 new_cell.fromJSON(cell_data);
638 641 };
639 642 };
640 643 };
641 644 };
642 645
643 646
644 647 Notebook.prototype.toJSON = function () {
645 648 var cells = this.cells();
646 649 var ncells = cells.length;
647 650 cell_array = new Array(ncells);
648 651 for (var i=0; i<ncells; i++) {
649 652 cell_array[i] = cells[i].toJSON();
650 653 };
651 654 data = {
652 655 // Only handle 1 worksheet for now.
653 656 worksheets : [{cells:cell_array}]
654 657 }
655 658 return data
656 659 };
657 660
658 661 Notebook.prototype.save_notebook = function () {
659 662 if (IPython.save_widget.test_notebook_name()) {
660 663 var notebook_id = IPython.save_widget.get_notebook_id();
661 664 var nbname = IPython.save_widget.get_notebook_name();
662 665 // We may want to move the name/id/nbformat logic inside toJSON?
663 666 var data = this.toJSON();
664 667 data.name = nbname;
665 668 data.nbformat = 2;
666 669 data.id = notebook_id
667 670 // We do the call with settings so we can set cache to false.
668 671 var settings = {
669 672 processData : false,
670 673 cache : false,
671 674 type : "PUT",
672 675 data : JSON.stringify(data),
673 676 headers : {'Content-Type': 'application/json'},
674 677 success : $.proxy(this.notebook_saved,this)
675 678 };
676 679 IPython.save_widget.status_saving();
677 680 $.ajax("/notebooks/" + notebook_id, settings);
678 681 };
679 682 };
680 683
681 684
682 685 Notebook.prototype.notebook_saved = function (data, status, xhr) {
683 686 IPython.save_widget.status_save();
684 687 }
685 688
686 689
687 690 Notebook.prototype.load_notebook = function (callback) {
688 691 var that = this;
689 692 var notebook_id = IPython.save_widget.get_notebook_id();
690 693 // We do the call with settings so we can set cache to false.
691 694 var settings = {
692 695 processData : false,
693 696 cache : false,
694 697 type : "GET",
695 698 dataType : "json",
696 699 success : function (data, status, xhr) {
697 700 that.notebook_loaded(data, status, xhr);
698 701 if (callback !== undefined) {
699 702 callback();
700 703 };
701 704 }
702 705 };
703 706 IPython.save_widget.status_loading();
704 707 $.ajax("/notebooks/" + notebook_id, settings);
705 708 }
706 709
707 710
708 711 Notebook.prototype.notebook_loaded = function (data, status, xhr) {
709 712 this.fromJSON(data);
710 713 if (this.ncells() === 0) {
711 714 this.insert_code_cell_after();
712 715 };
713 716 IPython.save_widget.status_save();
714 717 IPython.save_widget.set_notebook_name(data.name);
715 718 this.start_kernel();
716 719 // fromJSON always selects the last cell inserted. We need to wait
717 720 // until that is done before scrolling to the top.
718 721 setTimeout(function () {
719 722 IPython.notebook.select(0);
720 723 IPython.notebook.scroll_to_top();
721 724 }, 50);
722 725 };
723 726
724 727 IPython.Notebook = Notebook;
725 728
726 729 return IPython;
727 730
728 731 }(IPython));
729 732
@@ -1,106 +1,108 b''
1 1 """The basic dict based notebook format."""
2 2
3 3 import pprint
4 4 import uuid
5 5
6 6 from IPython.utils.ipstruct import Struct
7 7
8 8
9 9 class NotebookNode(Struct):
10 10 pass
11 11
12 12
13 13 def from_dict(d):
14 14 if isinstance(d, dict):
15 15 newd = NotebookNode()
16 16 for k,v in d.items():
17 17 newd[k] = from_dict(v)
18 18 return newd
19 19 elif isinstance(d, (tuple, list)):
20 20 return [from_dict(i) for i in d]
21 21 else:
22 22 return d
23 23
24 24
25 25 def new_output(output_type=None, output_text=None, output_png=None,
26 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 28 """Create a new code cell with input and output"""
29 29 output = NotebookNode()
30 30 if output_type is not None:
31 31 output.output_type = unicode(output_type)
32 32 if output_text is not None:
33 33 output.text = unicode(output_text)
34 34 if output_png is not None:
35 35 output.png = bytes(output_png)
36 if output_jpeg is not None:
37 output.jpeg = bytes(output_jpeg)
36 38 if output_html is not None:
37 39 output.html = unicode(output_html)
38 40 if output_svg is not None:
39 41 output.svg = unicode(output_svg)
40 42 if output_latex is not None:
41 43 output.latex = unicode(output_latex)
42 44 if output_json is not None:
43 45 output.json = unicode(output_json)
44 46 if output_javascript is not None:
45 47 output.javascript = unicode(output_javascript)
46 48 if prompt_number is not None:
47 49 output.prompt_number = int(prompt_number)
48 50 return output
49 51
50 52
51 53 def new_code_cell(input=None, prompt_number=None, outputs=None, language=u'python'):
52 54 """Create a new code cell with input and output"""
53 55 cell = NotebookNode()
54 56 cell.cell_type = u'code'
55 57 if language is not None:
56 58 cell.language = unicode(language)
57 59 if input is not None:
58 60 cell.input = unicode(input)
59 61 if prompt_number is not None:
60 62 cell.prompt_number = int(prompt_number)
61 63 if outputs is None:
62 64 cell.outputs = []
63 65 else:
64 66 cell.outputs = outputs
65 67
66 68 return cell
67 69
68 70 def new_text_cell(cell_type, source=None, rendered=None):
69 71 """Create a new text cell."""
70 72 cell = NotebookNode()
71 73 if source is not None:
72 74 cell.source = unicode(source)
73 75 if rendered is not None:
74 76 cell.rendered = unicode(rendered)
75 77 cell.cell_type = cell_type
76 78 return cell
77 79
78 80
79 81 def new_worksheet(name=None, cells=None):
80 82 """Create a worksheet by name with with a list of cells."""
81 83 ws = NotebookNode()
82 84 if name is not None:
83 85 ws.name = unicode(name)
84 86 if cells is None:
85 87 ws.cells = []
86 88 else:
87 89 ws.cells = list(cells)
88 90 return ws
89 91
90 92
91 93 def new_notebook(name=None, id=None, worksheets=None):
92 94 """Create a notebook by name, id and a list of worksheets."""
93 95 nb = NotebookNode()
94 96 nb.nbformat = 2
95 97 if name is not None:
96 98 nb.name = unicode(name)
97 99 if id is None:
98 100 nb.id = unicode(uuid.uuid4())
99 101 else:
100 102 nb.id = unicode(id)
101 103 if worksheets is None:
102 104 nb.worksheets = []
103 105 else:
104 106 nb.worksheets = list(worksheets)
105 107 return nb
106 108
@@ -1,178 +1,180 b''
1 1 """Read and write notebook files as XML."""
2 2
3 3 from base64 import encodestring, decodestring
4 4 from xml.etree import ElementTree as ET
5 5
6 6 from .rwbase import NotebookReader, NotebookWriter
7 7 from .nbbase import (
8 8 new_code_cell, new_text_cell, new_worksheet, new_notebook, new_output
9 9 )
10 10
11 11 def indent(elem, level=0):
12 12 i = "\n" + level*" "
13 13 if len(elem):
14 14 if not elem.text or not elem.text.strip():
15 15 elem.text = i + " "
16 16 if not elem.tail or not elem.tail.strip():
17 17 elem.tail = i
18 18 for elem in elem:
19 19 indent(elem, level+1)
20 20 if not elem.tail or not elem.tail.strip():
21 21 elem.tail = i
22 22 else:
23 23 if level and (not elem.tail or not elem.tail.strip()):
24 24 elem.tail = i
25 25
26 26
27 27 def _get_text(e, tag):
28 28 sub_e = e.find(tag)
29 29 if sub_e is None:
30 30 return None
31 31 else:
32 32 return sub_e.text
33 33
34 34
35 35 def _set_text(nbnode, attr, parent, tag):
36 36 if attr in nbnode:
37 37 e = ET.SubElement(parent, tag)
38 38 e.text = nbnode[attr]
39 39
40 40
41 41 def _get_int(e, tag):
42 42 sub_e = e.find(tag)
43 43 if sub_e is None:
44 44 return None
45 45 else:
46 46 return int(sub_e.text)
47 47
48 48
49 49 def _set_int(nbnode, attr, parent, tag):
50 50 if attr in nbnode:
51 51 e = ET.SubElement(parent, tag)
52 52 e.text = unicode(nbnode[attr])
53 53
54 54
55 55 def _get_binary(e, tag):
56 56 sub_e = e.find(tag)
57 57 if sub_e is None:
58 58 return None
59 59 else:
60 60 return decodestring(sub_e.text)
61 61
62 62
63 63 def _set_binary(nbnode, attr, parent, tag):
64 64 if attr in nbnode:
65 65 e = ET.SubElement(parent, tag)
66 66 e.text = encodestring(nbnode[attr])
67 67
68 68
69 69 class XMLReader(NotebookReader):
70 70
71 71 def reads(self, s, **kwargs):
72 72 root = ET.fromstring(s)
73 73 return self.to_notebook(root, **kwargs)
74 74
75 75 def to_notebook(self, root, **kwargs):
76 76 nbname = _get_text(root,'name')
77 77 nbid = _get_text(root,'id')
78 78
79 79 worksheets = []
80 80 for ws_e in root.find('worksheets').getiterator('worksheet'):
81 81 wsname = _get_text(ws_e,'name')
82 82 cells = []
83 83 for cell_e in ws_e.find('cells').getiterator():
84 84 if cell_e.tag == 'codecell':
85 85 input = _get_text(cell_e,'input')
86 86 prompt_number = _get_int(cell_e,'prompt_number')
87 87 language = _get_text(cell_e,'language')
88 88 outputs = []
89 89 for output_e in cell_e.find('outputs').getiterator('output'):
90 90 out_prompt_number = _get_int(output_e,'prompt_number')
91 91 output_type = _get_text(output_e,'output_type')
92 92 output_text = _get_text(output_e,'text')
93 93 output_png = _get_binary(output_e,'png')
94 output_jpeg = _get_binary(output_e,'jpeg')
94 95 output_svg = _get_text(output_e,'svg')
95 96 output_html = _get_text(output_e,'html')
96 97 output_latex = _get_text(output_e,'latex')
97 98 output_json = _get_text(output_e,'json')
98 99 output_javascript = _get_text(output_e,'javascript')
99 100 output = new_output(output_type=output_type,output_png=output_png,
100 101 output_text=output_text,output_svg=output_svg,
101 102 output_html=output_html,output_latex=output_latex,
102 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 106 outputs.append(output)
106 107 cc = new_code_cell(input=input,prompt_number=prompt_number,
107 108 language=language,outputs=outputs)
108 109 cells.append(cc)
109 110 if cell_e.tag == 'htmlcell':
110 111 source = _get_text(cell_e,'source')
111 112 rendered = _get_text(cell_e,'rendered')
112 113 cells.append(new_text_cell(u'html', source=source, rendered=rendered))
113 114 if cell_e.tag == 'markdowncell':
114 115 source = _get_text(cell_e,'source')
115 116 rendered = _get_text(cell_e,'rendered')
116 117 cells.append(new_text_cell(u'markdown', source=source, rendered=rendered))
117 118 ws = new_worksheet(name=wsname,cells=cells)
118 119 worksheets.append(ws)
119 120
120 121 nb = new_notebook(name=nbname,id=nbid,worksheets=worksheets)
121 122 return nb
122 123
123 124
124 125 class XMLWriter(NotebookWriter):
125 126
126 127 def writes(self, nb, **kwargs):
127 128 nb_e = ET.Element('notebook')
128 129 _set_text(nb,'name',nb_e,'name')
129 130 _set_text(nb,'id',nb_e,'id')
130 131 _set_int(nb,'nbformat',nb_e,'nbformat')
131 132 wss_e = ET.SubElement(nb_e,'worksheets')
132 133 for ws in nb.worksheets:
133 134 ws_e = ET.SubElement(wss_e, 'worksheet')
134 135 _set_text(ws,'name',ws_e,'name')
135 136 cells_e = ET.SubElement(ws_e,'cells')
136 137 for cell in ws.cells:
137 138 cell_type = cell.cell_type
138 139 if cell_type == 'code':
139 140 cell_e = ET.SubElement(cells_e, 'codecell')
140 141 _set_text(cell,'input',cell_e,'input')
141 142 _set_text(cell,'language',cell_e,'language')
142 143 _set_int(cell,'prompt_number',cell_e,'prompt_number')
143 144 outputs_e = ET.SubElement(cell_e, 'outputs')
144 145 for output in cell.outputs:
145 146 output_e = ET.SubElement(outputs_e, 'output')
146 147 _set_int(output,'prompt_number',output_e,'prompt_number')
147 148 _set_text(output,'output_type',output_e,'output_type')
148 149 _set_text(output,'text',output_e,'text')
149 150 _set_binary(output,'png',output_e,'png')
151 _set_binary(output,'jpeg',output_e,'jpeg')
150 152 _set_text(output,'html',output_e,'html')
151 153 _set_text(output,'svg',output_e,'svg')
152 154 _set_text(output,'latex',output_e,'latex')
153 155 _set_text(output,'json',output_e,'json')
154 156 _set_text(output,'javascript',output_e,'javascript')
155 157 elif cell_type == 'html':
156 158 cell_e = ET.SubElement(cells_e, 'htmlcell')
157 159 _set_text(cell,'source',cell_e,'source')
158 160 _set_text(cell,'rendered',cell_e,'rendered')
159 161 elif cell_type == 'markdown':
160 162 cell_e = ET.SubElement(cells_e, 'markdowncell')
161 163 _set_text(cell,'source',cell_e,'source')
162 164 _set_text(cell,'rendered',cell_e,'rendered')
163 165
164 166 indent(nb_e)
165 167 txt = ET.tostring(nb_e, encoding="utf-8")
166 168 txt = '<?xml version="1.0" encoding="utf-8"?>\n' + txt
167 169 return txt
168 170
169 171
170 172 _reader = XMLReader()
171 173 _writer = XMLWriter()
172 174
173 175 reads = _reader.reads
174 176 read = _reader.read
175 177 to_notebook = _reader.to_notebook
176 178 write = _writer.write
177 179 writes = _writer.writes
178 180
@@ -1,46 +1,50 b''
1 1 from base64 import encodestring, decodestring
2 2 import pprint
3 3
4 4 def base64_decode(nb):
5 5 """Base64 encode all bytes objects in the notebook."""
6 6 for ws in nb.worksheets:
7 7 for cell in ws.cells:
8 8 if cell.cell_type == 'code':
9 9 if 'png' in cell:
10 10 cell.png = bytes(decodestring(cell.png))
11 if 'jpeg' in cell:
12 cell.jpeg = bytes(decodestring(cell.jpeg))
11 13 return nb
12 14
13 15
14 16 def base64_encode(nb):
15 17 """Base64 decode all binary objects in the notebook."""
16 18 for ws in nb.worksheets:
17 19 for cell in ws.cells:
18 20 if cell.cell_type == 'code':
19 21 if 'png' in cell:
20 22 cell.png = unicode(encodestring(cell.png))
23 if 'jpeg' in cell:
24 cell.jpeg = unicode(encodestring(cell.jpeg))
21 25 return nb
22 26
23 27
24 28 class NotebookReader(object):
25 29
26 30 def reads(self, s, **kwargs):
27 31 """Read a notebook from a string."""
28 32 raise NotImplementedError("loads must be implemented in a subclass")
29 33
30 34 def read(self, fp, **kwargs):
31 35 """Read a notebook from a file like object"""
32 36 return self.read(fp.read(), **kwargs)
33 37
34 38
35 39 class NotebookWriter(object):
36 40
37 41 def writes(self, nb, **kwargs):
38 42 """Write a notebook to a string."""
39 43 raise NotImplementedError("loads must be implemented in a subclass")
40 44
41 45 def write(self, nb, fp, **kwargs):
42 46 """Write a notebook to a file like object"""
43 47 return fp.write(self.writes(nb,**kwargs))
44 48
45 49
46 50
@@ -1,83 +1,85 b''
1 1 from ..nbbase import (
2 2 NotebookNode,
3 3 new_code_cell, new_text_cell, new_worksheet, new_notebook, new_output
4 4 )
5 5
6 6
7 7
8 8 ws = new_worksheet(name='worksheet1')
9 9
10 10 ws.cells.append(new_text_cell(
11 11 u'html',
12 12 source='Some NumPy Examples',
13 13 rendered='Some NumPy Examples'
14 14 ))
15 15
16 16
17 17 ws.cells.append(new_code_cell(
18 18 input='import numpy',
19 19 prompt_number=1
20 20 ))
21 21
22 22 ws.cells.append(new_text_cell(
23 23 u'markdown',
24 24 source='Some NumPy Examples',
25 25 rendered='Some NumPy Examples'
26 26 ))
27 27
28 28 ws.cells.append(new_code_cell(
29 29 input='a = numpy.random.rand(100)',
30 30 prompt_number=2
31 31 ))
32 32
33 33 ws.cells.append(new_code_cell(
34 34 input='print a',
35 35 prompt_number=3,
36 36 outputs=[new_output(
37 37 output_type=u'pyout',
38 38 output_text=u'<array a>',
39 39 output_html=u'The HTML rep',
40 40 output_latex=u'$a$',
41 41 output_png=b'data',
42 output_jpeg=b'data',
42 43 output_svg=u'<svg>',
43 44 output_json=u'json data',
44 45 output_javascript=u'var i=0;',
45 46 prompt_number=3
46 47 ),new_output(
47 48 output_type=u'display_data',
48 49 output_text=u'<array a>',
49 50 output_html=u'The HTML rep',
50 51 output_latex=u'$a$',
51 52 output_png=b'data',
53 output_jpeg=b'data',
52 54 output_svg=u'<svg>',
53 55 output_json=u'json data',
54 56 output_javascript=u'var i=0;',
55 57 prompt_number=4
56 58 )]
57 59 ))
58 60
59 61 nb0 = new_notebook(
60 62 name='nb0',
61 63 worksheets=[ws, new_worksheet(name='worksheet2')]
62 64 )
63 65
64 66 nb0_py = """# <nbformat>2</nbformat>
65 67
66 68 # <codecell>
67 69
68 70 import numpy
69 71
70 72 # </codecell>
71 73 # <codecell>
72 74
73 75 a = numpy.random.rand(100)
74 76
75 77 # </codecell>
76 78 # <codecell>
77 79
78 80 print a
79 81
80 82 # </codecell>
81 83 """
82 84
83 85
@@ -1,64 +1,68 b''
1 1 import __builtin__
2 2 from base64 import encodestring
3 3
4 4 from IPython.core.displayhook import DisplayHook
5 5 from IPython.utils.traitlets import Instance, Dict
6 6 from session import extract_header, Session
7 7
8 8 class ZMQDisplayHook(object):
9 9 """A simple displayhook that publishes the object's repr over a ZeroMQ
10 10 socket."""
11 11 topic=None
12 12
13 13 def __init__(self, session, pub_socket):
14 14 self.session = session
15 15 self.pub_socket = pub_socket
16 16 self.parent_header = {}
17 17
18 18 def __call__(self, obj):
19 19 if obj is None:
20 20 return
21 21
22 22 __builtin__._ = obj
23 23 msg = self.session.send(self.pub_socket, u'pyout', {u'data':repr(obj)},
24 24 parent=self.parent_header, ident=self.topic)
25 25
26 26 def set_parent(self, parent):
27 27 self.parent_header = extract_header(parent)
28 28
29 29
30 def _encode_png(data):
31 pngdata = data.get('image/png')
30 def _encode_binary(format_dict):
31 pngdata = format_dict.get('image/png')
32 32 if pngdata is not None:
33 data['image/png'] = encodestring(pngdata)
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 39 class ZMQShellDisplayHook(DisplayHook):
36 40 """A displayhook subclass that publishes data using ZeroMQ. This is intended
37 41 to work with an InteractiveShell instance. It sends a dict of different
38 42 representations of the object."""
39 43
40 44 session = Instance(Session)
41 45 pub_socket = Instance('zmq.Socket')
42 46 parent_header = Dict({})
43 47
44 48 def set_parent(self, parent):
45 49 """Set the parent for outbound messages."""
46 50 self.parent_header = extract_header(parent)
47 51
48 52 def start_displayhook(self):
49 53 self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header)
50 54
51 55 def write_output_prompt(self):
52 56 """Write the output prompt."""
53 57 if self.do_full_cache:
54 58 self.msg['content']['execution_count'] = self.prompt_count
55 59
56 60 def write_format_data(self, format_dict):
57 pngdata = format_dict.get('image/png')
58 _encode_png(format_dict)
61 _encode_binary(format_dict)
59 62 self.msg['content']['data'] = format_dict
60 63
61 64 def finish_displayhook(self):
62 65 """Finish up all displayhook activities."""
63 66 self.session.send(self.pub_socket, self.msg)
64 67 self.msg = None
68
@@ -1,457 +1,457 b''
1 1 """A ZMQ-based subclass of InteractiveShell.
2 2
3 3 This code is meant to ease the refactoring of the base InteractiveShell into
4 4 something with a cleaner architecture for 2-process use, without actually
5 5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
6 6 we subclass and override what we want to fix. Once this is working well, we
7 7 can go back to the base class and refactor the code for a cleaner inheritance
8 8 implementation that doesn't rely on so much monkeypatching.
9 9
10 10 But this lets us maintain a fully working IPython as we develop the new
11 11 machinery. This should thus be thought of as scaffolding.
12 12 """
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16 from __future__ import print_function
17 17
18 18 # Stdlib
19 19 import inspect
20 20 import os
21 21
22 22 # Our own
23 23 from IPython.core.interactiveshell import (
24 24 InteractiveShell, InteractiveShellABC
25 25 )
26 26 from IPython.core import page
27 27 from IPython.core.autocall import ZMQExitAutocall
28 28 from IPython.core.displaypub import DisplayPublisher
29 29 from IPython.core.macro import Macro
30 30 from IPython.core.magic import MacroToEdit
31 31 from IPython.core.payloadpage import install_payload_page
32 32 from IPython.utils import io
33 33 from IPython.utils.path import get_py_filename
34 34 from IPython.utils.traitlets import Instance, Type, Dict, CBool
35 35 from IPython.utils.warn import warn
36 from IPython.zmq.displayhook import ZMQShellDisplayHook, _encode_png
36 from IPython.zmq.displayhook import ZMQShellDisplayHook, _encode_binary
37 37 from IPython.zmq.session import extract_header
38 38 from session import Session
39 39
40 40 #-----------------------------------------------------------------------------
41 41 # Globals and side-effects
42 42 #-----------------------------------------------------------------------------
43 43
44 44 # Install the payload version of page.
45 45 install_payload_page()
46 46
47 47 #-----------------------------------------------------------------------------
48 48 # Functions and classes
49 49 #-----------------------------------------------------------------------------
50 50
51 51 class ZMQDisplayPublisher(DisplayPublisher):
52 52 """A display publisher that publishes data using a ZeroMQ PUB socket."""
53 53
54 54 session = Instance(Session)
55 55 pub_socket = Instance('zmq.Socket')
56 56 parent_header = Dict({})
57 57
58 58 def set_parent(self, parent):
59 59 """Set the parent for outbound messages."""
60 60 self.parent_header = extract_header(parent)
61 61
62 62 def publish(self, source, data, metadata=None):
63 63 if metadata is None:
64 64 metadata = {}
65 65 self._validate_data(source, data, metadata)
66 66 content = {}
67 67 content['source'] = source
68 _encode_png(data)
68 _encode_binary(data)
69 69 content['data'] = data
70 70 content['metadata'] = metadata
71 71 self.session.send(
72 72 self.pub_socket, u'display_data', content,
73 73 parent=self.parent_header
74 74 )
75 75
76 76
77 77 class ZMQInteractiveShell(InteractiveShell):
78 78 """A subclass of InteractiveShell for ZMQ."""
79 79
80 80 displayhook_class = Type(ZMQShellDisplayHook)
81 81 display_pub_class = Type(ZMQDisplayPublisher)
82 82
83 83 # Override the traitlet in the parent class, because there's no point using
84 84 # readline for the kernel. Can be removed when the readline code is moved
85 85 # to the terminal frontend.
86 86
87 87 # FIXME. This is disabled for now, even though it may cause problems under
88 88 # Windows, because it breaks %run in the Qt console. See gh-617 for more
89 89 # details. Re-enable once we've fully tested that %run works in the Qt
90 90 # console with syntax highlighting in tracebacks.
91 91 # readline_use = CBool(False)
92 92 # /FIXME
93 93
94 94 exiter = Instance(ZMQExitAutocall)
95 95 def _exiter_default(self):
96 96 return ZMQExitAutocall(self)
97 97
98 98 keepkernel_on_exit = None
99 99
100 100 def init_environment(self):
101 101 """Configure the user's environment.
102 102
103 103 """
104 104 env = os.environ
105 105 # These two ensure 'ls' produces nice coloring on BSD-derived systems
106 106 env['TERM'] = 'xterm-color'
107 107 env['CLICOLOR'] = '1'
108 108 # Since normal pagers don't work at all (over pexpect we don't have
109 109 # single-key control of the subprocess), try to disable paging in
110 110 # subprocesses as much as possible.
111 111 env['PAGER'] = 'cat'
112 112 env['GIT_PAGER'] = 'cat'
113 113
114 114 def auto_rewrite_input(self, cmd):
115 115 """Called to show the auto-rewritten input for autocall and friends.
116 116
117 117 FIXME: this payload is currently not correctly processed by the
118 118 frontend.
119 119 """
120 120 new = self.displayhook.prompt1.auto_rewrite() + cmd
121 121 payload = dict(
122 122 source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input',
123 123 transformed_input=new,
124 124 )
125 125 self.payload_manager.write_payload(payload)
126 126
127 127 def ask_exit(self):
128 128 """Engage the exit actions."""
129 129 payload = dict(
130 130 source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit',
131 131 exit=True,
132 132 keepkernel=self.keepkernel_on_exit,
133 133 )
134 134 self.payload_manager.write_payload(payload)
135 135
136 136 def _showtraceback(self, etype, evalue, stb):
137 137
138 138 exc_content = {
139 139 u'traceback' : stb,
140 140 u'ename' : unicode(etype.__name__),
141 141 u'evalue' : unicode(evalue)
142 142 }
143 143
144 144 dh = self.displayhook
145 145 # Send exception info over pub socket for other clients than the caller
146 146 # to pick up
147 147 exc_msg = dh.session.send(dh.pub_socket, u'pyerr', exc_content, dh.parent_header)
148 148
149 149 # FIXME - Hack: store exception info in shell object. Right now, the
150 150 # caller is reading this info after the fact, we need to fix this logic
151 151 # to remove this hack. Even uglier, we need to store the error status
152 152 # here, because in the main loop, the logic that sets it is being
153 153 # skipped because runlines swallows the exceptions.
154 154 exc_content[u'status'] = u'error'
155 155 self._reply_content = exc_content
156 156 # /FIXME
157 157
158 158 return exc_content
159 159
160 160 #------------------------------------------------------------------------
161 161 # Magic overrides
162 162 #------------------------------------------------------------------------
163 163 # Once the base class stops inheriting from magic, this code needs to be
164 164 # moved into a separate machinery as well. For now, at least isolate here
165 165 # the magics which this class needs to implement differently from the base
166 166 # class, or that are unique to it.
167 167
168 168 def magic_doctest_mode(self,parameter_s=''):
169 169 """Toggle doctest mode on and off.
170 170
171 171 This mode is intended to make IPython behave as much as possible like a
172 172 plain Python shell, from the perspective of how its prompts, exceptions
173 173 and output look. This makes it easy to copy and paste parts of a
174 174 session into doctests. It does so by:
175 175
176 176 - Changing the prompts to the classic ``>>>`` ones.
177 177 - Changing the exception reporting mode to 'Plain'.
178 178 - Disabling pretty-printing of output.
179 179
180 180 Note that IPython also supports the pasting of code snippets that have
181 181 leading '>>>' and '...' prompts in them. This means that you can paste
182 182 doctests from files or docstrings (even if they have leading
183 183 whitespace), and the code will execute correctly. You can then use
184 184 '%history -t' to see the translated history; this will give you the
185 185 input after removal of all the leading prompts and whitespace, which
186 186 can be pasted back into an editor.
187 187
188 188 With these features, you can switch into this mode easily whenever you
189 189 need to do testing and changes to doctests, without having to leave
190 190 your existing IPython session.
191 191 """
192 192
193 193 from IPython.utils.ipstruct import Struct
194 194
195 195 # Shorthands
196 196 shell = self.shell
197 197 disp_formatter = self.shell.display_formatter
198 198 ptformatter = disp_formatter.formatters['text/plain']
199 199 # dstore is a data store kept in the instance metadata bag to track any
200 200 # changes we make, so we can undo them later.
201 201 dstore = shell.meta.setdefault('doctest_mode', Struct())
202 202 save_dstore = dstore.setdefault
203 203
204 204 # save a few values we'll need to recover later
205 205 mode = save_dstore('mode', False)
206 206 save_dstore('rc_pprint', ptformatter.pprint)
207 207 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
208 208 save_dstore('xmode', shell.InteractiveTB.mode)
209 209
210 210 if mode == False:
211 211 # turn on
212 212 ptformatter.pprint = False
213 213 disp_formatter.plain_text_only = True
214 214 shell.magic_xmode('Plain')
215 215 else:
216 216 # turn off
217 217 ptformatter.pprint = dstore.rc_pprint
218 218 disp_formatter.plain_text_only = dstore.rc_plain_text_only
219 219 shell.magic_xmode(dstore.xmode)
220 220
221 221 # Store new mode and inform on console
222 222 dstore.mode = bool(1-int(mode))
223 223 mode_label = ['OFF','ON'][dstore.mode]
224 224 print('Doctest mode is:', mode_label)
225 225
226 226 # Send the payload back so that clients can modify their prompt display
227 227 payload = dict(
228 228 source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode',
229 229 mode=dstore.mode)
230 230 self.payload_manager.write_payload(payload)
231 231
232 232 def magic_edit(self,parameter_s='',last_call=['','']):
233 233 """Bring up an editor and execute the resulting code.
234 234
235 235 Usage:
236 236 %edit [options] [args]
237 237
238 238 %edit runs IPython's editor hook. The default version of this hook is
239 239 set to call the __IPYTHON__.rc.editor command. This is read from your
240 240 environment variable $EDITOR. If this isn't found, it will default to
241 241 vi under Linux/Unix and to notepad under Windows. See the end of this
242 242 docstring for how to change the editor hook.
243 243
244 244 You can also set the value of this editor via the command line option
245 245 '-editor' or in your ipythonrc file. This is useful if you wish to use
246 246 specifically for IPython an editor different from your typical default
247 247 (and for Windows users who typically don't set environment variables).
248 248
249 249 This command allows you to conveniently edit multi-line code right in
250 250 your IPython session.
251 251
252 252 If called without arguments, %edit opens up an empty editor with a
253 253 temporary file and will execute the contents of this file when you
254 254 close it (don't forget to save it!).
255 255
256 256
257 257 Options:
258 258
259 259 -n <number>: open the editor at a specified line number. By default,
260 260 the IPython editor hook uses the unix syntax 'editor +N filename', but
261 261 you can configure this by providing your own modified hook if your
262 262 favorite editor supports line-number specifications with a different
263 263 syntax.
264 264
265 265 -p: this will call the editor with the same data as the previous time
266 266 it was used, regardless of how long ago (in your current session) it
267 267 was.
268 268
269 269 -r: use 'raw' input. This option only applies to input taken from the
270 270 user's history. By default, the 'processed' history is used, so that
271 271 magics are loaded in their transformed version to valid Python. If
272 272 this option is given, the raw input as typed as the command line is
273 273 used instead. When you exit the editor, it will be executed by
274 274 IPython's own processor.
275 275
276 276 -x: do not execute the edited code immediately upon exit. This is
277 277 mainly useful if you are editing programs which need to be called with
278 278 command line arguments, which you can then do using %run.
279 279
280 280
281 281 Arguments:
282 282
283 283 If arguments are given, the following possibilites exist:
284 284
285 285 - The arguments are numbers or pairs of colon-separated numbers (like
286 286 1 4:8 9). These are interpreted as lines of previous input to be
287 287 loaded into the editor. The syntax is the same of the %macro command.
288 288
289 289 - If the argument doesn't start with a number, it is evaluated as a
290 290 variable and its contents loaded into the editor. You can thus edit
291 291 any string which contains python code (including the result of
292 292 previous edits).
293 293
294 294 - If the argument is the name of an object (other than a string),
295 295 IPython will try to locate the file where it was defined and open the
296 296 editor at the point where it is defined. You can use `%edit function`
297 297 to load an editor exactly at the point where 'function' is defined,
298 298 edit it and have the file be executed automatically.
299 299
300 300 If the object is a macro (see %macro for details), this opens up your
301 301 specified editor with a temporary file containing the macro's data.
302 302 Upon exit, the macro is reloaded with the contents of the file.
303 303
304 304 Note: opening at an exact line is only supported under Unix, and some
305 305 editors (like kedit and gedit up to Gnome 2.8) do not understand the
306 306 '+NUMBER' parameter necessary for this feature. Good editors like
307 307 (X)Emacs, vi, jed, pico and joe all do.
308 308
309 309 - If the argument is not found as a variable, IPython will look for a
310 310 file with that name (adding .py if necessary) and load it into the
311 311 editor. It will execute its contents with execfile() when you exit,
312 312 loading any code in the file into your interactive namespace.
313 313
314 314 After executing your code, %edit will return as output the code you
315 315 typed in the editor (except when it was an existing file). This way
316 316 you can reload the code in further invocations of %edit as a variable,
317 317 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
318 318 the output.
319 319
320 320 Note that %edit is also available through the alias %ed.
321 321
322 322 This is an example of creating a simple function inside the editor and
323 323 then modifying it. First, start up the editor:
324 324
325 325 In [1]: ed
326 326 Editing... done. Executing edited code...
327 327 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
328 328
329 329 We can then call the function foo():
330 330
331 331 In [2]: foo()
332 332 foo() was defined in an editing session
333 333
334 334 Now we edit foo. IPython automatically loads the editor with the
335 335 (temporary) file where foo() was previously defined:
336 336
337 337 In [3]: ed foo
338 338 Editing... done. Executing edited code...
339 339
340 340 And if we call foo() again we get the modified version:
341 341
342 342 In [4]: foo()
343 343 foo() has now been changed!
344 344
345 345 Here is an example of how to edit a code snippet successive
346 346 times. First we call the editor:
347 347
348 348 In [5]: ed
349 349 Editing... done. Executing edited code...
350 350 hello
351 351 Out[5]: "print 'hello'n"
352 352
353 353 Now we call it again with the previous output (stored in _):
354 354
355 355 In [6]: ed _
356 356 Editing... done. Executing edited code...
357 357 hello world
358 358 Out[6]: "print 'hello world'n"
359 359
360 360 Now we call it with the output #8 (stored in _8, also as Out[8]):
361 361
362 362 In [7]: ed _8
363 363 Editing... done. Executing edited code...
364 364 hello again
365 365 Out[7]: "print 'hello again'n"
366 366
367 367
368 368 Changing the default editor hook:
369 369
370 370 If you wish to write your own editor hook, you can put it in a
371 371 configuration file which you load at startup time. The default hook
372 372 is defined in the IPython.core.hooks module, and you can use that as a
373 373 starting example for further modifications. That file also has
374 374 general instructions on how to set a new hook for use once you've
375 375 defined it."""
376 376
377 377 opts,args = self.parse_options(parameter_s,'prn:')
378 378
379 379 try:
380 380 filename, lineno, _ = self._find_edit_target(args, opts, last_call)
381 381 except MacroToEdit as e:
382 382 # TODO: Implement macro editing over 2 processes.
383 383 print("Macro editing not yet implemented in 2-process model.")
384 384 return
385 385
386 386 # Make sure we send to the client an absolute path, in case the working
387 387 # directory of client and kernel don't match
388 388 filename = os.path.abspath(filename)
389 389
390 390 payload = {
391 391 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
392 392 'filename' : filename,
393 393 'line_number' : lineno
394 394 }
395 395 self.payload_manager.write_payload(payload)
396 396
397 397 def magic_gui(self, *args, **kwargs):
398 398 raise NotImplementedError(
399 399 'Kernel GUI support is not implemented yet, except for --pylab.')
400 400
401 401 def magic_pylab(self, *args, **kwargs):
402 402 raise NotImplementedError(
403 403 'pylab support must be enabled in command line options.')
404 404
405 405 # A few magics that are adapted to the specifics of using pexpect and a
406 406 # remote terminal
407 407
408 408 def magic_clear(self, arg_s):
409 409 """Clear the terminal."""
410 410 if os.name == 'posix':
411 411 self.shell.system("clear")
412 412 else:
413 413 self.shell.system("cls")
414 414
415 415 if os.name == 'nt':
416 416 # This is the usual name in windows
417 417 magic_cls = magic_clear
418 418
419 419 # Terminal pagers won't work over pexpect, but we do have our own pager
420 420
421 421 def magic_less(self, arg_s):
422 422 """Show a file through the pager.
423 423
424 424 Files ending in .py are syntax-highlighted."""
425 425 cont = open(arg_s).read()
426 426 if arg_s.endswith('.py'):
427 427 cont = self.shell.pycolorize(cont)
428 428 page.page(cont)
429 429
430 430 magic_more = magic_less
431 431
432 432 # Man calls a pager, so we also need to redefine it
433 433 if os.name == 'posix':
434 434 def magic_man(self, arg_s):
435 435 """Find the man page for the given command and display in pager."""
436 436 page.page(self.shell.getoutput('man %s | col -b' % arg_s,
437 437 split=False))
438 438
439 439 # FIXME: this is specific to the GUI, so we should let the gui app load
440 440 # magics at startup that are only for the gui. Once the gui app has proper
441 441 # profile and configuration management, we can have it initialize a kernel
442 442 # with a special config file that provides these.
443 443 def magic_guiref(self, arg_s):
444 444 """Show a basic reference about the GUI console."""
445 445 from IPython.core.usage import gui_reference
446 446 page.page(gui_reference, auto_html=True)
447 447
448 448 def set_next_input(self, text):
449 449 """Send the specified text to the frontend to be presented at the next
450 450 input cell."""
451 451 payload = dict(
452 452 source='IPython.zmq.zmqshell.ZMQInteractiveShell.set_next_input',
453 453 text=text
454 454 )
455 455 self.payload_manager.write_payload(payload)
456 456
457 457 InteractiveShellABC.register(ZMQInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now