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