##// END OF EJS Templates
Changing how IPython.utils.io.Term is handled....
Brian Granger -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,510 +1,510 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Pdb debugger class.
3 Pdb debugger class.
4
4
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 the command line completion of other programs which include this isn't
6 the command line completion of other programs which include this isn't
7 damaged.
7 damaged.
8
8
9 In the future, this class will be expanded with improvements over the standard
9 In the future, this class will be expanded with improvements over the standard
10 pdb.
10 pdb.
11
11
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 changes. Licensing should therefore be under the standard Python terms. For
13 changes. Licensing should therefore be under the standard Python terms. For
14 details on the PSF (Python Software Foundation) standard license, see:
14 details on the PSF (Python Software Foundation) standard license, see:
15
15
16 http://www.python.org/2.2.3/license.html"""
16 http://www.python.org/2.2.3/license.html"""
17
17
18 #*****************************************************************************
18 #*****************************************************************************
19 #
19 #
20 # This file is licensed under the PSF license.
20 # This file is licensed under the PSF license.
21 #
21 #
22 # Copyright (C) 2001 Python Software Foundation, www.python.org
22 # Copyright (C) 2001 Python Software Foundation, www.python.org
23 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
23 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
24 #
24 #
25 #
25 #
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 import bdb
28 import bdb
29 import linecache
29 import linecache
30 import sys
30 import sys
31
31
32 from IPython.utils import PyColorize
32 from IPython.utils import PyColorize
33 from IPython.core import ipapi
33 from IPython.core import ipapi
34 from IPython.utils import coloransi
34 from IPython.utils import coloransi
35 from IPython.utils.io import Term
35 import IPython.utils.io
36 from IPython.core.excolors import exception_colors
36 from IPython.core.excolors import exception_colors
37
37
38 # See if we can use pydb.
38 # See if we can use pydb.
39 has_pydb = False
39 has_pydb = False
40 prompt = 'ipdb> '
40 prompt = 'ipdb> '
41 #We have to check this directly from sys.argv, config struct not yet available
41 #We have to check this directly from sys.argv, config struct not yet available
42 if '-pydb' in sys.argv:
42 if '-pydb' in sys.argv:
43 try:
43 try:
44 import pydb
44 import pydb
45 if hasattr(pydb.pydb, "runl") and pydb.version>'1.17':
45 if hasattr(pydb.pydb, "runl") and pydb.version>'1.17':
46 # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we
46 # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we
47 # better protect against it.
47 # better protect against it.
48 has_pydb = True
48 has_pydb = True
49 except ImportError:
49 except ImportError:
50 print "Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available"
50 print "Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available"
51
51
52 if has_pydb:
52 if has_pydb:
53 from pydb import Pdb as OldPdb
53 from pydb import Pdb as OldPdb
54 #print "Using pydb for %run -d and post-mortem" #dbg
54 #print "Using pydb for %run -d and post-mortem" #dbg
55 prompt = 'ipydb> '
55 prompt = 'ipydb> '
56 else:
56 else:
57 from pdb import Pdb as OldPdb
57 from pdb import Pdb as OldPdb
58
58
59 # Allow the set_trace code to operate outside of an ipython instance, even if
59 # Allow the set_trace code to operate outside of an ipython instance, even if
60 # it does so with some limitations. The rest of this support is implemented in
60 # it does so with some limitations. The rest of this support is implemented in
61 # the Tracer constructor.
61 # the Tracer constructor.
62 def BdbQuit_excepthook(et,ev,tb):
62 def BdbQuit_excepthook(et,ev,tb):
63 if et==bdb.BdbQuit:
63 if et==bdb.BdbQuit:
64 print 'Exiting Debugger.'
64 print 'Exiting Debugger.'
65 else:
65 else:
66 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
66 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
67
67
68 def BdbQuit_IPython_excepthook(self,et,ev,tb):
68 def BdbQuit_IPython_excepthook(self,et,ev,tb):
69 print 'Exiting Debugger.'
69 print 'Exiting Debugger.'
70
70
71
71
72 class Tracer(object):
72 class Tracer(object):
73 """Class for local debugging, similar to pdb.set_trace.
73 """Class for local debugging, similar to pdb.set_trace.
74
74
75 Instances of this class, when called, behave like pdb.set_trace, but
75 Instances of this class, when called, behave like pdb.set_trace, but
76 providing IPython's enhanced capabilities.
76 providing IPython's enhanced capabilities.
77
77
78 This is implemented as a class which must be initialized in your own code
78 This is implemented as a class which must be initialized in your own code
79 and not as a standalone function because we need to detect at runtime
79 and not as a standalone function because we need to detect at runtime
80 whether IPython is already active or not. That detection is done in the
80 whether IPython is already active or not. That detection is done in the
81 constructor, ensuring that this code plays nicely with a running IPython,
81 constructor, ensuring that this code plays nicely with a running IPython,
82 while functioning acceptably (though with limitations) if outside of it.
82 while functioning acceptably (though with limitations) if outside of it.
83 """
83 """
84
84
85 def __init__(self,colors=None):
85 def __init__(self,colors=None):
86 """Create a local debugger instance.
86 """Create a local debugger instance.
87
87
88 :Parameters:
88 :Parameters:
89
89
90 - `colors` (None): a string containing the name of the color scheme to
90 - `colors` (None): a string containing the name of the color scheme to
91 use, it must be one of IPython's valid color schemes. If not given, the
91 use, it must be one of IPython's valid color schemes. If not given, the
92 function will default to the current IPython scheme when running inside
92 function will default to the current IPython scheme when running inside
93 IPython, and to 'NoColor' otherwise.
93 IPython, and to 'NoColor' otherwise.
94
94
95 Usage example:
95 Usage example:
96
96
97 from IPython.core.debugger import Tracer; debug_here = Tracer()
97 from IPython.core.debugger import Tracer; debug_here = Tracer()
98
98
99 ... later in your code
99 ... later in your code
100 debug_here() # -> will open up the debugger at that point.
100 debug_here() # -> will open up the debugger at that point.
101
101
102 Once the debugger activates, you can use all of its regular commands to
102 Once the debugger activates, you can use all of its regular commands to
103 step through code, set breakpoints, etc. See the pdb documentation
103 step through code, set breakpoints, etc. See the pdb documentation
104 from the Python standard library for usage details.
104 from the Python standard library for usage details.
105 """
105 """
106
106
107 try:
107 try:
108 ip = ipapi.get()
108 ip = ipapi.get()
109 except:
109 except:
110 # Outside of ipython, we set our own exception hook manually
110 # Outside of ipython, we set our own exception hook manually
111 BdbQuit_excepthook.excepthook_ori = sys.excepthook
111 BdbQuit_excepthook.excepthook_ori = sys.excepthook
112 sys.excepthook = BdbQuit_excepthook
112 sys.excepthook = BdbQuit_excepthook
113 def_colors = 'NoColor'
113 def_colors = 'NoColor'
114 try:
114 try:
115 # Limited tab completion support
115 # Limited tab completion support
116 import readline
116 import readline
117 readline.parse_and_bind('tab: complete')
117 readline.parse_and_bind('tab: complete')
118 except ImportError:
118 except ImportError:
119 pass
119 pass
120 else:
120 else:
121 # In ipython, we use its custom exception handler mechanism
121 # In ipython, we use its custom exception handler mechanism
122 def_colors = ip.colors
122 def_colors = ip.colors
123 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
123 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
124
124
125 if colors is None:
125 if colors is None:
126 colors = def_colors
126 colors = def_colors
127 self.debugger = Pdb(colors)
127 self.debugger = Pdb(colors)
128
128
129 def __call__(self):
129 def __call__(self):
130 """Starts an interactive debugger at the point where called.
130 """Starts an interactive debugger at the point where called.
131
131
132 This is similar to the pdb.set_trace() function from the std lib, but
132 This is similar to the pdb.set_trace() function from the std lib, but
133 using IPython's enhanced debugger."""
133 using IPython's enhanced debugger."""
134
134
135 self.debugger.set_trace(sys._getframe().f_back)
135 self.debugger.set_trace(sys._getframe().f_back)
136
136
137
137
138 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
138 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
139 """Make new_fn have old_fn's doc string. This is particularly useful
139 """Make new_fn have old_fn's doc string. This is particularly useful
140 for the do_... commands that hook into the help system.
140 for the do_... commands that hook into the help system.
141 Adapted from from a comp.lang.python posting
141 Adapted from from a comp.lang.python posting
142 by Duncan Booth."""
142 by Duncan Booth."""
143 def wrapper(*args, **kw):
143 def wrapper(*args, **kw):
144 return new_fn(*args, **kw)
144 return new_fn(*args, **kw)
145 if old_fn.__doc__:
145 if old_fn.__doc__:
146 wrapper.__doc__ = old_fn.__doc__ + additional_text
146 wrapper.__doc__ = old_fn.__doc__ + additional_text
147 return wrapper
147 return wrapper
148
148
149
149
150 def _file_lines(fname):
150 def _file_lines(fname):
151 """Return the contents of a named file as a list of lines.
151 """Return the contents of a named file as a list of lines.
152
152
153 This function never raises an IOError exception: if the file can't be
153 This function never raises an IOError exception: if the file can't be
154 read, it simply returns an empty list."""
154 read, it simply returns an empty list."""
155
155
156 try:
156 try:
157 outfile = open(fname)
157 outfile = open(fname)
158 except IOError:
158 except IOError:
159 return []
159 return []
160 else:
160 else:
161 out = outfile.readlines()
161 out = outfile.readlines()
162 outfile.close()
162 outfile.close()
163 return out
163 return out
164
164
165
165
166 class Pdb(OldPdb):
166 class Pdb(OldPdb):
167 """Modified Pdb class, does not load readline."""
167 """Modified Pdb class, does not load readline."""
168
168
169 def __init__(self,color_scheme='NoColor',completekey=None,
169 def __init__(self,color_scheme='NoColor',completekey=None,
170 stdin=None, stdout=None):
170 stdin=None, stdout=None):
171
171
172 # Parent constructor:
172 # Parent constructor:
173 if has_pydb and completekey is None:
173 if has_pydb and completekey is None:
174 OldPdb.__init__(self,stdin=stdin,stdout=Term.cout)
174 OldPdb.__init__(self,stdin=stdin,stdout=IPython.utils.io.Term.cout)
175 else:
175 else:
176 OldPdb.__init__(self,completekey,stdin,stdout)
176 OldPdb.__init__(self,completekey,stdin,stdout)
177
177
178 self.prompt = prompt # The default prompt is '(Pdb)'
178 self.prompt = prompt # The default prompt is '(Pdb)'
179
179
180 # IPython changes...
180 # IPython changes...
181 self.is_pydb = has_pydb
181 self.is_pydb = has_pydb
182
182
183 self.shell = ipapi.get()
183 self.shell = ipapi.get()
184
184
185 if self.is_pydb:
185 if self.is_pydb:
186
186
187 # interactiveshell.py's ipalias seems to want pdb's checkline
187 # interactiveshell.py's ipalias seems to want pdb's checkline
188 # which located in pydb.fn
188 # which located in pydb.fn
189 import pydb.fns
189 import pydb.fns
190 self.checkline = lambda filename, lineno: \
190 self.checkline = lambda filename, lineno: \
191 pydb.fns.checkline(self, filename, lineno)
191 pydb.fns.checkline(self, filename, lineno)
192
192
193 self.curframe = None
193 self.curframe = None
194 self.do_restart = self.new_do_restart
194 self.do_restart = self.new_do_restart
195
195
196 self.old_all_completions = self.shell.Completer.all_completions
196 self.old_all_completions = self.shell.Completer.all_completions
197 self.shell.Completer.all_completions=self.all_completions
197 self.shell.Completer.all_completions=self.all_completions
198
198
199 self.do_list = decorate_fn_with_doc(self.list_command_pydb,
199 self.do_list = decorate_fn_with_doc(self.list_command_pydb,
200 OldPdb.do_list)
200 OldPdb.do_list)
201 self.do_l = self.do_list
201 self.do_l = self.do_list
202 self.do_frame = decorate_fn_with_doc(self.new_do_frame,
202 self.do_frame = decorate_fn_with_doc(self.new_do_frame,
203 OldPdb.do_frame)
203 OldPdb.do_frame)
204
204
205 self.aliases = {}
205 self.aliases = {}
206
206
207 # Create color table: we copy the default one from the traceback
207 # Create color table: we copy the default one from the traceback
208 # module and add a few attributes needed for debugging
208 # module and add a few attributes needed for debugging
209 self.color_scheme_table = exception_colors()
209 self.color_scheme_table = exception_colors()
210
210
211 # shorthands
211 # shorthands
212 C = coloransi.TermColors
212 C = coloransi.TermColors
213 cst = self.color_scheme_table
213 cst = self.color_scheme_table
214
214
215 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
215 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
216 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
216 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
217
217
218 cst['Linux'].colors.breakpoint_enabled = C.LightRed
218 cst['Linux'].colors.breakpoint_enabled = C.LightRed
219 cst['Linux'].colors.breakpoint_disabled = C.Red
219 cst['Linux'].colors.breakpoint_disabled = C.Red
220
220
221 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
221 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
222 cst['LightBG'].colors.breakpoint_disabled = C.Red
222 cst['LightBG'].colors.breakpoint_disabled = C.Red
223
223
224 self.set_colors(color_scheme)
224 self.set_colors(color_scheme)
225
225
226 # Add a python parser so we can syntax highlight source while
226 # Add a python parser so we can syntax highlight source while
227 # debugging.
227 # debugging.
228 self.parser = PyColorize.Parser()
228 self.parser = PyColorize.Parser()
229
229
230 def set_colors(self, scheme):
230 def set_colors(self, scheme):
231 """Shorthand access to the color table scheme selector method."""
231 """Shorthand access to the color table scheme selector method."""
232 self.color_scheme_table.set_active_scheme(scheme)
232 self.color_scheme_table.set_active_scheme(scheme)
233
233
234 def interaction(self, frame, traceback):
234 def interaction(self, frame, traceback):
235 self.shell.set_completer_frame(frame)
235 self.shell.set_completer_frame(frame)
236 OldPdb.interaction(self, frame, traceback)
236 OldPdb.interaction(self, frame, traceback)
237
237
238 def new_do_up(self, arg):
238 def new_do_up(self, arg):
239 OldPdb.do_up(self, arg)
239 OldPdb.do_up(self, arg)
240 self.shell.set_completer_frame(self.curframe)
240 self.shell.set_completer_frame(self.curframe)
241 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
241 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
242
242
243 def new_do_down(self, arg):
243 def new_do_down(self, arg):
244 OldPdb.do_down(self, arg)
244 OldPdb.do_down(self, arg)
245 self.shell.set_completer_frame(self.curframe)
245 self.shell.set_completer_frame(self.curframe)
246
246
247 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
247 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
248
248
249 def new_do_frame(self, arg):
249 def new_do_frame(self, arg):
250 OldPdb.do_frame(self, arg)
250 OldPdb.do_frame(self, arg)
251 self.shell.set_completer_frame(self.curframe)
251 self.shell.set_completer_frame(self.curframe)
252
252
253 def new_do_quit(self, arg):
253 def new_do_quit(self, arg):
254
254
255 if hasattr(self, 'old_all_completions'):
255 if hasattr(self, 'old_all_completions'):
256 self.shell.Completer.all_completions=self.old_all_completions
256 self.shell.Completer.all_completions=self.old_all_completions
257
257
258
258
259 return OldPdb.do_quit(self, arg)
259 return OldPdb.do_quit(self, arg)
260
260
261 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
261 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
262
262
263 def new_do_restart(self, arg):
263 def new_do_restart(self, arg):
264 """Restart command. In the context of ipython this is exactly the same
264 """Restart command. In the context of ipython this is exactly the same
265 thing as 'quit'."""
265 thing as 'quit'."""
266 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
266 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
267 return self.do_quit(arg)
267 return self.do_quit(arg)
268
268
269 def postloop(self):
269 def postloop(self):
270 self.shell.set_completer_frame(None)
270 self.shell.set_completer_frame(None)
271
271
272 def print_stack_trace(self):
272 def print_stack_trace(self):
273 try:
273 try:
274 for frame_lineno in self.stack:
274 for frame_lineno in self.stack:
275 self.print_stack_entry(frame_lineno, context = 5)
275 self.print_stack_entry(frame_lineno, context = 5)
276 except KeyboardInterrupt:
276 except KeyboardInterrupt:
277 pass
277 pass
278
278
279 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
279 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
280 context = 3):
280 context = 3):
281 #frame, lineno = frame_lineno
281 #frame, lineno = frame_lineno
282 print >>Term.cout, self.format_stack_entry(frame_lineno, '', context)
282 print >>IPython.utils.io.Term.cout, self.format_stack_entry(frame_lineno, '', context)
283
283
284 # vds: >>
284 # vds: >>
285 frame, lineno = frame_lineno
285 frame, lineno = frame_lineno
286 filename = frame.f_code.co_filename
286 filename = frame.f_code.co_filename
287 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
287 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
288 # vds: <<
288 # vds: <<
289
289
290 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
290 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
291 import linecache, repr
291 import linecache, repr
292
292
293 ret = []
293 ret = []
294
294
295 Colors = self.color_scheme_table.active_colors
295 Colors = self.color_scheme_table.active_colors
296 ColorsNormal = Colors.Normal
296 ColorsNormal = Colors.Normal
297 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
297 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
298 tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
298 tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
299 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
299 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
300 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
300 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
301 ColorsNormal)
301 ColorsNormal)
302
302
303 frame, lineno = frame_lineno
303 frame, lineno = frame_lineno
304
304
305 return_value = ''
305 return_value = ''
306 if '__return__' in frame.f_locals:
306 if '__return__' in frame.f_locals:
307 rv = frame.f_locals['__return__']
307 rv = frame.f_locals['__return__']
308 #return_value += '->'
308 #return_value += '->'
309 return_value += repr.repr(rv) + '\n'
309 return_value += repr.repr(rv) + '\n'
310 ret.append(return_value)
310 ret.append(return_value)
311
311
312 #s = filename + '(' + `lineno` + ')'
312 #s = filename + '(' + `lineno` + ')'
313 filename = self.canonic(frame.f_code.co_filename)
313 filename = self.canonic(frame.f_code.co_filename)
314 link = tpl_link % filename
314 link = tpl_link % filename
315
315
316 if frame.f_code.co_name:
316 if frame.f_code.co_name:
317 func = frame.f_code.co_name
317 func = frame.f_code.co_name
318 else:
318 else:
319 func = "<lambda>"
319 func = "<lambda>"
320
320
321 call = ''
321 call = ''
322 if func != '?':
322 if func != '?':
323 if '__args__' in frame.f_locals:
323 if '__args__' in frame.f_locals:
324 args = repr.repr(frame.f_locals['__args__'])
324 args = repr.repr(frame.f_locals['__args__'])
325 else:
325 else:
326 args = '()'
326 args = '()'
327 call = tpl_call % (func, args)
327 call = tpl_call % (func, args)
328
328
329 # The level info should be generated in the same format pdb uses, to
329 # The level info should be generated in the same format pdb uses, to
330 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
330 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
331 if frame is self.curframe:
331 if frame is self.curframe:
332 ret.append('> ')
332 ret.append('> ')
333 else:
333 else:
334 ret.append(' ')
334 ret.append(' ')
335 ret.append('%s(%s)%s\n' % (link,lineno,call))
335 ret.append('%s(%s)%s\n' % (link,lineno,call))
336
336
337 start = lineno - 1 - context//2
337 start = lineno - 1 - context//2
338 lines = linecache.getlines(filename)
338 lines = linecache.getlines(filename)
339 start = max(start, 0)
339 start = max(start, 0)
340 start = min(start, len(lines) - context)
340 start = min(start, len(lines) - context)
341 lines = lines[start : start + context]
341 lines = lines[start : start + context]
342
342
343 for i,line in enumerate(lines):
343 for i,line in enumerate(lines):
344 show_arrow = (start + 1 + i == lineno)
344 show_arrow = (start + 1 + i == lineno)
345 linetpl = (frame is self.curframe or show_arrow) \
345 linetpl = (frame is self.curframe or show_arrow) \
346 and tpl_line_em \
346 and tpl_line_em \
347 or tpl_line
347 or tpl_line
348 ret.append(self.__format_line(linetpl, filename,
348 ret.append(self.__format_line(linetpl, filename,
349 start + 1 + i, line,
349 start + 1 + i, line,
350 arrow = show_arrow) )
350 arrow = show_arrow) )
351
351
352 return ''.join(ret)
352 return ''.join(ret)
353
353
354 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
354 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
355 bp_mark = ""
355 bp_mark = ""
356 bp_mark_color = ""
356 bp_mark_color = ""
357
357
358 scheme = self.color_scheme_table.active_scheme_name
358 scheme = self.color_scheme_table.active_scheme_name
359 new_line, err = self.parser.format2(line, 'str', scheme)
359 new_line, err = self.parser.format2(line, 'str', scheme)
360 if not err: line = new_line
360 if not err: line = new_line
361
361
362 bp = None
362 bp = None
363 if lineno in self.get_file_breaks(filename):
363 if lineno in self.get_file_breaks(filename):
364 bps = self.get_breaks(filename, lineno)
364 bps = self.get_breaks(filename, lineno)
365 bp = bps[-1]
365 bp = bps[-1]
366
366
367 if bp:
367 if bp:
368 Colors = self.color_scheme_table.active_colors
368 Colors = self.color_scheme_table.active_colors
369 bp_mark = str(bp.number)
369 bp_mark = str(bp.number)
370 bp_mark_color = Colors.breakpoint_enabled
370 bp_mark_color = Colors.breakpoint_enabled
371 if not bp.enabled:
371 if not bp.enabled:
372 bp_mark_color = Colors.breakpoint_disabled
372 bp_mark_color = Colors.breakpoint_disabled
373
373
374 numbers_width = 7
374 numbers_width = 7
375 if arrow:
375 if arrow:
376 # This is the line with the error
376 # This is the line with the error
377 pad = numbers_width - len(str(lineno)) - len(bp_mark)
377 pad = numbers_width - len(str(lineno)) - len(bp_mark)
378 if pad >= 3:
378 if pad >= 3:
379 marker = '-'*(pad-3) + '-> '
379 marker = '-'*(pad-3) + '-> '
380 elif pad == 2:
380 elif pad == 2:
381 marker = '> '
381 marker = '> '
382 elif pad == 1:
382 elif pad == 1:
383 marker = '>'
383 marker = '>'
384 else:
384 else:
385 marker = ''
385 marker = ''
386 num = '%s%s' % (marker, str(lineno))
386 num = '%s%s' % (marker, str(lineno))
387 line = tpl_line % (bp_mark_color + bp_mark, num, line)
387 line = tpl_line % (bp_mark_color + bp_mark, num, line)
388 else:
388 else:
389 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
389 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
390 line = tpl_line % (bp_mark_color + bp_mark, num, line)
390 line = tpl_line % (bp_mark_color + bp_mark, num, line)
391
391
392 return line
392 return line
393
393
394 def list_command_pydb(self, arg):
394 def list_command_pydb(self, arg):
395 """List command to use if we have a newer pydb installed"""
395 """List command to use if we have a newer pydb installed"""
396 filename, first, last = OldPdb.parse_list_cmd(self, arg)
396 filename, first, last = OldPdb.parse_list_cmd(self, arg)
397 if filename is not None:
397 if filename is not None:
398 self.print_list_lines(filename, first, last)
398 self.print_list_lines(filename, first, last)
399
399
400 def print_list_lines(self, filename, first, last):
400 def print_list_lines(self, filename, first, last):
401 """The printing (as opposed to the parsing part of a 'list'
401 """The printing (as opposed to the parsing part of a 'list'
402 command."""
402 command."""
403 try:
403 try:
404 Colors = self.color_scheme_table.active_colors
404 Colors = self.color_scheme_table.active_colors
405 ColorsNormal = Colors.Normal
405 ColorsNormal = Colors.Normal
406 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
406 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
407 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
407 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
408 src = []
408 src = []
409 for lineno in range(first, last+1):
409 for lineno in range(first, last+1):
410 line = linecache.getline(filename, lineno)
410 line = linecache.getline(filename, lineno)
411 if not line:
411 if not line:
412 break
412 break
413
413
414 if lineno == self.curframe.f_lineno:
414 if lineno == self.curframe.f_lineno:
415 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
415 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
416 else:
416 else:
417 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
417 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
418
418
419 src.append(line)
419 src.append(line)
420 self.lineno = lineno
420 self.lineno = lineno
421
421
422 print >>Term.cout, ''.join(src)
422 print >>IPython.utils.io.Term.cout, ''.join(src)
423
423
424 except KeyboardInterrupt:
424 except KeyboardInterrupt:
425 pass
425 pass
426
426
427 def do_list(self, arg):
427 def do_list(self, arg):
428 self.lastcmd = 'list'
428 self.lastcmd = 'list'
429 last = None
429 last = None
430 if arg:
430 if arg:
431 try:
431 try:
432 x = eval(arg, {}, {})
432 x = eval(arg, {}, {})
433 if type(x) == type(()):
433 if type(x) == type(()):
434 first, last = x
434 first, last = x
435 first = int(first)
435 first = int(first)
436 last = int(last)
436 last = int(last)
437 if last < first:
437 if last < first:
438 # Assume it's a count
438 # Assume it's a count
439 last = first + last
439 last = first + last
440 else:
440 else:
441 first = max(1, int(x) - 5)
441 first = max(1, int(x) - 5)
442 except:
442 except:
443 print '*** Error in argument:', `arg`
443 print '*** Error in argument:', `arg`
444 return
444 return
445 elif self.lineno is None:
445 elif self.lineno is None:
446 first = max(1, self.curframe.f_lineno - 5)
446 first = max(1, self.curframe.f_lineno - 5)
447 else:
447 else:
448 first = self.lineno + 1
448 first = self.lineno + 1
449 if last is None:
449 if last is None:
450 last = first + 10
450 last = first + 10
451 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
451 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
452
452
453 # vds: >>
453 # vds: >>
454 lineno = first
454 lineno = first
455 filename = self.curframe.f_code.co_filename
455 filename = self.curframe.f_code.co_filename
456 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
456 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
457 # vds: <<
457 # vds: <<
458
458
459 do_l = do_list
459 do_l = do_list
460
460
461 def do_pdef(self, arg):
461 def do_pdef(self, arg):
462 """The debugger interface to magic_pdef"""
462 """The debugger interface to magic_pdef"""
463 namespaces = [('Locals', self.curframe.f_locals),
463 namespaces = [('Locals', self.curframe.f_locals),
464 ('Globals', self.curframe.f_globals)]
464 ('Globals', self.curframe.f_globals)]
465 self.shell.magic_pdef(arg, namespaces=namespaces)
465 self.shell.magic_pdef(arg, namespaces=namespaces)
466
466
467 def do_pdoc(self, arg):
467 def do_pdoc(self, arg):
468 """The debugger interface to magic_pdoc"""
468 """The debugger interface to magic_pdoc"""
469 namespaces = [('Locals', self.curframe.f_locals),
469 namespaces = [('Locals', self.curframe.f_locals),
470 ('Globals', self.curframe.f_globals)]
470 ('Globals', self.curframe.f_globals)]
471 self.shell.magic_pdoc(arg, namespaces=namespaces)
471 self.shell.magic_pdoc(arg, namespaces=namespaces)
472
472
473 def do_pinfo(self, arg):
473 def do_pinfo(self, arg):
474 """The debugger equivalant of ?obj"""
474 """The debugger equivalant of ?obj"""
475 namespaces = [('Locals', self.curframe.f_locals),
475 namespaces = [('Locals', self.curframe.f_locals),
476 ('Globals', self.curframe.f_globals)]
476 ('Globals', self.curframe.f_globals)]
477 self.shell.magic_pinfo("pinfo %s" % arg, namespaces=namespaces)
477 self.shell.magic_pinfo("pinfo %s" % arg, namespaces=namespaces)
478
478
479 def checkline(self, filename, lineno):
479 def checkline(self, filename, lineno):
480 """Check whether specified line seems to be executable.
480 """Check whether specified line seems to be executable.
481
481
482 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
482 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
483 line or EOF). Warning: testing is not comprehensive.
483 line or EOF). Warning: testing is not comprehensive.
484 """
484 """
485 #######################################################################
485 #######################################################################
486 # XXX Hack! Use python-2.5 compatible code for this call, because with
486 # XXX Hack! Use python-2.5 compatible code for this call, because with
487 # all of our changes, we've drifted from the pdb api in 2.6. For now,
487 # all of our changes, we've drifted from the pdb api in 2.6. For now,
488 # changing:
488 # changing:
489 #
489 #
490 #line = linecache.getline(filename, lineno, self.curframe.f_globals)
490 #line = linecache.getline(filename, lineno, self.curframe.f_globals)
491 # to:
491 # to:
492 #
492 #
493 line = linecache.getline(filename, lineno)
493 line = linecache.getline(filename, lineno)
494 #
494 #
495 # does the trick. But in reality, we need to fix this by reconciling
495 # does the trick. But in reality, we need to fix this by reconciling
496 # our updates with the new Pdb APIs in Python 2.6.
496 # our updates with the new Pdb APIs in Python 2.6.
497 #
497 #
498 # End hack. The rest of this method is copied verbatim from 2.6 pdb.py
498 # End hack. The rest of this method is copied verbatim from 2.6 pdb.py
499 #######################################################################
499 #######################################################################
500
500
501 if not line:
501 if not line:
502 print >>self.stdout, 'End of file'
502 print >>self.stdout, 'End of file'
503 return 0
503 return 0
504 line = line.strip()
504 line = line.strip()
505 # Don't allow setting breakpoint at a blank line
505 # Don't allow setting breakpoint at a blank line
506 if (not line or (line[0] == '#') or
506 if (not line or (line[0] == '#') or
507 (line[:3] == '"""') or line[:3] == "'''"):
507 (line[:3] == '"""') or line[:3] == "'''"):
508 print >>self.stdout, '*** Blank or comment'
508 print >>self.stdout, '*** Blank or comment'
509 return 0
509 return 0
510 return lineno
510 return lineno
@@ -1,277 +1,278 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """ History related magics and functionality """
2 """ History related magics and functionality """
3
3
4 # Stdlib imports
4 # Stdlib imports
5 import fnmatch
5 import fnmatch
6 import os
6 import os
7
7
8 from IPython.utils.io import Term, ask_yes_no
8 import IPython.utils.io
9 from IPython.utils.io import ask_yes_no
9 from IPython.utils.warn import warn
10 from IPython.utils.warn import warn
10 from IPython.core import ipapi
11 from IPython.core import ipapi
11
12
12 def magic_history(self, parameter_s = ''):
13 def magic_history(self, parameter_s = ''):
13 """Print input history (_i<n> variables), with most recent last.
14 """Print input history (_i<n> variables), with most recent last.
14
15
15 %history -> print at most 40 inputs (some may be multi-line)\\
16 %history -> print at most 40 inputs (some may be multi-line)\\
16 %history n -> print at most n inputs\\
17 %history n -> print at most n inputs\\
17 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
18 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
18
19
19 By default, input history is printed without line numbers so it can be
20 By default, input history is printed without line numbers so it can be
20 directly pasted into an editor.
21 directly pasted into an editor.
21
22
22 With -n, each input's number <n> is shown, and is accessible as the
23 With -n, each input's number <n> is shown, and is accessible as the
23 automatically generated variable _i<n> as well as In[<n>]. Multi-line
24 automatically generated variable _i<n> as well as In[<n>]. Multi-line
24 statements are printed starting at a new line for easy copy/paste.
25 statements are printed starting at a new line for easy copy/paste.
25
26
26 Options:
27 Options:
27
28
28 -n: print line numbers for each input.
29 -n: print line numbers for each input.
29 This feature is only available if numbered prompts are in use.
30 This feature is only available if numbered prompts are in use.
30
31
31 -o: also print outputs for each input.
32 -o: also print outputs for each input.
32
33
33 -p: print classic '>>>' python prompts before each input. This is useful
34 -p: print classic '>>>' python prompts before each input. This is useful
34 for making documentation, and in conjunction with -o, for producing
35 for making documentation, and in conjunction with -o, for producing
35 doctest-ready output.
36 doctest-ready output.
36
37
37 -t: (default) print the 'translated' history, as IPython understands it.
38 -t: (default) print the 'translated' history, as IPython understands it.
38 IPython filters your input and converts it all into valid Python source
39 IPython filters your input and converts it all into valid Python source
39 before executing it (things like magics or aliases are turned into
40 before executing it (things like magics or aliases are turned into
40 function calls, for example). With this option, you'll see the native
41 function calls, for example). With this option, you'll see the native
41 history instead of the user-entered version: '%cd /' will be seen as
42 history instead of the user-entered version: '%cd /' will be seen as
42 '_ip.magic("%cd /")' instead of '%cd /'.
43 '_ip.magic("%cd /")' instead of '%cd /'.
43
44
44 -r: print the 'raw' history, i.e. the actual commands you typed.
45 -r: print the 'raw' history, i.e. the actual commands you typed.
45
46
46 -g: treat the arg as a pattern to grep for in (full) history.
47 -g: treat the arg as a pattern to grep for in (full) history.
47 This includes the "shadow history" (almost all commands ever written).
48 This includes the "shadow history" (almost all commands ever written).
48 Use '%hist -g' to show full shadow history (may be very long).
49 Use '%hist -g' to show full shadow history (may be very long).
49 In shadow history, every index nuwber starts with 0.
50 In shadow history, every index nuwber starts with 0.
50
51
51 -f FILENAME: instead of printing the output to the screen, redirect it to
52 -f FILENAME: instead of printing the output to the screen, redirect it to
52 the given file. The file is always overwritten, though IPython asks for
53 the given file. The file is always overwritten, though IPython asks for
53 confirmation first if it already exists.
54 confirmation first if it already exists.
54 """
55 """
55
56
56 if not self.outputcache.do_full_cache:
57 if not self.outputcache.do_full_cache:
57 print 'This feature is only available if numbered prompts are in use.'
58 print 'This feature is only available if numbered prompts are in use.'
58 return
59 return
59 opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list')
60 opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list')
60
61
61 # Check if output to specific file was requested.
62 # Check if output to specific file was requested.
62 try:
63 try:
63 outfname = opts['f']
64 outfname = opts['f']
64 except KeyError:
65 except KeyError:
65 outfile = Term.cout # default
66 outfile = IPython.utils.io.Term.cout # default
66 # We don't want to close stdout at the end!
67 # We don't want to close stdout at the end!
67 close_at_end = False
68 close_at_end = False
68 else:
69 else:
69 if os.path.exists(outfname):
70 if os.path.exists(outfname):
70 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
71 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
71 print 'Aborting.'
72 print 'Aborting.'
72 return
73 return
73
74
74 outfile = open(outfname,'w')
75 outfile = open(outfname,'w')
75 close_at_end = True
76 close_at_end = True
76
77
77 if 't' in opts:
78 if 't' in opts:
78 input_hist = self.input_hist
79 input_hist = self.input_hist
79 elif 'r' in opts:
80 elif 'r' in opts:
80 input_hist = self.input_hist_raw
81 input_hist = self.input_hist_raw
81 else:
82 else:
82 input_hist = self.input_hist
83 input_hist = self.input_hist
83
84
84 default_length = 40
85 default_length = 40
85 pattern = None
86 pattern = None
86 if 'g' in opts:
87 if 'g' in opts:
87 init = 1
88 init = 1
88 final = len(input_hist)
89 final = len(input_hist)
89 parts = parameter_s.split(None, 1)
90 parts = parameter_s.split(None, 1)
90 if len(parts) == 1:
91 if len(parts) == 1:
91 parts += '*'
92 parts += '*'
92 head, pattern = parts
93 head, pattern = parts
93 pattern = "*" + pattern + "*"
94 pattern = "*" + pattern + "*"
94 elif len(args) == 0:
95 elif len(args) == 0:
95 final = len(input_hist)-1
96 final = len(input_hist)-1
96 init = max(1,final-default_length)
97 init = max(1,final-default_length)
97 elif len(args) == 1:
98 elif len(args) == 1:
98 final = len(input_hist)
99 final = len(input_hist)
99 init = max(1, final-int(args[0]))
100 init = max(1, final-int(args[0]))
100 elif len(args) == 2:
101 elif len(args) == 2:
101 init, final = map(int, args)
102 init, final = map(int, args)
102 else:
103 else:
103 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
104 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
104 print >> Term.cout, self.magic_hist.__doc__
105 print >> IPython.utils.io.Term.cout, self.magic_hist.__doc__
105 return
106 return
106
107
107 width = len(str(final))
108 width = len(str(final))
108 line_sep = ['','\n']
109 line_sep = ['','\n']
109 print_nums = 'n' in opts
110 print_nums = 'n' in opts
110 print_outputs = 'o' in opts
111 print_outputs = 'o' in opts
111 pyprompts = 'p' in opts
112 pyprompts = 'p' in opts
112
113
113 found = False
114 found = False
114 if pattern is not None:
115 if pattern is not None:
115 sh = self.shadowhist.all()
116 sh = self.shadowhist.all()
116 for idx, s in sh:
117 for idx, s in sh:
117 if fnmatch.fnmatch(s, pattern):
118 if fnmatch.fnmatch(s, pattern):
118 print >> outfile, "0%d: %s" %(idx, s)
119 print >> outfile, "0%d: %s" %(idx, s)
119 found = True
120 found = True
120
121
121 if found:
122 if found:
122 print >> outfile, "==="
123 print >> outfile, "==="
123 print >> outfile, \
124 print >> outfile, \
124 "shadow history ends, fetch by %rep <number> (must start with 0)"
125 "shadow history ends, fetch by %rep <number> (must start with 0)"
125 print >> outfile, "=== start of normal history ==="
126 print >> outfile, "=== start of normal history ==="
126
127
127 for in_num in range(init,final):
128 for in_num in range(init,final):
128 inline = input_hist[in_num]
129 inline = input_hist[in_num]
129 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
130 if pattern is not None and not fnmatch.fnmatch(inline, pattern):
130 continue
131 continue
131
132
132 multiline = int(inline.count('\n') > 1)
133 multiline = int(inline.count('\n') > 1)
133 if print_nums:
134 if print_nums:
134 print >> outfile, \
135 print >> outfile, \
135 '%s:%s' % (str(in_num).ljust(width), line_sep[multiline]),
136 '%s:%s' % (str(in_num).ljust(width), line_sep[multiline]),
136 if pyprompts:
137 if pyprompts:
137 print >> outfile, '>>>',
138 print >> outfile, '>>>',
138 if multiline:
139 if multiline:
139 lines = inline.splitlines()
140 lines = inline.splitlines()
140 print >> outfile, '\n... '.join(lines)
141 print >> outfile, '\n... '.join(lines)
141 print >> outfile, '... '
142 print >> outfile, '... '
142 else:
143 else:
143 print >> outfile, inline,
144 print >> outfile, inline,
144 else:
145 else:
145 print >> outfile, inline,
146 print >> outfile, inline,
146 if print_outputs:
147 if print_outputs:
147 output = self.shell.user_ns['Out'].get(in_num)
148 output = self.shell.user_ns['Out'].get(in_num)
148 if output is not None:
149 if output is not None:
149 print >> outfile, repr(output)
150 print >> outfile, repr(output)
150
151
151 if close_at_end:
152 if close_at_end:
152 outfile.close()
153 outfile.close()
153
154
154
155
155 def magic_hist(self, parameter_s=''):
156 def magic_hist(self, parameter_s=''):
156 """Alternate name for %history."""
157 """Alternate name for %history."""
157 return self.magic_history(parameter_s)
158 return self.magic_history(parameter_s)
158
159
159
160
160 def rep_f(self, arg):
161 def rep_f(self, arg):
161 r""" Repeat a command, or get command to input line for editing
162 r""" Repeat a command, or get command to input line for editing
162
163
163 - %rep (no arguments):
164 - %rep (no arguments):
164
165
165 Place a string version of last computation result (stored in the special '_'
166 Place a string version of last computation result (stored in the special '_'
166 variable) to the next input prompt. Allows you to create elaborate command
167 variable) to the next input prompt. Allows you to create elaborate command
167 lines without using copy-paste::
168 lines without using copy-paste::
168
169
169 $ l = ["hei", "vaan"]
170 $ l = ["hei", "vaan"]
170 $ "".join(l)
171 $ "".join(l)
171 ==> heivaan
172 ==> heivaan
172 $ %rep
173 $ %rep
173 $ heivaan_ <== cursor blinking
174 $ heivaan_ <== cursor blinking
174
175
175 %rep 45
176 %rep 45
176
177
177 Place history line 45 to next input prompt. Use %hist to find out the
178 Place history line 45 to next input prompt. Use %hist to find out the
178 number.
179 number.
179
180
180 %rep 1-4 6-7 3
181 %rep 1-4 6-7 3
181
182
182 Repeat the specified lines immediately. Input slice syntax is the same as
183 Repeat the specified lines immediately. Input slice syntax is the same as
183 in %macro and %save.
184 in %macro and %save.
184
185
185 %rep foo
186 %rep foo
186
187
187 Place the most recent line that has the substring "foo" to next input.
188 Place the most recent line that has the substring "foo" to next input.
188 (e.g. 'svn ci -m foobar').
189 (e.g. 'svn ci -m foobar').
189 """
190 """
190
191
191 opts,args = self.parse_options(arg,'',mode='list')
192 opts,args = self.parse_options(arg,'',mode='list')
192 if not args:
193 if not args:
193 self.set_next_input(str(self.user_ns["_"]))
194 self.set_next_input(str(self.user_ns["_"]))
194 return
195 return
195
196
196 if len(args) == 1 and not '-' in args[0]:
197 if len(args) == 1 and not '-' in args[0]:
197 arg = args[0]
198 arg = args[0]
198 if len(arg) > 1 and arg.startswith('0'):
199 if len(arg) > 1 and arg.startswith('0'):
199 # get from shadow hist
200 # get from shadow hist
200 num = int(arg[1:])
201 num = int(arg[1:])
201 line = self.shadowhist.get(num)
202 line = self.shadowhist.get(num)
202 self.set_next_input(str(line))
203 self.set_next_input(str(line))
203 return
204 return
204 try:
205 try:
205 num = int(args[0])
206 num = int(args[0])
206 self.set_next_input(str(self.input_hist_raw[num]).rstrip())
207 self.set_next_input(str(self.input_hist_raw[num]).rstrip())
207 return
208 return
208 except ValueError:
209 except ValueError:
209 pass
210 pass
210
211
211 for h in reversed(self.input_hist_raw):
212 for h in reversed(self.input_hist_raw):
212 if 'rep' in h:
213 if 'rep' in h:
213 continue
214 continue
214 if fnmatch.fnmatch(h,'*' + arg + '*'):
215 if fnmatch.fnmatch(h,'*' + arg + '*'):
215 self.set_next_input(str(h).rstrip())
216 self.set_next_input(str(h).rstrip())
216 return
217 return
217
218
218 try:
219 try:
219 lines = self.extract_input_slices(args, True)
220 lines = self.extract_input_slices(args, True)
220 print "lines",lines
221 print "lines",lines
221 self.runlines(lines)
222 self.runlines(lines)
222 except ValueError:
223 except ValueError:
223 print "Not found in recent history:", args
224 print "Not found in recent history:", args
224
225
225
226
226 _sentinel = object()
227 _sentinel = object()
227
228
228 class ShadowHist(object):
229 class ShadowHist(object):
229 def __init__(self,db):
230 def __init__(self,db):
230 # cmd => idx mapping
231 # cmd => idx mapping
231 self.curidx = 0
232 self.curidx = 0
232 self.db = db
233 self.db = db
233 self.disabled = False
234 self.disabled = False
234
235
235 def inc_idx(self):
236 def inc_idx(self):
236 idx = self.db.get('shadowhist_idx', 1)
237 idx = self.db.get('shadowhist_idx', 1)
237 self.db['shadowhist_idx'] = idx + 1
238 self.db['shadowhist_idx'] = idx + 1
238 return idx
239 return idx
239
240
240 def add(self, ent):
241 def add(self, ent):
241 if self.disabled:
242 if self.disabled:
242 return
243 return
243 try:
244 try:
244 old = self.db.hget('shadowhist', ent, _sentinel)
245 old = self.db.hget('shadowhist', ent, _sentinel)
245 if old is not _sentinel:
246 if old is not _sentinel:
246 return
247 return
247 newidx = self.inc_idx()
248 newidx = self.inc_idx()
248 #print "new",newidx # dbg
249 #print "new",newidx # dbg
249 self.db.hset('shadowhist',ent, newidx)
250 self.db.hset('shadowhist',ent, newidx)
250 except:
251 except:
251 ipapi.get().showtraceback()
252 ipapi.get().showtraceback()
252 print "WARNING: disabling shadow history"
253 print "WARNING: disabling shadow history"
253 self.disabled = True
254 self.disabled = True
254
255
255 def all(self):
256 def all(self):
256 d = self.db.hdict('shadowhist')
257 d = self.db.hdict('shadowhist')
257 items = [(i,s) for (s,i) in d.items()]
258 items = [(i,s) for (s,i) in d.items()]
258 items.sort()
259 items.sort()
259 return items
260 return items
260
261
261 def get(self, idx):
262 def get(self, idx):
262 all = self.all()
263 all = self.all()
263
264
264 for k, v in all:
265 for k, v in all:
265 #print k,v
266 #print k,v
266 if k == idx:
267 if k == idx:
267 return v
268 return v
268
269
269
270
270 def init_ipython(ip):
271 def init_ipython(ip):
271 ip.define_magic("rep",rep_f)
272 ip.define_magic("rep",rep_f)
272 ip.define_magic("hist",magic_hist)
273 ip.define_magic("hist",magic_hist)
273 ip.define_magic("history",magic_history)
274 ip.define_magic("history",magic_history)
274
275
275 # XXX - ipy_completers are in quarantine, need to be updated to new apis
276 # XXX - ipy_completers are in quarantine, need to be updated to new apis
276 #import ipy_completers
277 #import ipy_completers
277 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
278 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
@@ -1,276 +1,276 b''
1 """hooks for IPython.
1 """hooks for IPython.
2
2
3 In Python, it is possible to overwrite any method of any object if you really
3 In Python, it is possible to overwrite any method of any object if you really
4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
4 want to. But IPython exposes a few 'hooks', methods which are _designed_ to
5 be overwritten by users for customization purposes. This module defines the
5 be overwritten by users for customization purposes. This module defines the
6 default versions of all such hooks, which get used by IPython if not
6 default versions of all such hooks, which get used by IPython if not
7 overridden by the user.
7 overridden by the user.
8
8
9 hooks are simple functions, but they should be declared with 'self' as their
9 hooks are simple functions, but they should be declared with 'self' as their
10 first argument, because when activated they are registered into IPython as
10 first argument, because when activated they are registered into IPython as
11 instance methods. The self argument will be the IPython running instance
11 instance methods. The self argument will be the IPython running instance
12 itself, so hooks have full access to the entire IPython object.
12 itself, so hooks have full access to the entire IPython object.
13
13
14 If you wish to define a new hook and activate it, you need to put the
14 If you wish to define a new hook and activate it, you need to put the
15 necessary code into a python file which can be either imported or execfile()'d
15 necessary code into a python file which can be either imported or execfile()'d
16 from within your ipythonrc configuration.
16 from within your ipythonrc configuration.
17
17
18 For example, suppose that you have a module called 'myiphooks' in your
18 For example, suppose that you have a module called 'myiphooks' in your
19 PYTHONPATH, which contains the following definition:
19 PYTHONPATH, which contains the following definition:
20
20
21 import os
21 import os
22 from IPython.core import ipapi
22 from IPython.core import ipapi
23 ip = ipapi.get()
23 ip = ipapi.get()
24
24
25 def calljed(self,filename, linenum):
25 def calljed(self,filename, linenum):
26 "My editor hook calls the jed editor directly."
26 "My editor hook calls the jed editor directly."
27 print "Calling my own editor, jed ..."
27 print "Calling my own editor, jed ..."
28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
29 raise TryNext()
29 raise TryNext()
30
30
31 ip.set_hook('editor', calljed)
31 ip.set_hook('editor', calljed)
32
32
33 You can then enable the functionality by doing 'import myiphooks'
33 You can then enable the functionality by doing 'import myiphooks'
34 somewhere in your configuration files or ipython command line.
34 somewhere in your configuration files or ipython command line.
35 """
35 """
36
36
37 #*****************************************************************************
37 #*****************************************************************************
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
38 # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu>
39 #
39 #
40 # Distributed under the terms of the BSD License. The full license is in
40 # Distributed under the terms of the BSD License. The full license is in
41 # the file COPYING, distributed as part of this software.
41 # the file COPYING, distributed as part of this software.
42 #*****************************************************************************
42 #*****************************************************************************
43
43
44 import os, bisect
44 import os, bisect
45 import sys
45 import sys
46
46
47 from pprint import PrettyPrinter
47 from pprint import PrettyPrinter
48
48
49 from IPython.utils.io import Term
49 import IPython.utils.io
50 from IPython.utils.process import shell
50 from IPython.utils.process import shell
51
51
52 from IPython.core.error import TryNext
52 from IPython.core.error import TryNext
53
53
54 # List here all the default hooks. For now it's just the editor functions
54 # List here all the default hooks. For now it's just the editor functions
55 # but over time we'll move here all the public API for user-accessible things.
55 # but over time we'll move here all the public API for user-accessible things.
56
56
57 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display',
57 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display',
58 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
58 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
59 'generate_prompt', 'generate_output_prompt','shell_hook',
59 'generate_prompt', 'generate_output_prompt','shell_hook',
60 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook',
60 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook',
61 'clipboard_get']
61 'clipboard_get']
62
62
63 pformat = PrettyPrinter().pformat
63 pformat = PrettyPrinter().pformat
64
64
65 def editor(self,filename, linenum=None):
65 def editor(self,filename, linenum=None):
66 """Open the default editor at the given filename and linenumber.
66 """Open the default editor at the given filename and linenumber.
67
67
68 This is IPython's default editor hook, you can use it as an example to
68 This is IPython's default editor hook, you can use it as an example to
69 write your own modified one. To set your own editor function as the
69 write your own modified one. To set your own editor function as the
70 new editor hook, call ip.set_hook('editor',yourfunc)."""
70 new editor hook, call ip.set_hook('editor',yourfunc)."""
71
71
72 # IPython configures a default editor at startup by reading $EDITOR from
72 # IPython configures a default editor at startup by reading $EDITOR from
73 # the environment, and falling back on vi (unix) or notepad (win32).
73 # the environment, and falling back on vi (unix) or notepad (win32).
74 editor = self.editor
74 editor = self.editor
75
75
76 # marker for at which line to open the file (for existing objects)
76 # marker for at which line to open the file (for existing objects)
77 if linenum is None or editor=='notepad':
77 if linenum is None or editor=='notepad':
78 linemark = ''
78 linemark = ''
79 else:
79 else:
80 linemark = '+%d' % int(linenum)
80 linemark = '+%d' % int(linenum)
81
81
82 # Enclose in quotes if necessary and legal
82 # Enclose in quotes if necessary and legal
83 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
83 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
84 editor = '"%s"' % editor
84 editor = '"%s"' % editor
85
85
86 # Call the actual editor
86 # Call the actual editor
87 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
87 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
88 raise TryNext()
88 raise TryNext()
89
89
90 import tempfile
90 import tempfile
91 def fix_error_editor(self,filename,linenum,column,msg):
91 def fix_error_editor(self,filename,linenum,column,msg):
92 """Open the editor at the given filename, linenumber, column and
92 """Open the editor at the given filename, linenumber, column and
93 show an error message. This is used for correcting syntax errors.
93 show an error message. This is used for correcting syntax errors.
94 The current implementation only has special support for the VIM editor,
94 The current implementation only has special support for the VIM editor,
95 and falls back on the 'editor' hook if VIM is not used.
95 and falls back on the 'editor' hook if VIM is not used.
96
96
97 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
97 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
98 """
98 """
99 def vim_quickfix_file():
99 def vim_quickfix_file():
100 t = tempfile.NamedTemporaryFile()
100 t = tempfile.NamedTemporaryFile()
101 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
101 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
102 t.flush()
102 t.flush()
103 return t
103 return t
104 if os.path.basename(self.editor) != 'vim':
104 if os.path.basename(self.editor) != 'vim':
105 self.hooks.editor(filename,linenum)
105 self.hooks.editor(filename,linenum)
106 return
106 return
107 t = vim_quickfix_file()
107 t = vim_quickfix_file()
108 try:
108 try:
109 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
109 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
110 raise TryNext()
110 raise TryNext()
111 finally:
111 finally:
112 t.close()
112 t.close()
113
113
114
114
115 def synchronize_with_editor(self, filename, linenum, column):
115 def synchronize_with_editor(self, filename, linenum, column):
116 pass
116 pass
117
117
118
118
119 class CommandChainDispatcher:
119 class CommandChainDispatcher:
120 """ Dispatch calls to a chain of commands until some func can handle it
120 """ Dispatch calls to a chain of commands until some func can handle it
121
121
122 Usage: instantiate, execute "add" to add commands (with optional
122 Usage: instantiate, execute "add" to add commands (with optional
123 priority), execute normally via f() calling mechanism.
123 priority), execute normally via f() calling mechanism.
124
124
125 """
125 """
126 def __init__(self,commands=None):
126 def __init__(self,commands=None):
127 if commands is None:
127 if commands is None:
128 self.chain = []
128 self.chain = []
129 else:
129 else:
130 self.chain = commands
130 self.chain = commands
131
131
132
132
133 def __call__(self,*args, **kw):
133 def __call__(self,*args, **kw):
134 """ Command chain is called just like normal func.
134 """ Command chain is called just like normal func.
135
135
136 This will call all funcs in chain with the same args as were given to this
136 This will call all funcs in chain with the same args as were given to this
137 function, and return the result of first func that didn't raise
137 function, and return the result of first func that didn't raise
138 TryNext """
138 TryNext """
139
139
140 for prio,cmd in self.chain:
140 for prio,cmd in self.chain:
141 #print "prio",prio,"cmd",cmd #dbg
141 #print "prio",prio,"cmd",cmd #dbg
142 try:
142 try:
143 return cmd(*args, **kw)
143 return cmd(*args, **kw)
144 except TryNext, exc:
144 except TryNext, exc:
145 if exc.args or exc.kwargs:
145 if exc.args or exc.kwargs:
146 args = exc.args
146 args = exc.args
147 kw = exc.kwargs
147 kw = exc.kwargs
148 # if no function will accept it, raise TryNext up to the caller
148 # if no function will accept it, raise TryNext up to the caller
149 raise TryNext
149 raise TryNext
150
150
151 def __str__(self):
151 def __str__(self):
152 return str(self.chain)
152 return str(self.chain)
153
153
154 def add(self, func, priority=0):
154 def add(self, func, priority=0):
155 """ Add a func to the cmd chain with given priority """
155 """ Add a func to the cmd chain with given priority """
156 bisect.insort(self.chain,(priority,func))
156 bisect.insort(self.chain,(priority,func))
157
157
158 def __iter__(self):
158 def __iter__(self):
159 """ Return all objects in chain.
159 """ Return all objects in chain.
160
160
161 Handy if the objects are not callable.
161 Handy if the objects are not callable.
162 """
162 """
163 return iter(self.chain)
163 return iter(self.chain)
164
164
165
165
166 def result_display(self,arg):
166 def result_display(self,arg):
167 """ Default display hook.
167 """ Default display hook.
168
168
169 Called for displaying the result to the user.
169 Called for displaying the result to the user.
170 """
170 """
171
171
172 if self.pprint:
172 if self.pprint:
173 out = pformat(arg)
173 out = pformat(arg)
174 if '\n' in out:
174 if '\n' in out:
175 # So that multi-line strings line up with the left column of
175 # So that multi-line strings line up with the left column of
176 # the screen, instead of having the output prompt mess up
176 # the screen, instead of having the output prompt mess up
177 # their first line.
177 # their first line.
178 Term.cout.write('\n')
178 IPython.utils.io.Term.cout.write('\n')
179 print >>Term.cout, out
179 print >>IPython.utils.io.Term.cout, out
180 else:
180 else:
181 # By default, the interactive prompt uses repr() to display results,
181 # By default, the interactive prompt uses repr() to display results,
182 # so we should honor this. Users who'd rather use a different
182 # so we should honor this. Users who'd rather use a different
183 # mechanism can easily override this hook.
183 # mechanism can easily override this hook.
184 print >>Term.cout, repr(arg)
184 print >>IPython.utils.io.Term.cout, repr(arg)
185 # the default display hook doesn't manipulate the value to put in history
185 # the default display hook doesn't manipulate the value to put in history
186 return None
186 return None
187
187
188
188
189 def input_prefilter(self,line):
189 def input_prefilter(self,line):
190 """ Default input prefilter
190 """ Default input prefilter
191
191
192 This returns the line as unchanged, so that the interpreter
192 This returns the line as unchanged, so that the interpreter
193 knows that nothing was done and proceeds with "classic" prefiltering
193 knows that nothing was done and proceeds with "classic" prefiltering
194 (%magics, !shell commands etc.).
194 (%magics, !shell commands etc.).
195
195
196 Note that leading whitespace is not passed to this hook. Prefilter
196 Note that leading whitespace is not passed to this hook. Prefilter
197 can't alter indentation.
197 can't alter indentation.
198
198
199 """
199 """
200 #print "attempt to rewrite",line #dbg
200 #print "attempt to rewrite",line #dbg
201 return line
201 return line
202
202
203
203
204 def shutdown_hook(self):
204 def shutdown_hook(self):
205 """ default shutdown hook
205 """ default shutdown hook
206
206
207 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
207 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
208 """
208 """
209
209
210 #print "default shutdown hook ok" # dbg
210 #print "default shutdown hook ok" # dbg
211 return
211 return
212
212
213
213
214 def late_startup_hook(self):
214 def late_startup_hook(self):
215 """ Executed after ipython has been constructed and configured
215 """ Executed after ipython has been constructed and configured
216
216
217 """
217 """
218 #print "default startup hook ok" # dbg
218 #print "default startup hook ok" # dbg
219
219
220
220
221 def generate_prompt(self, is_continuation):
221 def generate_prompt(self, is_continuation):
222 """ calculate and return a string with the prompt to display """
222 """ calculate and return a string with the prompt to display """
223 if is_continuation:
223 if is_continuation:
224 return str(self.outputcache.prompt2)
224 return str(self.outputcache.prompt2)
225 return str(self.outputcache.prompt1)
225 return str(self.outputcache.prompt1)
226
226
227
227
228 def generate_output_prompt(self):
228 def generate_output_prompt(self):
229 return str(self.outputcache.prompt_out)
229 return str(self.outputcache.prompt_out)
230
230
231
231
232 def shell_hook(self,cmd):
232 def shell_hook(self,cmd):
233 """ Run system/shell command a'la os.system() """
233 """ Run system/shell command a'la os.system() """
234
234
235 shell(cmd, header=self.system_header, verbose=self.system_verbose)
235 shell(cmd, header=self.system_header, verbose=self.system_verbose)
236
236
237
237
238 def show_in_pager(self,s):
238 def show_in_pager(self,s):
239 """ Run a string through pager """
239 """ Run a string through pager """
240 # raising TryNext here will use the default paging functionality
240 # raising TryNext here will use the default paging functionality
241 raise TryNext
241 raise TryNext
242
242
243
243
244 def pre_prompt_hook(self):
244 def pre_prompt_hook(self):
245 """ Run before displaying the next prompt
245 """ Run before displaying the next prompt
246
246
247 Use this e.g. to display output from asynchronous operations (in order
247 Use this e.g. to display output from asynchronous operations (in order
248 to not mess up text entry)
248 to not mess up text entry)
249 """
249 """
250
250
251 return None
251 return None
252
252
253
253
254 def pre_runcode_hook(self):
254 def pre_runcode_hook(self):
255 """ Executed before running the (prefiltered) code in IPython """
255 """ Executed before running the (prefiltered) code in IPython """
256 return None
256 return None
257
257
258
258
259 def clipboard_get(self):
259 def clipboard_get(self):
260 """ Get text from the clipboard.
260 """ Get text from the clipboard.
261 """
261 """
262 from IPython.lib.clipboard import (
262 from IPython.lib.clipboard import (
263 osx_clipboard_get, tkinter_clipboard_get,
263 osx_clipboard_get, tkinter_clipboard_get,
264 win32_clipboard_get
264 win32_clipboard_get
265 )
265 )
266 if sys.platform == 'win32':
266 if sys.platform == 'win32':
267 chain = [win32_clipboard_get, tkinter_clipboard_get]
267 chain = [win32_clipboard_get, tkinter_clipboard_get]
268 elif sys.platform == 'darwin':
268 elif sys.platform == 'darwin':
269 chain = [osx_clipboard_get, tkinter_clipboard_get]
269 chain = [osx_clipboard_get, tkinter_clipboard_get]
270 else:
270 else:
271 chain = [tkinter_clipboard_get]
271 chain = [tkinter_clipboard_get]
272 dispatcher = CommandChainDispatcher()
272 dispatcher = CommandChainDispatcher()
273 for func in chain:
273 for func in chain:
274 dispatcher.add(func)
274 dispatcher.add(func)
275 text = dispatcher()
275 text = dispatcher()
276 return text
276 return text
@@ -1,2044 +1,2060 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2010 The IPython Development Team
7 # Copyright (C) 2008-2010 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import with_statement
17 from __future__ import with_statement
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19
19
20 import __builtin__
20 import __builtin__
21 import abc
21 import abc
22 import codeop
22 import codeop
23 import exceptions
23 import exceptions
24 import new
24 import new
25 import os
25 import os
26 import re
26 import re
27 import string
27 import string
28 import sys
28 import sys
29 import tempfile
29 import tempfile
30 from contextlib import nested
30 from contextlib import nested
31
31
32 from IPython.core import debugger, oinspect
32 from IPython.core import debugger, oinspect
33 from IPython.core import history as ipcorehist
33 from IPython.core import history as ipcorehist
34 from IPython.core import prefilter
34 from IPython.core import prefilter
35 from IPython.core import shadowns
35 from IPython.core import shadowns
36 from IPython.core import ultratb
36 from IPython.core import ultratb
37 from IPython.core.alias import AliasManager
37 from IPython.core.alias import AliasManager
38 from IPython.core.builtin_trap import BuiltinTrap
38 from IPython.core.builtin_trap import BuiltinTrap
39 from IPython.config.configurable import Configurable
39 from IPython.config.configurable import Configurable
40 from IPython.core.display_trap import DisplayTrap
40 from IPython.core.display_trap import DisplayTrap
41 from IPython.core.error import UsageError
41 from IPython.core.error import UsageError
42 from IPython.core.extensions import ExtensionManager
42 from IPython.core.extensions import ExtensionManager
43 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
43 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
44 from IPython.core.inputlist import InputList
44 from IPython.core.inputlist import InputList
45 from IPython.core.logger import Logger
45 from IPython.core.logger import Logger
46 from IPython.core.magic import Magic
46 from IPython.core.magic import Magic
47 from IPython.core.plugin import PluginManager
47 from IPython.core.plugin import PluginManager
48 from IPython.core.prefilter import PrefilterManager
48 from IPython.core.prefilter import PrefilterManager
49 from IPython.core.prompts import CachedOutput
49 from IPython.core.prompts import CachedOutput
50 import IPython.core.hooks
50 import IPython.core.hooks
51 from IPython.external.Itpl import ItplNS
51 from IPython.external.Itpl import ItplNS
52 from IPython.utils import PyColorize
52 from IPython.utils import PyColorize
53 from IPython.utils import pickleshare
53 from IPython.utils import pickleshare
54 from IPython.utils.doctestreload import doctest_reload
54 from IPython.utils.doctestreload import doctest_reload
55 from IPython.utils.ipstruct import Struct
55 from IPython.utils.ipstruct import Struct
56 from IPython.utils.io import Term, ask_yes_no
56 import IPython.utils.io
57 from IPython.utils.io import ask_yes_no
57 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
58 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
58 from IPython.utils.process import getoutput, getoutputerror
59 from IPython.utils.process import getoutput, getoutputerror
59 from IPython.utils.strdispatch import StrDispatch
60 from IPython.utils.strdispatch import StrDispatch
60 from IPython.utils.syspathcontext import prepended_to_syspath
61 from IPython.utils.syspathcontext import prepended_to_syspath
61 from IPython.utils.text import num_ini_spaces
62 from IPython.utils.text import num_ini_spaces
62 from IPython.utils.warn import warn, error, fatal
63 from IPython.utils.warn import warn, error, fatal
63 from IPython.utils.traitlets import (
64 from IPython.utils.traitlets import (
64 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode, Instance
65 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode, Instance
65 )
66 )
66
67
67 # from IPython.utils import growl
68 # from IPython.utils import growl
68 # growl.start("IPython")
69 # growl.start("IPython")
69
70
70 #-----------------------------------------------------------------------------
71 #-----------------------------------------------------------------------------
71 # Globals
72 # Globals
72 #-----------------------------------------------------------------------------
73 #-----------------------------------------------------------------------------
73
74
74 # compiled regexps for autoindent management
75 # compiled regexps for autoindent management
75 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
76 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
76
77
77 #-----------------------------------------------------------------------------
78 #-----------------------------------------------------------------------------
78 # Utilities
79 # Utilities
79 #-----------------------------------------------------------------------------
80 #-----------------------------------------------------------------------------
80
81
81 # store the builtin raw_input globally, and use this always, in case user code
82 # store the builtin raw_input globally, and use this always, in case user code
82 # overwrites it (like wx.py.PyShell does)
83 # overwrites it (like wx.py.PyShell does)
83 raw_input_original = raw_input
84 raw_input_original = raw_input
84
85
85 def softspace(file, newvalue):
86 def softspace(file, newvalue):
86 """Copied from code.py, to remove the dependency"""
87 """Copied from code.py, to remove the dependency"""
87
88
88 oldvalue = 0
89 oldvalue = 0
89 try:
90 try:
90 oldvalue = file.softspace
91 oldvalue = file.softspace
91 except AttributeError:
92 except AttributeError:
92 pass
93 pass
93 try:
94 try:
94 file.softspace = newvalue
95 file.softspace = newvalue
95 except (AttributeError, TypeError):
96 except (AttributeError, TypeError):
96 # "attribute-less object" or "read-only attributes"
97 # "attribute-less object" or "read-only attributes"
97 pass
98 pass
98 return oldvalue
99 return oldvalue
99
100
100
101
101 def no_op(*a, **kw): pass
102 def no_op(*a, **kw): pass
102
103
103 class SpaceInInput(exceptions.Exception): pass
104 class SpaceInInput(exceptions.Exception): pass
104
105
105 class Bunch: pass
106 class Bunch: pass
106
107
107 class SyntaxTB(ultratb.ListTB):
108 class SyntaxTB(ultratb.ListTB):
108 """Extension which holds some state: the last exception value"""
109 """Extension which holds some state: the last exception value"""
109
110
110 def __init__(self,color_scheme = 'NoColor'):
111 def __init__(self,color_scheme = 'NoColor'):
111 ultratb.ListTB.__init__(self,color_scheme)
112 ultratb.ListTB.__init__(self,color_scheme)
112 self.last_syntax_error = None
113 self.last_syntax_error = None
113
114
114 def __call__(self, etype, value, elist):
115 def __call__(self, etype, value, elist):
115 self.last_syntax_error = value
116 self.last_syntax_error = value
116 ultratb.ListTB.__call__(self,etype,value,elist)
117 ultratb.ListTB.__call__(self,etype,value,elist)
117
118
118 def clear_err_state(self):
119 def clear_err_state(self):
119 """Return the current error state and clear it"""
120 """Return the current error state and clear it"""
120 e = self.last_syntax_error
121 e = self.last_syntax_error
121 self.last_syntax_error = None
122 self.last_syntax_error = None
122 return e
123 return e
123
124
124
125
125 def get_default_colors():
126 def get_default_colors():
126 if sys.platform=='darwin':
127 if sys.platform=='darwin':
127 return "LightBG"
128 return "LightBG"
128 elif os.name=='nt':
129 elif os.name=='nt':
129 return 'Linux'
130 return 'Linux'
130 else:
131 else:
131 return 'Linux'
132 return 'Linux'
132
133
133
134
134 class SeparateStr(Str):
135 class SeparateStr(Str):
135 """A Str subclass to validate separate_in, separate_out, etc.
136 """A Str subclass to validate separate_in, separate_out, etc.
136
137
137 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
138 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
138 """
139 """
139
140
140 def validate(self, obj, value):
141 def validate(self, obj, value):
141 if value == '0': value = ''
142 if value == '0': value = ''
142 value = value.replace('\\n','\n')
143 value = value.replace('\\n','\n')
143 return super(SeparateStr, self).validate(obj, value)
144 return super(SeparateStr, self).validate(obj, value)
144
145
145
146
146 #-----------------------------------------------------------------------------
147 #-----------------------------------------------------------------------------
147 # Main IPython class
148 # Main IPython class
148 #-----------------------------------------------------------------------------
149 #-----------------------------------------------------------------------------
149
150
150
151
151 class InteractiveShell(Configurable, Magic):
152 class InteractiveShell(Configurable, Magic):
152 """An enhanced, interactive shell for Python."""
153 """An enhanced, interactive shell for Python."""
153
154
154 autocall = Enum((0,1,2), default_value=1, config=True)
155 autocall = Enum((0,1,2), default_value=1, config=True)
155 # TODO: remove all autoindent logic and put into frontends.
156 # TODO: remove all autoindent logic and put into frontends.
156 # We can't do this yet because even runlines uses the autoindent.
157 # We can't do this yet because even runlines uses the autoindent.
157 autoindent = CBool(True, config=True)
158 autoindent = CBool(True, config=True)
158 automagic = CBool(True, config=True)
159 automagic = CBool(True, config=True)
159 cache_size = Int(1000, config=True)
160 cache_size = Int(1000, config=True)
160 color_info = CBool(True, config=True)
161 color_info = CBool(True, config=True)
161 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
162 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
162 default_value=get_default_colors(), config=True)
163 default_value=get_default_colors(), config=True)
163 debug = CBool(False, config=True)
164 debug = CBool(False, config=True)
164 deep_reload = CBool(False, config=True)
165 deep_reload = CBool(False, config=True)
165 filename = Str("<ipython console>")
166 filename = Str("<ipython console>")
166 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
167 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
167 logstart = CBool(False, config=True)
168 logstart = CBool(False, config=True)
168 logfile = Str('', config=True)
169 logfile = Str('', config=True)
169 logappend = Str('', config=True)
170 logappend = Str('', config=True)
170 object_info_string_level = Enum((0,1,2), default_value=0,
171 object_info_string_level = Enum((0,1,2), default_value=0,
171 config=True)
172 config=True)
172 pdb = CBool(False, config=True)
173 pdb = CBool(False, config=True)
173 pprint = CBool(True, config=True)
174 pprint = CBool(True, config=True)
174 profile = Str('', config=True)
175 profile = Str('', config=True)
175 prompt_in1 = Str('In [\\#]: ', config=True)
176 prompt_in1 = Str('In [\\#]: ', config=True)
176 prompt_in2 = Str(' .\\D.: ', config=True)
177 prompt_in2 = Str(' .\\D.: ', config=True)
177 prompt_out = Str('Out[\\#]: ', config=True)
178 prompt_out = Str('Out[\\#]: ', config=True)
178 prompts_pad_left = CBool(True, config=True)
179 prompts_pad_left = CBool(True, config=True)
179 quiet = CBool(False, config=True)
180 quiet = CBool(False, config=True)
180
181
181 # The readline stuff will eventually be moved to the terminal subclass
182 # The readline stuff will eventually be moved to the terminal subclass
182 # but for now, we can't do that as readline is welded in everywhere.
183 # but for now, we can't do that as readline is welded in everywhere.
183 readline_use = CBool(True, config=True)
184 readline_use = CBool(True, config=True)
184 readline_merge_completions = CBool(True, config=True)
185 readline_merge_completions = CBool(True, config=True)
185 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
186 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
186 readline_remove_delims = Str('-/~', config=True)
187 readline_remove_delims = Str('-/~', config=True)
187 readline_parse_and_bind = List([
188 readline_parse_and_bind = List([
188 'tab: complete',
189 'tab: complete',
189 '"\C-l": clear-screen',
190 '"\C-l": clear-screen',
190 'set show-all-if-ambiguous on',
191 'set show-all-if-ambiguous on',
191 '"\C-o": tab-insert',
192 '"\C-o": tab-insert',
192 '"\M-i": " "',
193 '"\M-i": " "',
193 '"\M-o": "\d\d\d\d"',
194 '"\M-o": "\d\d\d\d"',
194 '"\M-I": "\d\d\d\d"',
195 '"\M-I": "\d\d\d\d"',
195 '"\C-r": reverse-search-history',
196 '"\C-r": reverse-search-history',
196 '"\C-s": forward-search-history',
197 '"\C-s": forward-search-history',
197 '"\C-p": history-search-backward',
198 '"\C-p": history-search-backward',
198 '"\C-n": history-search-forward',
199 '"\C-n": history-search-forward',
199 '"\e[A": history-search-backward',
200 '"\e[A": history-search-backward',
200 '"\e[B": history-search-forward',
201 '"\e[B": history-search-forward',
201 '"\C-k": kill-line',
202 '"\C-k": kill-line',
202 '"\C-u": unix-line-discard',
203 '"\C-u": unix-line-discard',
203 ], allow_none=False, config=True)
204 ], allow_none=False, config=True)
204
205
205 # TODO: this part of prompt management should be moved to the frontends.
206 # TODO: this part of prompt management should be moved to the frontends.
206 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
207 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
207 separate_in = SeparateStr('\n', config=True)
208 separate_in = SeparateStr('\n', config=True)
208 separate_out = SeparateStr('', config=True)
209 separate_out = SeparateStr('', config=True)
209 separate_out2 = SeparateStr('', config=True)
210 separate_out2 = SeparateStr('', config=True)
210 system_header = Str('IPython system call: ', config=True)
211 system_header = Str('IPython system call: ', config=True)
211 system_verbose = CBool(False, config=True)
212 system_verbose = CBool(False, config=True)
212 wildcards_case_sensitive = CBool(True, config=True)
213 wildcards_case_sensitive = CBool(True, config=True)
213 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
214 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
214 default_value='Context', config=True)
215 default_value='Context', config=True)
215
216
216 # Subcomponents of InteractiveShell
217 # Subcomponents of InteractiveShell
217 alias_manager = Instance('IPython.core.alias.AliasManager')
218 alias_manager = Instance('IPython.core.alias.AliasManager')
218 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
219 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
219 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
220 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
220 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
221 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
221 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
222 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
222 plugin_manager = Instance('IPython.core.plugin.PluginManager')
223 plugin_manager = Instance('IPython.core.plugin.PluginManager')
223
224
224 def __init__(self, config=None, ipython_dir=None,
225 def __init__(self, config=None, ipython_dir=None,
225 user_ns=None, user_global_ns=None,
226 user_ns=None, user_global_ns=None,
226 custom_exceptions=((),None)):
227 custom_exceptions=((),None)):
227
228
228 # This is where traits with a config_key argument are updated
229 # This is where traits with a config_key argument are updated
229 # from the values on config.
230 # from the values on config.
230 super(InteractiveShell, self).__init__(config=config)
231 super(InteractiveShell, self).__init__(config=config)
231
232
232 # These are relatively independent and stateless
233 # These are relatively independent and stateless
233 self.init_ipython_dir(ipython_dir)
234 self.init_ipython_dir(ipython_dir)
234 self.init_instance_attrs()
235 self.init_instance_attrs()
235
236
236 # Create namespaces (user_ns, user_global_ns, etc.)
237 # Create namespaces (user_ns, user_global_ns, etc.)
237 self.init_create_namespaces(user_ns, user_global_ns)
238 self.init_create_namespaces(user_ns, user_global_ns)
238 # This has to be done after init_create_namespaces because it uses
239 # This has to be done after init_create_namespaces because it uses
239 # something in self.user_ns, but before init_sys_modules, which
240 # something in self.user_ns, but before init_sys_modules, which
240 # is the first thing to modify sys.
241 # is the first thing to modify sys.
241 self.save_sys_module_state()
242 self.save_sys_module_state()
242 self.init_sys_modules()
243 self.init_sys_modules()
243
244
244 self.init_history()
245 self.init_history()
245 self.init_encoding()
246 self.init_encoding()
246 self.init_prefilter()
247 self.init_prefilter()
247
248
248 Magic.__init__(self, self)
249 Magic.__init__(self, self)
249
250
250 self.init_syntax_highlighting()
251 self.init_syntax_highlighting()
251 self.init_hooks()
252 self.init_hooks()
252 self.init_pushd_popd_magic()
253 self.init_pushd_popd_magic()
254 # TODO: init_io() needs to happen before init_traceback handlers
255 # because the traceback handlers hardcode the stdout/stderr streams.
256 # This logic in in debugger.Pdb and should eventually be changed.
257 self.init_io()
253 self.init_traceback_handlers(custom_exceptions)
258 self.init_traceback_handlers(custom_exceptions)
254 self.init_user_ns()
259 self.init_user_ns()
255 self.init_logger()
260 self.init_logger()
256 self.init_alias()
261 self.init_alias()
257 self.init_builtins()
262 self.init_builtins()
258
263
259 # pre_config_initialization
264 # pre_config_initialization
260 self.init_shadow_hist()
265 self.init_shadow_hist()
261
266
262 # The next section should contain averything that was in ipmaker.
267 # The next section should contain averything that was in ipmaker.
263 self.init_logstart()
268 self.init_logstart()
264
269
265 # The following was in post_config_initialization
270 # The following was in post_config_initialization
266 self.init_inspector()
271 self.init_inspector()
267 self.init_readline()
272 self.init_readline()
268 self.init_prompts()
273 self.init_prompts()
269 self.init_displayhook()
274 self.init_displayhook()
270 self.init_reload_doctest()
275 self.init_reload_doctest()
271 self.init_magics()
276 self.init_magics()
272 self.init_pdb()
277 self.init_pdb()
273 self.init_extension_manager()
278 self.init_extension_manager()
274 self.init_plugin_manager()
279 self.init_plugin_manager()
275 self.hooks.late_startup_hook()
280 self.hooks.late_startup_hook()
276
281
277 @classmethod
282 @classmethod
278 def instance(cls, *args, **kwargs):
283 def instance(cls, *args, **kwargs):
279 """Returns a global InteractiveShell instance."""
284 """Returns a global InteractiveShell instance."""
280 if not hasattr(cls, "_instance"):
285 if not hasattr(cls, "_instance"):
281 cls._instance = cls(*args, **kwargs)
286 cls._instance = cls(*args, **kwargs)
282 return cls._instance
287 return cls._instance
283
288
284 @classmethod
289 @classmethod
285 def initialized(cls):
290 def initialized(cls):
286 return hasattr(cls, "_instance")
291 return hasattr(cls, "_instance")
287
292
288 def get_ipython(self):
293 def get_ipython(self):
289 """Return the currently running IPython instance."""
294 """Return the currently running IPython instance."""
290 return self
295 return self
291
296
292 #-------------------------------------------------------------------------
297 #-------------------------------------------------------------------------
293 # Trait changed handlers
298 # Trait changed handlers
294 #-------------------------------------------------------------------------
299 #-------------------------------------------------------------------------
295
300
296 def _ipython_dir_changed(self, name, new):
301 def _ipython_dir_changed(self, name, new):
297 if not os.path.isdir(new):
302 if not os.path.isdir(new):
298 os.makedirs(new, mode = 0777)
303 os.makedirs(new, mode = 0777)
299
304
300 def set_autoindent(self,value=None):
305 def set_autoindent(self,value=None):
301 """Set the autoindent flag, checking for readline support.
306 """Set the autoindent flag, checking for readline support.
302
307
303 If called with no arguments, it acts as a toggle."""
308 If called with no arguments, it acts as a toggle."""
304
309
305 if not self.has_readline:
310 if not self.has_readline:
306 if os.name == 'posix':
311 if os.name == 'posix':
307 warn("The auto-indent feature requires the readline library")
312 warn("The auto-indent feature requires the readline library")
308 self.autoindent = 0
313 self.autoindent = 0
309 return
314 return
310 if value is None:
315 if value is None:
311 self.autoindent = not self.autoindent
316 self.autoindent = not self.autoindent
312 else:
317 else:
313 self.autoindent = value
318 self.autoindent = value
314
319
315 #-------------------------------------------------------------------------
320 #-------------------------------------------------------------------------
316 # init_* methods called by __init__
321 # init_* methods called by __init__
317 #-------------------------------------------------------------------------
322 #-------------------------------------------------------------------------
318
323
319 def init_ipython_dir(self, ipython_dir):
324 def init_ipython_dir(self, ipython_dir):
320 if ipython_dir is not None:
325 if ipython_dir is not None:
321 self.ipython_dir = ipython_dir
326 self.ipython_dir = ipython_dir
322 self.config.Global.ipython_dir = self.ipython_dir
327 self.config.Global.ipython_dir = self.ipython_dir
323 return
328 return
324
329
325 if hasattr(self.config.Global, 'ipython_dir'):
330 if hasattr(self.config.Global, 'ipython_dir'):
326 self.ipython_dir = self.config.Global.ipython_dir
331 self.ipython_dir = self.config.Global.ipython_dir
327 else:
332 else:
328 self.ipython_dir = get_ipython_dir()
333 self.ipython_dir = get_ipython_dir()
329
334
330 # All children can just read this
335 # All children can just read this
331 self.config.Global.ipython_dir = self.ipython_dir
336 self.config.Global.ipython_dir = self.ipython_dir
332
337
333 def init_instance_attrs(self):
338 def init_instance_attrs(self):
334 self.more = False
339 self.more = False
335
340
336 # command compiler
341 # command compiler
337 self.compile = codeop.CommandCompiler()
342 self.compile = codeop.CommandCompiler()
338
343
339 # User input buffer
344 # User input buffer
340 self.buffer = []
345 self.buffer = []
341
346
342 # Make an empty namespace, which extension writers can rely on both
347 # Make an empty namespace, which extension writers can rely on both
343 # existing and NEVER being used by ipython itself. This gives them a
348 # existing and NEVER being used by ipython itself. This gives them a
344 # convenient location for storing additional information and state
349 # convenient location for storing additional information and state
345 # their extensions may require, without fear of collisions with other
350 # their extensions may require, without fear of collisions with other
346 # ipython names that may develop later.
351 # ipython names that may develop later.
347 self.meta = Struct()
352 self.meta = Struct()
348
353
349 # Object variable to store code object waiting execution. This is
354 # Object variable to store code object waiting execution. This is
350 # used mainly by the multithreaded shells, but it can come in handy in
355 # used mainly by the multithreaded shells, but it can come in handy in
351 # other situations. No need to use a Queue here, since it's a single
356 # other situations. No need to use a Queue here, since it's a single
352 # item which gets cleared once run.
357 # item which gets cleared once run.
353 self.code_to_run = None
358 self.code_to_run = None
354
359
355 # Temporary files used for various purposes. Deleted at exit.
360 # Temporary files used for various purposes. Deleted at exit.
356 self.tempfiles = []
361 self.tempfiles = []
357
362
358 # Keep track of readline usage (later set by init_readline)
363 # Keep track of readline usage (later set by init_readline)
359 self.has_readline = False
364 self.has_readline = False
360
365
361 # keep track of where we started running (mainly for crash post-mortem)
366 # keep track of where we started running (mainly for crash post-mortem)
362 # This is not being used anywhere currently.
367 # This is not being used anywhere currently.
363 self.starting_dir = os.getcwd()
368 self.starting_dir = os.getcwd()
364
369
365 # Indentation management
370 # Indentation management
366 self.indent_current_nsp = 0
371 self.indent_current_nsp = 0
367
372
368 def init_encoding(self):
373 def init_encoding(self):
369 # Get system encoding at startup time. Certain terminals (like Emacs
374 # Get system encoding at startup time. Certain terminals (like Emacs
370 # under Win32 have it set to None, and we need to have a known valid
375 # under Win32 have it set to None, and we need to have a known valid
371 # encoding to use in the raw_input() method
376 # encoding to use in the raw_input() method
372 try:
377 try:
373 self.stdin_encoding = sys.stdin.encoding or 'ascii'
378 self.stdin_encoding = sys.stdin.encoding or 'ascii'
374 except AttributeError:
379 except AttributeError:
375 self.stdin_encoding = 'ascii'
380 self.stdin_encoding = 'ascii'
376
381
377 def init_syntax_highlighting(self):
382 def init_syntax_highlighting(self):
378 # Python source parser/formatter for syntax highlighting
383 # Python source parser/formatter for syntax highlighting
379 pyformat = PyColorize.Parser().format
384 pyformat = PyColorize.Parser().format
380 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
385 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
381
386
382 def init_pushd_popd_magic(self):
387 def init_pushd_popd_magic(self):
383 # for pushd/popd management
388 # for pushd/popd management
384 try:
389 try:
385 self.home_dir = get_home_dir()
390 self.home_dir = get_home_dir()
386 except HomeDirError, msg:
391 except HomeDirError, msg:
387 fatal(msg)
392 fatal(msg)
388
393
389 self.dir_stack = []
394 self.dir_stack = []
390
395
391 def init_logger(self):
396 def init_logger(self):
392 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
397 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
393 # local shortcut, this is used a LOT
398 # local shortcut, this is used a LOT
394 self.log = self.logger.log
399 self.log = self.logger.log
395
400
396 def init_logstart(self):
401 def init_logstart(self):
397 if self.logappend:
402 if self.logappend:
398 self.magic_logstart(self.logappend + ' append')
403 self.magic_logstart(self.logappend + ' append')
399 elif self.logfile:
404 elif self.logfile:
400 self.magic_logstart(self.logfile)
405 self.magic_logstart(self.logfile)
401 elif self.logstart:
406 elif self.logstart:
402 self.magic_logstart()
407 self.magic_logstart()
403
408
404 def init_builtins(self):
409 def init_builtins(self):
405 self.builtin_trap = BuiltinTrap(shell=self)
410 self.builtin_trap = BuiltinTrap(shell=self)
406
411
407 def init_inspector(self):
412 def init_inspector(self):
408 # Object inspector
413 # Object inspector
409 self.inspector = oinspect.Inspector(oinspect.InspectColors,
414 self.inspector = oinspect.Inspector(oinspect.InspectColors,
410 PyColorize.ANSICodeColors,
415 PyColorize.ANSICodeColors,
411 'NoColor',
416 'NoColor',
412 self.object_info_string_level)
417 self.object_info_string_level)
413
418
419 def init_io(self):
420 import IPython.utils.io
421 if sys.platform == 'win32' and readline.have_readline and \
422 self.readline_use:
423 Term = IPython.utils.io.IOTerm(
424 cout=readline._outputfile,cerr=readline._outputfile
425 )
426 else:
427 Term = IPython.utils.io.IOTerm()
428 IPython.utils.io.Term = Term
429
414 def init_prompts(self):
430 def init_prompts(self):
415 # Initialize cache, set in/out prompts and printing system
431 # Initialize cache, set in/out prompts and printing system
416 self.outputcache = CachedOutput(self,
432 self.outputcache = CachedOutput(self,
417 self.cache_size,
433 self.cache_size,
418 self.pprint,
434 self.pprint,
419 input_sep = self.separate_in,
435 input_sep = self.separate_in,
420 output_sep = self.separate_out,
436 output_sep = self.separate_out,
421 output_sep2 = self.separate_out2,
437 output_sep2 = self.separate_out2,
422 ps1 = self.prompt_in1,
438 ps1 = self.prompt_in1,
423 ps2 = self.prompt_in2,
439 ps2 = self.prompt_in2,
424 ps_out = self.prompt_out,
440 ps_out = self.prompt_out,
425 pad_left = self.prompts_pad_left)
441 pad_left = self.prompts_pad_left)
426
442
427 # user may have over-ridden the default print hook:
443 # user may have over-ridden the default print hook:
428 try:
444 try:
429 self.outputcache.__class__.display = self.hooks.display
445 self.outputcache.__class__.display = self.hooks.display
430 except AttributeError:
446 except AttributeError:
431 pass
447 pass
432
448
433 def init_displayhook(self):
449 def init_displayhook(self):
434 self.display_trap = DisplayTrap(hook=self.outputcache)
450 self.display_trap = DisplayTrap(hook=self.outputcache)
435
451
436 def init_reload_doctest(self):
452 def init_reload_doctest(self):
437 # Do a proper resetting of doctest, including the necessary displayhook
453 # Do a proper resetting of doctest, including the necessary displayhook
438 # monkeypatching
454 # monkeypatching
439 try:
455 try:
440 doctest_reload()
456 doctest_reload()
441 except ImportError:
457 except ImportError:
442 warn("doctest module does not exist.")
458 warn("doctest module does not exist.")
443
459
444 #-------------------------------------------------------------------------
460 #-------------------------------------------------------------------------
445 # Things related to injections into the sys module
461 # Things related to injections into the sys module
446 #-------------------------------------------------------------------------
462 #-------------------------------------------------------------------------
447
463
448 def save_sys_module_state(self):
464 def save_sys_module_state(self):
449 """Save the state of hooks in the sys module.
465 """Save the state of hooks in the sys module.
450
466
451 This has to be called after self.user_ns is created.
467 This has to be called after self.user_ns is created.
452 """
468 """
453 self._orig_sys_module_state = {}
469 self._orig_sys_module_state = {}
454 self._orig_sys_module_state['stdin'] = sys.stdin
470 self._orig_sys_module_state['stdin'] = sys.stdin
455 self._orig_sys_module_state['stdout'] = sys.stdout
471 self._orig_sys_module_state['stdout'] = sys.stdout
456 self._orig_sys_module_state['stderr'] = sys.stderr
472 self._orig_sys_module_state['stderr'] = sys.stderr
457 self._orig_sys_module_state['excepthook'] = sys.excepthook
473 self._orig_sys_module_state['excepthook'] = sys.excepthook
458 try:
474 try:
459 self._orig_sys_modules_main_name = self.user_ns['__name__']
475 self._orig_sys_modules_main_name = self.user_ns['__name__']
460 except KeyError:
476 except KeyError:
461 pass
477 pass
462
478
463 def restore_sys_module_state(self):
479 def restore_sys_module_state(self):
464 """Restore the state of the sys module."""
480 """Restore the state of the sys module."""
465 try:
481 try:
466 for k, v in self._orig_sys_module_state.items():
482 for k, v in self._orig_sys_module_state.items():
467 setattr(sys, k, v)
483 setattr(sys, k, v)
468 except AttributeError:
484 except AttributeError:
469 pass
485 pass
470 try:
486 try:
471 delattr(sys, 'ipcompleter')
487 delattr(sys, 'ipcompleter')
472 except AttributeError:
488 except AttributeError:
473 pass
489 pass
474 # Reset what what done in self.init_sys_modules
490 # Reset what what done in self.init_sys_modules
475 try:
491 try:
476 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
492 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
477 except (AttributeError, KeyError):
493 except (AttributeError, KeyError):
478 pass
494 pass
479
495
480 #-------------------------------------------------------------------------
496 #-------------------------------------------------------------------------
481 # Things related to hooks
497 # Things related to hooks
482 #-------------------------------------------------------------------------
498 #-------------------------------------------------------------------------
483
499
484 def init_hooks(self):
500 def init_hooks(self):
485 # hooks holds pointers used for user-side customizations
501 # hooks holds pointers used for user-side customizations
486 self.hooks = Struct()
502 self.hooks = Struct()
487
503
488 self.strdispatchers = {}
504 self.strdispatchers = {}
489
505
490 # Set all default hooks, defined in the IPython.hooks module.
506 # Set all default hooks, defined in the IPython.hooks module.
491 hooks = IPython.core.hooks
507 hooks = IPython.core.hooks
492 for hook_name in hooks.__all__:
508 for hook_name in hooks.__all__:
493 # default hooks have priority 100, i.e. low; user hooks should have
509 # default hooks have priority 100, i.e. low; user hooks should have
494 # 0-100 priority
510 # 0-100 priority
495 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
511 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
496
512
497 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
513 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
498 """set_hook(name,hook) -> sets an internal IPython hook.
514 """set_hook(name,hook) -> sets an internal IPython hook.
499
515
500 IPython exposes some of its internal API as user-modifiable hooks. By
516 IPython exposes some of its internal API as user-modifiable hooks. By
501 adding your function to one of these hooks, you can modify IPython's
517 adding your function to one of these hooks, you can modify IPython's
502 behavior to call at runtime your own routines."""
518 behavior to call at runtime your own routines."""
503
519
504 # At some point in the future, this should validate the hook before it
520 # At some point in the future, this should validate the hook before it
505 # accepts it. Probably at least check that the hook takes the number
521 # accepts it. Probably at least check that the hook takes the number
506 # of args it's supposed to.
522 # of args it's supposed to.
507
523
508 f = new.instancemethod(hook,self,self.__class__)
524 f = new.instancemethod(hook,self,self.__class__)
509
525
510 # check if the hook is for strdispatcher first
526 # check if the hook is for strdispatcher first
511 if str_key is not None:
527 if str_key is not None:
512 sdp = self.strdispatchers.get(name, StrDispatch())
528 sdp = self.strdispatchers.get(name, StrDispatch())
513 sdp.add_s(str_key, f, priority )
529 sdp.add_s(str_key, f, priority )
514 self.strdispatchers[name] = sdp
530 self.strdispatchers[name] = sdp
515 return
531 return
516 if re_key is not None:
532 if re_key is not None:
517 sdp = self.strdispatchers.get(name, StrDispatch())
533 sdp = self.strdispatchers.get(name, StrDispatch())
518 sdp.add_re(re.compile(re_key), f, priority )
534 sdp.add_re(re.compile(re_key), f, priority )
519 self.strdispatchers[name] = sdp
535 self.strdispatchers[name] = sdp
520 return
536 return
521
537
522 dp = getattr(self.hooks, name, None)
538 dp = getattr(self.hooks, name, None)
523 if name not in IPython.core.hooks.__all__:
539 if name not in IPython.core.hooks.__all__:
524 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
540 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
525 if not dp:
541 if not dp:
526 dp = IPython.core.hooks.CommandChainDispatcher()
542 dp = IPython.core.hooks.CommandChainDispatcher()
527
543
528 try:
544 try:
529 dp.add(f,priority)
545 dp.add(f,priority)
530 except AttributeError:
546 except AttributeError:
531 # it was not commandchain, plain old func - replace
547 # it was not commandchain, plain old func - replace
532 dp = f
548 dp = f
533
549
534 setattr(self.hooks,name, dp)
550 setattr(self.hooks,name, dp)
535
551
536 #-------------------------------------------------------------------------
552 #-------------------------------------------------------------------------
537 # Things related to the "main" module
553 # Things related to the "main" module
538 #-------------------------------------------------------------------------
554 #-------------------------------------------------------------------------
539
555
540 def new_main_mod(self,ns=None):
556 def new_main_mod(self,ns=None):
541 """Return a new 'main' module object for user code execution.
557 """Return a new 'main' module object for user code execution.
542 """
558 """
543 main_mod = self._user_main_module
559 main_mod = self._user_main_module
544 init_fakemod_dict(main_mod,ns)
560 init_fakemod_dict(main_mod,ns)
545 return main_mod
561 return main_mod
546
562
547 def cache_main_mod(self,ns,fname):
563 def cache_main_mod(self,ns,fname):
548 """Cache a main module's namespace.
564 """Cache a main module's namespace.
549
565
550 When scripts are executed via %run, we must keep a reference to the
566 When scripts are executed via %run, we must keep a reference to the
551 namespace of their __main__ module (a FakeModule instance) around so
567 namespace of their __main__ module (a FakeModule instance) around so
552 that Python doesn't clear it, rendering objects defined therein
568 that Python doesn't clear it, rendering objects defined therein
553 useless.
569 useless.
554
570
555 This method keeps said reference in a private dict, keyed by the
571 This method keeps said reference in a private dict, keyed by the
556 absolute path of the module object (which corresponds to the script
572 absolute path of the module object (which corresponds to the script
557 path). This way, for multiple executions of the same script we only
573 path). This way, for multiple executions of the same script we only
558 keep one copy of the namespace (the last one), thus preventing memory
574 keep one copy of the namespace (the last one), thus preventing memory
559 leaks from old references while allowing the objects from the last
575 leaks from old references while allowing the objects from the last
560 execution to be accessible.
576 execution to be accessible.
561
577
562 Note: we can not allow the actual FakeModule instances to be deleted,
578 Note: we can not allow the actual FakeModule instances to be deleted,
563 because of how Python tears down modules (it hard-sets all their
579 because of how Python tears down modules (it hard-sets all their
564 references to None without regard for reference counts). This method
580 references to None without regard for reference counts). This method
565 must therefore make a *copy* of the given namespace, to allow the
581 must therefore make a *copy* of the given namespace, to allow the
566 original module's __dict__ to be cleared and reused.
582 original module's __dict__ to be cleared and reused.
567
583
568
584
569 Parameters
585 Parameters
570 ----------
586 ----------
571 ns : a namespace (a dict, typically)
587 ns : a namespace (a dict, typically)
572
588
573 fname : str
589 fname : str
574 Filename associated with the namespace.
590 Filename associated with the namespace.
575
591
576 Examples
592 Examples
577 --------
593 --------
578
594
579 In [10]: import IPython
595 In [10]: import IPython
580
596
581 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
597 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
582
598
583 In [12]: IPython.__file__ in _ip._main_ns_cache
599 In [12]: IPython.__file__ in _ip._main_ns_cache
584 Out[12]: True
600 Out[12]: True
585 """
601 """
586 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
602 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
587
603
588 def clear_main_mod_cache(self):
604 def clear_main_mod_cache(self):
589 """Clear the cache of main modules.
605 """Clear the cache of main modules.
590
606
591 Mainly for use by utilities like %reset.
607 Mainly for use by utilities like %reset.
592
608
593 Examples
609 Examples
594 --------
610 --------
595
611
596 In [15]: import IPython
612 In [15]: import IPython
597
613
598 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
614 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
599
615
600 In [17]: len(_ip._main_ns_cache) > 0
616 In [17]: len(_ip._main_ns_cache) > 0
601 Out[17]: True
617 Out[17]: True
602
618
603 In [18]: _ip.clear_main_mod_cache()
619 In [18]: _ip.clear_main_mod_cache()
604
620
605 In [19]: len(_ip._main_ns_cache) == 0
621 In [19]: len(_ip._main_ns_cache) == 0
606 Out[19]: True
622 Out[19]: True
607 """
623 """
608 self._main_ns_cache.clear()
624 self._main_ns_cache.clear()
609
625
610 #-------------------------------------------------------------------------
626 #-------------------------------------------------------------------------
611 # Things related to debugging
627 # Things related to debugging
612 #-------------------------------------------------------------------------
628 #-------------------------------------------------------------------------
613
629
614 def init_pdb(self):
630 def init_pdb(self):
615 # Set calling of pdb on exceptions
631 # Set calling of pdb on exceptions
616 # self.call_pdb is a property
632 # self.call_pdb is a property
617 self.call_pdb = self.pdb
633 self.call_pdb = self.pdb
618
634
619 def _get_call_pdb(self):
635 def _get_call_pdb(self):
620 return self._call_pdb
636 return self._call_pdb
621
637
622 def _set_call_pdb(self,val):
638 def _set_call_pdb(self,val):
623
639
624 if val not in (0,1,False,True):
640 if val not in (0,1,False,True):
625 raise ValueError,'new call_pdb value must be boolean'
641 raise ValueError,'new call_pdb value must be boolean'
626
642
627 # store value in instance
643 # store value in instance
628 self._call_pdb = val
644 self._call_pdb = val
629
645
630 # notify the actual exception handlers
646 # notify the actual exception handlers
631 self.InteractiveTB.call_pdb = val
647 self.InteractiveTB.call_pdb = val
632
648
633 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
649 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
634 'Control auto-activation of pdb at exceptions')
650 'Control auto-activation of pdb at exceptions')
635
651
636 def debugger(self,force=False):
652 def debugger(self,force=False):
637 """Call the pydb/pdb debugger.
653 """Call the pydb/pdb debugger.
638
654
639 Keywords:
655 Keywords:
640
656
641 - force(False): by default, this routine checks the instance call_pdb
657 - force(False): by default, this routine checks the instance call_pdb
642 flag and does not actually invoke the debugger if the flag is false.
658 flag and does not actually invoke the debugger if the flag is false.
643 The 'force' option forces the debugger to activate even if the flag
659 The 'force' option forces the debugger to activate even if the flag
644 is false.
660 is false.
645 """
661 """
646
662
647 if not (force or self.call_pdb):
663 if not (force or self.call_pdb):
648 return
664 return
649
665
650 if not hasattr(sys,'last_traceback'):
666 if not hasattr(sys,'last_traceback'):
651 error('No traceback has been produced, nothing to debug.')
667 error('No traceback has been produced, nothing to debug.')
652 return
668 return
653
669
654 # use pydb if available
670 # use pydb if available
655 if debugger.has_pydb:
671 if debugger.has_pydb:
656 from pydb import pm
672 from pydb import pm
657 else:
673 else:
658 # fallback to our internal debugger
674 # fallback to our internal debugger
659 pm = lambda : self.InteractiveTB.debugger(force=True)
675 pm = lambda : self.InteractiveTB.debugger(force=True)
660 self.history_saving_wrapper(pm)()
676 self.history_saving_wrapper(pm)()
661
677
662 #-------------------------------------------------------------------------
678 #-------------------------------------------------------------------------
663 # Things related to IPython's various namespaces
679 # Things related to IPython's various namespaces
664 #-------------------------------------------------------------------------
680 #-------------------------------------------------------------------------
665
681
666 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
682 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
667 # Create the namespace where the user will operate. user_ns is
683 # Create the namespace where the user will operate. user_ns is
668 # normally the only one used, and it is passed to the exec calls as
684 # normally the only one used, and it is passed to the exec calls as
669 # the locals argument. But we do carry a user_global_ns namespace
685 # the locals argument. But we do carry a user_global_ns namespace
670 # given as the exec 'globals' argument, This is useful in embedding
686 # given as the exec 'globals' argument, This is useful in embedding
671 # situations where the ipython shell opens in a context where the
687 # situations where the ipython shell opens in a context where the
672 # distinction between locals and globals is meaningful. For
688 # distinction between locals and globals is meaningful. For
673 # non-embedded contexts, it is just the same object as the user_ns dict.
689 # non-embedded contexts, it is just the same object as the user_ns dict.
674
690
675 # FIXME. For some strange reason, __builtins__ is showing up at user
691 # FIXME. For some strange reason, __builtins__ is showing up at user
676 # level as a dict instead of a module. This is a manual fix, but I
692 # level as a dict instead of a module. This is a manual fix, but I
677 # should really track down where the problem is coming from. Alex
693 # should really track down where the problem is coming from. Alex
678 # Schmolck reported this problem first.
694 # Schmolck reported this problem first.
679
695
680 # A useful post by Alex Martelli on this topic:
696 # A useful post by Alex Martelli on this topic:
681 # Re: inconsistent value from __builtins__
697 # Re: inconsistent value from __builtins__
682 # Von: Alex Martelli <aleaxit@yahoo.com>
698 # Von: Alex Martelli <aleaxit@yahoo.com>
683 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
699 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
684 # Gruppen: comp.lang.python
700 # Gruppen: comp.lang.python
685
701
686 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
702 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
687 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
703 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
688 # > <type 'dict'>
704 # > <type 'dict'>
689 # > >>> print type(__builtins__)
705 # > >>> print type(__builtins__)
690 # > <type 'module'>
706 # > <type 'module'>
691 # > Is this difference in return value intentional?
707 # > Is this difference in return value intentional?
692
708
693 # Well, it's documented that '__builtins__' can be either a dictionary
709 # Well, it's documented that '__builtins__' can be either a dictionary
694 # or a module, and it's been that way for a long time. Whether it's
710 # or a module, and it's been that way for a long time. Whether it's
695 # intentional (or sensible), I don't know. In any case, the idea is
711 # intentional (or sensible), I don't know. In any case, the idea is
696 # that if you need to access the built-in namespace directly, you
712 # that if you need to access the built-in namespace directly, you
697 # should start with "import __builtin__" (note, no 's') which will
713 # should start with "import __builtin__" (note, no 's') which will
698 # definitely give you a module. Yeah, it's somewhat confusing:-(.
714 # definitely give you a module. Yeah, it's somewhat confusing:-(.
699
715
700 # These routines return properly built dicts as needed by the rest of
716 # These routines return properly built dicts as needed by the rest of
701 # the code, and can also be used by extension writers to generate
717 # the code, and can also be used by extension writers to generate
702 # properly initialized namespaces.
718 # properly initialized namespaces.
703 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
719 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
704
720
705 # Assign namespaces
721 # Assign namespaces
706 # This is the namespace where all normal user variables live
722 # This is the namespace where all normal user variables live
707 self.user_ns = user_ns
723 self.user_ns = user_ns
708 self.user_global_ns = user_global_ns
724 self.user_global_ns = user_global_ns
709
725
710 # An auxiliary namespace that checks what parts of the user_ns were
726 # An auxiliary namespace that checks what parts of the user_ns were
711 # loaded at startup, so we can list later only variables defined in
727 # loaded at startup, so we can list later only variables defined in
712 # actual interactive use. Since it is always a subset of user_ns, it
728 # actual interactive use. Since it is always a subset of user_ns, it
713 # doesn't need to be separately tracked in the ns_table.
729 # doesn't need to be separately tracked in the ns_table.
714 self.user_ns_hidden = {}
730 self.user_ns_hidden = {}
715
731
716 # A namespace to keep track of internal data structures to prevent
732 # A namespace to keep track of internal data structures to prevent
717 # them from cluttering user-visible stuff. Will be updated later
733 # them from cluttering user-visible stuff. Will be updated later
718 self.internal_ns = {}
734 self.internal_ns = {}
719
735
720 # Now that FakeModule produces a real module, we've run into a nasty
736 # Now that FakeModule produces a real module, we've run into a nasty
721 # problem: after script execution (via %run), the module where the user
737 # problem: after script execution (via %run), the module where the user
722 # code ran is deleted. Now that this object is a true module (needed
738 # code ran is deleted. Now that this object is a true module (needed
723 # so docetst and other tools work correctly), the Python module
739 # so docetst and other tools work correctly), the Python module
724 # teardown mechanism runs over it, and sets to None every variable
740 # teardown mechanism runs over it, and sets to None every variable
725 # present in that module. Top-level references to objects from the
741 # present in that module. Top-level references to objects from the
726 # script survive, because the user_ns is updated with them. However,
742 # script survive, because the user_ns is updated with them. However,
727 # calling functions defined in the script that use other things from
743 # calling functions defined in the script that use other things from
728 # the script will fail, because the function's closure had references
744 # the script will fail, because the function's closure had references
729 # to the original objects, which are now all None. So we must protect
745 # to the original objects, which are now all None. So we must protect
730 # these modules from deletion by keeping a cache.
746 # these modules from deletion by keeping a cache.
731 #
747 #
732 # To avoid keeping stale modules around (we only need the one from the
748 # To avoid keeping stale modules around (we only need the one from the
733 # last run), we use a dict keyed with the full path to the script, so
749 # last run), we use a dict keyed with the full path to the script, so
734 # only the last version of the module is held in the cache. Note,
750 # only the last version of the module is held in the cache. Note,
735 # however, that we must cache the module *namespace contents* (their
751 # however, that we must cache the module *namespace contents* (their
736 # __dict__). Because if we try to cache the actual modules, old ones
752 # __dict__). Because if we try to cache the actual modules, old ones
737 # (uncached) could be destroyed while still holding references (such as
753 # (uncached) could be destroyed while still holding references (such as
738 # those held by GUI objects that tend to be long-lived)>
754 # those held by GUI objects that tend to be long-lived)>
739 #
755 #
740 # The %reset command will flush this cache. See the cache_main_mod()
756 # The %reset command will flush this cache. See the cache_main_mod()
741 # and clear_main_mod_cache() methods for details on use.
757 # and clear_main_mod_cache() methods for details on use.
742
758
743 # This is the cache used for 'main' namespaces
759 # This is the cache used for 'main' namespaces
744 self._main_ns_cache = {}
760 self._main_ns_cache = {}
745 # And this is the single instance of FakeModule whose __dict__ we keep
761 # And this is the single instance of FakeModule whose __dict__ we keep
746 # copying and clearing for reuse on each %run
762 # copying and clearing for reuse on each %run
747 self._user_main_module = FakeModule()
763 self._user_main_module = FakeModule()
748
764
749 # A table holding all the namespaces IPython deals with, so that
765 # A table holding all the namespaces IPython deals with, so that
750 # introspection facilities can search easily.
766 # introspection facilities can search easily.
751 self.ns_table = {'user':user_ns,
767 self.ns_table = {'user':user_ns,
752 'user_global':user_global_ns,
768 'user_global':user_global_ns,
753 'internal':self.internal_ns,
769 'internal':self.internal_ns,
754 'builtin':__builtin__.__dict__
770 'builtin':__builtin__.__dict__
755 }
771 }
756
772
757 # Similarly, track all namespaces where references can be held and that
773 # Similarly, track all namespaces where references can be held and that
758 # we can safely clear (so it can NOT include builtin). This one can be
774 # we can safely clear (so it can NOT include builtin). This one can be
759 # a simple list.
775 # a simple list.
760 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
776 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
761 self.internal_ns, self._main_ns_cache ]
777 self.internal_ns, self._main_ns_cache ]
762
778
763 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
779 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
764 """Return a valid local and global user interactive namespaces.
780 """Return a valid local and global user interactive namespaces.
765
781
766 This builds a dict with the minimal information needed to operate as a
782 This builds a dict with the minimal information needed to operate as a
767 valid IPython user namespace, which you can pass to the various
783 valid IPython user namespace, which you can pass to the various
768 embedding classes in ipython. The default implementation returns the
784 embedding classes in ipython. The default implementation returns the
769 same dict for both the locals and the globals to allow functions to
785 same dict for both the locals and the globals to allow functions to
770 refer to variables in the namespace. Customized implementations can
786 refer to variables in the namespace. Customized implementations can
771 return different dicts. The locals dictionary can actually be anything
787 return different dicts. The locals dictionary can actually be anything
772 following the basic mapping protocol of a dict, but the globals dict
788 following the basic mapping protocol of a dict, but the globals dict
773 must be a true dict, not even a subclass. It is recommended that any
789 must be a true dict, not even a subclass. It is recommended that any
774 custom object for the locals namespace synchronize with the globals
790 custom object for the locals namespace synchronize with the globals
775 dict somehow.
791 dict somehow.
776
792
777 Raises TypeError if the provided globals namespace is not a true dict.
793 Raises TypeError if the provided globals namespace is not a true dict.
778
794
779 Parameters
795 Parameters
780 ----------
796 ----------
781 user_ns : dict-like, optional
797 user_ns : dict-like, optional
782 The current user namespace. The items in this namespace should
798 The current user namespace. The items in this namespace should
783 be included in the output. If None, an appropriate blank
799 be included in the output. If None, an appropriate blank
784 namespace should be created.
800 namespace should be created.
785 user_global_ns : dict, optional
801 user_global_ns : dict, optional
786 The current user global namespace. The items in this namespace
802 The current user global namespace. The items in this namespace
787 should be included in the output. If None, an appropriate
803 should be included in the output. If None, an appropriate
788 blank namespace should be created.
804 blank namespace should be created.
789
805
790 Returns
806 Returns
791 -------
807 -------
792 A pair of dictionary-like object to be used as the local namespace
808 A pair of dictionary-like object to be used as the local namespace
793 of the interpreter and a dict to be used as the global namespace.
809 of the interpreter and a dict to be used as the global namespace.
794 """
810 """
795
811
796
812
797 # We must ensure that __builtin__ (without the final 's') is always
813 # We must ensure that __builtin__ (without the final 's') is always
798 # available and pointing to the __builtin__ *module*. For more details:
814 # available and pointing to the __builtin__ *module*. For more details:
799 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
815 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
800
816
801 if user_ns is None:
817 if user_ns is None:
802 # Set __name__ to __main__ to better match the behavior of the
818 # Set __name__ to __main__ to better match the behavior of the
803 # normal interpreter.
819 # normal interpreter.
804 user_ns = {'__name__' :'__main__',
820 user_ns = {'__name__' :'__main__',
805 '__builtin__' : __builtin__,
821 '__builtin__' : __builtin__,
806 '__builtins__' : __builtin__,
822 '__builtins__' : __builtin__,
807 }
823 }
808 else:
824 else:
809 user_ns.setdefault('__name__','__main__')
825 user_ns.setdefault('__name__','__main__')
810 user_ns.setdefault('__builtin__',__builtin__)
826 user_ns.setdefault('__builtin__',__builtin__)
811 user_ns.setdefault('__builtins__',__builtin__)
827 user_ns.setdefault('__builtins__',__builtin__)
812
828
813 if user_global_ns is None:
829 if user_global_ns is None:
814 user_global_ns = user_ns
830 user_global_ns = user_ns
815 if type(user_global_ns) is not dict:
831 if type(user_global_ns) is not dict:
816 raise TypeError("user_global_ns must be a true dict; got %r"
832 raise TypeError("user_global_ns must be a true dict; got %r"
817 % type(user_global_ns))
833 % type(user_global_ns))
818
834
819 return user_ns, user_global_ns
835 return user_ns, user_global_ns
820
836
821 def init_sys_modules(self):
837 def init_sys_modules(self):
822 # We need to insert into sys.modules something that looks like a
838 # We need to insert into sys.modules something that looks like a
823 # module but which accesses the IPython namespace, for shelve and
839 # module but which accesses the IPython namespace, for shelve and
824 # pickle to work interactively. Normally they rely on getting
840 # pickle to work interactively. Normally they rely on getting
825 # everything out of __main__, but for embedding purposes each IPython
841 # everything out of __main__, but for embedding purposes each IPython
826 # instance has its own private namespace, so we can't go shoving
842 # instance has its own private namespace, so we can't go shoving
827 # everything into __main__.
843 # everything into __main__.
828
844
829 # note, however, that we should only do this for non-embedded
845 # note, however, that we should only do this for non-embedded
830 # ipythons, which really mimic the __main__.__dict__ with their own
846 # ipythons, which really mimic the __main__.__dict__ with their own
831 # namespace. Embedded instances, on the other hand, should not do
847 # namespace. Embedded instances, on the other hand, should not do
832 # this because they need to manage the user local/global namespaces
848 # this because they need to manage the user local/global namespaces
833 # only, but they live within a 'normal' __main__ (meaning, they
849 # only, but they live within a 'normal' __main__ (meaning, they
834 # shouldn't overtake the execution environment of the script they're
850 # shouldn't overtake the execution environment of the script they're
835 # embedded in).
851 # embedded in).
836
852
837 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
853 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
838
854
839 try:
855 try:
840 main_name = self.user_ns['__name__']
856 main_name = self.user_ns['__name__']
841 except KeyError:
857 except KeyError:
842 raise KeyError('user_ns dictionary MUST have a "__name__" key')
858 raise KeyError('user_ns dictionary MUST have a "__name__" key')
843 else:
859 else:
844 sys.modules[main_name] = FakeModule(self.user_ns)
860 sys.modules[main_name] = FakeModule(self.user_ns)
845
861
846 def init_user_ns(self):
862 def init_user_ns(self):
847 """Initialize all user-visible namespaces to their minimum defaults.
863 """Initialize all user-visible namespaces to their minimum defaults.
848
864
849 Certain history lists are also initialized here, as they effectively
865 Certain history lists are also initialized here, as they effectively
850 act as user namespaces.
866 act as user namespaces.
851
867
852 Notes
868 Notes
853 -----
869 -----
854 All data structures here are only filled in, they are NOT reset by this
870 All data structures here are only filled in, they are NOT reset by this
855 method. If they were not empty before, data will simply be added to
871 method. If they were not empty before, data will simply be added to
856 therm.
872 therm.
857 """
873 """
858 # This function works in two parts: first we put a few things in
874 # This function works in two parts: first we put a few things in
859 # user_ns, and we sync that contents into user_ns_hidden so that these
875 # user_ns, and we sync that contents into user_ns_hidden so that these
860 # initial variables aren't shown by %who. After the sync, we add the
876 # initial variables aren't shown by %who. After the sync, we add the
861 # rest of what we *do* want the user to see with %who even on a new
877 # rest of what we *do* want the user to see with %who even on a new
862 # session (probably nothing, so theye really only see their own stuff)
878 # session (probably nothing, so theye really only see their own stuff)
863
879
864 # The user dict must *always* have a __builtin__ reference to the
880 # The user dict must *always* have a __builtin__ reference to the
865 # Python standard __builtin__ namespace, which must be imported.
881 # Python standard __builtin__ namespace, which must be imported.
866 # This is so that certain operations in prompt evaluation can be
882 # This is so that certain operations in prompt evaluation can be
867 # reliably executed with builtins. Note that we can NOT use
883 # reliably executed with builtins. Note that we can NOT use
868 # __builtins__ (note the 's'), because that can either be a dict or a
884 # __builtins__ (note the 's'), because that can either be a dict or a
869 # module, and can even mutate at runtime, depending on the context
885 # module, and can even mutate at runtime, depending on the context
870 # (Python makes no guarantees on it). In contrast, __builtin__ is
886 # (Python makes no guarantees on it). In contrast, __builtin__ is
871 # always a module object, though it must be explicitly imported.
887 # always a module object, though it must be explicitly imported.
872
888
873 # For more details:
889 # For more details:
874 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
890 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
875 ns = dict(__builtin__ = __builtin__)
891 ns = dict(__builtin__ = __builtin__)
876
892
877 # Put 'help' in the user namespace
893 # Put 'help' in the user namespace
878 try:
894 try:
879 from site import _Helper
895 from site import _Helper
880 ns['help'] = _Helper()
896 ns['help'] = _Helper()
881 except ImportError:
897 except ImportError:
882 warn('help() not available - check site.py')
898 warn('help() not available - check site.py')
883
899
884 # make global variables for user access to the histories
900 # make global variables for user access to the histories
885 ns['_ih'] = self.input_hist
901 ns['_ih'] = self.input_hist
886 ns['_oh'] = self.output_hist
902 ns['_oh'] = self.output_hist
887 ns['_dh'] = self.dir_hist
903 ns['_dh'] = self.dir_hist
888
904
889 ns['_sh'] = shadowns
905 ns['_sh'] = shadowns
890
906
891 # user aliases to input and output histories. These shouldn't show up
907 # user aliases to input and output histories. These shouldn't show up
892 # in %who, as they can have very large reprs.
908 # in %who, as they can have very large reprs.
893 ns['In'] = self.input_hist
909 ns['In'] = self.input_hist
894 ns['Out'] = self.output_hist
910 ns['Out'] = self.output_hist
895
911
896 # Store myself as the public api!!!
912 # Store myself as the public api!!!
897 ns['get_ipython'] = self.get_ipython
913 ns['get_ipython'] = self.get_ipython
898
914
899 # Sync what we've added so far to user_ns_hidden so these aren't seen
915 # Sync what we've added so far to user_ns_hidden so these aren't seen
900 # by %who
916 # by %who
901 self.user_ns_hidden.update(ns)
917 self.user_ns_hidden.update(ns)
902
918
903 # Anything put into ns now would show up in %who. Think twice before
919 # Anything put into ns now would show up in %who. Think twice before
904 # putting anything here, as we really want %who to show the user their
920 # putting anything here, as we really want %who to show the user their
905 # stuff, not our variables.
921 # stuff, not our variables.
906
922
907 # Finally, update the real user's namespace
923 # Finally, update the real user's namespace
908 self.user_ns.update(ns)
924 self.user_ns.update(ns)
909
925
910
926
911 def reset(self):
927 def reset(self):
912 """Clear all internal namespaces.
928 """Clear all internal namespaces.
913
929
914 Note that this is much more aggressive than %reset, since it clears
930 Note that this is much more aggressive than %reset, since it clears
915 fully all namespaces, as well as all input/output lists.
931 fully all namespaces, as well as all input/output lists.
916 """
932 """
917 for ns in self.ns_refs_table:
933 for ns in self.ns_refs_table:
918 ns.clear()
934 ns.clear()
919
935
920 self.alias_manager.clear_aliases()
936 self.alias_manager.clear_aliases()
921
937
922 # Clear input and output histories
938 # Clear input and output histories
923 self.input_hist[:] = []
939 self.input_hist[:] = []
924 self.input_hist_raw[:] = []
940 self.input_hist_raw[:] = []
925 self.output_hist.clear()
941 self.output_hist.clear()
926
942
927 # Restore the user namespaces to minimal usability
943 # Restore the user namespaces to minimal usability
928 self.init_user_ns()
944 self.init_user_ns()
929
945
930 # Restore the default and user aliases
946 # Restore the default and user aliases
931 self.alias_manager.init_aliases()
947 self.alias_manager.init_aliases()
932
948
933 def reset_selective(self, regex=None):
949 def reset_selective(self, regex=None):
934 """Clear selective variables from internal namespaces based on a specified regular expression.
950 """Clear selective variables from internal namespaces based on a specified regular expression.
935
951
936 Parameters
952 Parameters
937 ----------
953 ----------
938 regex : string or compiled pattern, optional
954 regex : string or compiled pattern, optional
939 A regular expression pattern that will be used in searching variable names in the users
955 A regular expression pattern that will be used in searching variable names in the users
940 namespaces.
956 namespaces.
941 """
957 """
942 if regex is not None:
958 if regex is not None:
943 try:
959 try:
944 m = re.compile(regex)
960 m = re.compile(regex)
945 except TypeError:
961 except TypeError:
946 raise TypeError('regex must be a string or compiled pattern')
962 raise TypeError('regex must be a string or compiled pattern')
947 # Search for keys in each namespace that match the given regex
963 # Search for keys in each namespace that match the given regex
948 # If a match is found, delete the key/value pair.
964 # If a match is found, delete the key/value pair.
949 for ns in self.ns_refs_table:
965 for ns in self.ns_refs_table:
950 for var in ns:
966 for var in ns:
951 if m.search(var):
967 if m.search(var):
952 del ns[var]
968 del ns[var]
953
969
954 def push(self, variables, interactive=True):
970 def push(self, variables, interactive=True):
955 """Inject a group of variables into the IPython user namespace.
971 """Inject a group of variables into the IPython user namespace.
956
972
957 Parameters
973 Parameters
958 ----------
974 ----------
959 variables : dict, str or list/tuple of str
975 variables : dict, str or list/tuple of str
960 The variables to inject into the user's namespace. If a dict,
976 The variables to inject into the user's namespace. If a dict,
961 a simple update is done. If a str, the string is assumed to
977 a simple update is done. If a str, the string is assumed to
962 have variable names separated by spaces. A list/tuple of str
978 have variable names separated by spaces. A list/tuple of str
963 can also be used to give the variable names. If just the variable
979 can also be used to give the variable names. If just the variable
964 names are give (list/tuple/str) then the variable values looked
980 names are give (list/tuple/str) then the variable values looked
965 up in the callers frame.
981 up in the callers frame.
966 interactive : bool
982 interactive : bool
967 If True (default), the variables will be listed with the ``who``
983 If True (default), the variables will be listed with the ``who``
968 magic.
984 magic.
969 """
985 """
970 vdict = None
986 vdict = None
971
987
972 # We need a dict of name/value pairs to do namespace updates.
988 # We need a dict of name/value pairs to do namespace updates.
973 if isinstance(variables, dict):
989 if isinstance(variables, dict):
974 vdict = variables
990 vdict = variables
975 elif isinstance(variables, (basestring, list, tuple)):
991 elif isinstance(variables, (basestring, list, tuple)):
976 if isinstance(variables, basestring):
992 if isinstance(variables, basestring):
977 vlist = variables.split()
993 vlist = variables.split()
978 else:
994 else:
979 vlist = variables
995 vlist = variables
980 vdict = {}
996 vdict = {}
981 cf = sys._getframe(1)
997 cf = sys._getframe(1)
982 for name in vlist:
998 for name in vlist:
983 try:
999 try:
984 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1000 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
985 except:
1001 except:
986 print ('Could not get variable %s from %s' %
1002 print ('Could not get variable %s from %s' %
987 (name,cf.f_code.co_name))
1003 (name,cf.f_code.co_name))
988 else:
1004 else:
989 raise ValueError('variables must be a dict/str/list/tuple')
1005 raise ValueError('variables must be a dict/str/list/tuple')
990
1006
991 # Propagate variables to user namespace
1007 # Propagate variables to user namespace
992 self.user_ns.update(vdict)
1008 self.user_ns.update(vdict)
993
1009
994 # And configure interactive visibility
1010 # And configure interactive visibility
995 config_ns = self.user_ns_hidden
1011 config_ns = self.user_ns_hidden
996 if interactive:
1012 if interactive:
997 for name, val in vdict.iteritems():
1013 for name, val in vdict.iteritems():
998 config_ns.pop(name, None)
1014 config_ns.pop(name, None)
999 else:
1015 else:
1000 for name,val in vdict.iteritems():
1016 for name,val in vdict.iteritems():
1001 config_ns[name] = val
1017 config_ns[name] = val
1002
1018
1003 #-------------------------------------------------------------------------
1019 #-------------------------------------------------------------------------
1004 # Things related to history management
1020 # Things related to history management
1005 #-------------------------------------------------------------------------
1021 #-------------------------------------------------------------------------
1006
1022
1007 def init_history(self):
1023 def init_history(self):
1008 # List of input with multi-line handling.
1024 # List of input with multi-line handling.
1009 self.input_hist = InputList()
1025 self.input_hist = InputList()
1010 # This one will hold the 'raw' input history, without any
1026 # This one will hold the 'raw' input history, without any
1011 # pre-processing. This will allow users to retrieve the input just as
1027 # pre-processing. This will allow users to retrieve the input just as
1012 # it was exactly typed in by the user, with %hist -r.
1028 # it was exactly typed in by the user, with %hist -r.
1013 self.input_hist_raw = InputList()
1029 self.input_hist_raw = InputList()
1014
1030
1015 # list of visited directories
1031 # list of visited directories
1016 try:
1032 try:
1017 self.dir_hist = [os.getcwd()]
1033 self.dir_hist = [os.getcwd()]
1018 except OSError:
1034 except OSError:
1019 self.dir_hist = []
1035 self.dir_hist = []
1020
1036
1021 # dict of output history
1037 # dict of output history
1022 self.output_hist = {}
1038 self.output_hist = {}
1023
1039
1024 # Now the history file
1040 # Now the history file
1025 if self.profile:
1041 if self.profile:
1026 histfname = 'history-%s' % self.profile
1042 histfname = 'history-%s' % self.profile
1027 else:
1043 else:
1028 histfname = 'history'
1044 histfname = 'history'
1029 self.histfile = os.path.join(self.ipython_dir, histfname)
1045 self.histfile = os.path.join(self.ipython_dir, histfname)
1030
1046
1031 # Fill the history zero entry, user counter starts at 1
1047 # Fill the history zero entry, user counter starts at 1
1032 self.input_hist.append('\n')
1048 self.input_hist.append('\n')
1033 self.input_hist_raw.append('\n')
1049 self.input_hist_raw.append('\n')
1034
1050
1035 def init_shadow_hist(self):
1051 def init_shadow_hist(self):
1036 try:
1052 try:
1037 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1053 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1038 except exceptions.UnicodeDecodeError:
1054 except exceptions.UnicodeDecodeError:
1039 print "Your ipython_dir can't be decoded to unicode!"
1055 print "Your ipython_dir can't be decoded to unicode!"
1040 print "Please set HOME environment variable to something that"
1056 print "Please set HOME environment variable to something that"
1041 print r"only has ASCII characters, e.g. c:\home"
1057 print r"only has ASCII characters, e.g. c:\home"
1042 print "Now it is", self.ipython_dir
1058 print "Now it is", self.ipython_dir
1043 sys.exit()
1059 sys.exit()
1044 self.shadowhist = ipcorehist.ShadowHist(self.db)
1060 self.shadowhist = ipcorehist.ShadowHist(self.db)
1045
1061
1046 def savehist(self):
1062 def savehist(self):
1047 """Save input history to a file (via readline library)."""
1063 """Save input history to a file (via readline library)."""
1048
1064
1049 try:
1065 try:
1050 self.readline.write_history_file(self.histfile)
1066 self.readline.write_history_file(self.histfile)
1051 except:
1067 except:
1052 print 'Unable to save IPython command history to file: ' + \
1068 print 'Unable to save IPython command history to file: ' + \
1053 `self.histfile`
1069 `self.histfile`
1054
1070
1055 def reloadhist(self):
1071 def reloadhist(self):
1056 """Reload the input history from disk file."""
1072 """Reload the input history from disk file."""
1057
1073
1058 try:
1074 try:
1059 self.readline.clear_history()
1075 self.readline.clear_history()
1060 self.readline.read_history_file(self.shell.histfile)
1076 self.readline.read_history_file(self.shell.histfile)
1061 except AttributeError:
1077 except AttributeError:
1062 pass
1078 pass
1063
1079
1064 def history_saving_wrapper(self, func):
1080 def history_saving_wrapper(self, func):
1065 """ Wrap func for readline history saving
1081 """ Wrap func for readline history saving
1066
1082
1067 Convert func into callable that saves & restores
1083 Convert func into callable that saves & restores
1068 history around the call """
1084 history around the call """
1069
1085
1070 if self.has_readline:
1086 if self.has_readline:
1071 from IPython.utils import rlineimpl as readline
1087 from IPython.utils import rlineimpl as readline
1072 else:
1088 else:
1073 return func
1089 return func
1074
1090
1075 def wrapper():
1091 def wrapper():
1076 self.savehist()
1092 self.savehist()
1077 try:
1093 try:
1078 func()
1094 func()
1079 finally:
1095 finally:
1080 readline.read_history_file(self.histfile)
1096 readline.read_history_file(self.histfile)
1081 return wrapper
1097 return wrapper
1082
1098
1083 #-------------------------------------------------------------------------
1099 #-------------------------------------------------------------------------
1084 # Things related to exception handling and tracebacks (not debugging)
1100 # Things related to exception handling and tracebacks (not debugging)
1085 #-------------------------------------------------------------------------
1101 #-------------------------------------------------------------------------
1086
1102
1087 def init_traceback_handlers(self, custom_exceptions):
1103 def init_traceback_handlers(self, custom_exceptions):
1088 # Syntax error handler.
1104 # Syntax error handler.
1089 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1105 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1090
1106
1091 # The interactive one is initialized with an offset, meaning we always
1107 # The interactive one is initialized with an offset, meaning we always
1092 # want to remove the topmost item in the traceback, which is our own
1108 # want to remove the topmost item in the traceback, which is our own
1093 # internal code. Valid modes: ['Plain','Context','Verbose']
1109 # internal code. Valid modes: ['Plain','Context','Verbose']
1094 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1110 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1095 color_scheme='NoColor',
1111 color_scheme='NoColor',
1096 tb_offset = 1)
1112 tb_offset = 1)
1097
1113
1098 # The instance will store a pointer to the system-wide exception hook,
1114 # The instance will store a pointer to the system-wide exception hook,
1099 # so that runtime code (such as magics) can access it. This is because
1115 # so that runtime code (such as magics) can access it. This is because
1100 # during the read-eval loop, it may get temporarily overwritten.
1116 # during the read-eval loop, it may get temporarily overwritten.
1101 self.sys_excepthook = sys.excepthook
1117 self.sys_excepthook = sys.excepthook
1102
1118
1103 # and add any custom exception handlers the user may have specified
1119 # and add any custom exception handlers the user may have specified
1104 self.set_custom_exc(*custom_exceptions)
1120 self.set_custom_exc(*custom_exceptions)
1105
1121
1106 # Set the exception mode
1122 # Set the exception mode
1107 self.InteractiveTB.set_mode(mode=self.xmode)
1123 self.InteractiveTB.set_mode(mode=self.xmode)
1108
1124
1109 def set_custom_exc(self,exc_tuple,handler):
1125 def set_custom_exc(self,exc_tuple,handler):
1110 """set_custom_exc(exc_tuple,handler)
1126 """set_custom_exc(exc_tuple,handler)
1111
1127
1112 Set a custom exception handler, which will be called if any of the
1128 Set a custom exception handler, which will be called if any of the
1113 exceptions in exc_tuple occur in the mainloop (specifically, in the
1129 exceptions in exc_tuple occur in the mainloop (specifically, in the
1114 runcode() method.
1130 runcode() method.
1115
1131
1116 Inputs:
1132 Inputs:
1117
1133
1118 - exc_tuple: a *tuple* of valid exceptions to call the defined
1134 - exc_tuple: a *tuple* of valid exceptions to call the defined
1119 handler for. It is very important that you use a tuple, and NOT A
1135 handler for. It is very important that you use a tuple, and NOT A
1120 LIST here, because of the way Python's except statement works. If
1136 LIST here, because of the way Python's except statement works. If
1121 you only want to trap a single exception, use a singleton tuple:
1137 you only want to trap a single exception, use a singleton tuple:
1122
1138
1123 exc_tuple == (MyCustomException,)
1139 exc_tuple == (MyCustomException,)
1124
1140
1125 - handler: this must be defined as a function with the following
1141 - handler: this must be defined as a function with the following
1126 basic interface: def my_handler(self,etype,value,tb).
1142 basic interface: def my_handler(self,etype,value,tb).
1127
1143
1128 This will be made into an instance method (via new.instancemethod)
1144 This will be made into an instance method (via new.instancemethod)
1129 of IPython itself, and it will be called if any of the exceptions
1145 of IPython itself, and it will be called if any of the exceptions
1130 listed in the exc_tuple are caught. If the handler is None, an
1146 listed in the exc_tuple are caught. If the handler is None, an
1131 internal basic one is used, which just prints basic info.
1147 internal basic one is used, which just prints basic info.
1132
1148
1133 WARNING: by putting in your own exception handler into IPython's main
1149 WARNING: by putting in your own exception handler into IPython's main
1134 execution loop, you run a very good chance of nasty crashes. This
1150 execution loop, you run a very good chance of nasty crashes. This
1135 facility should only be used if you really know what you are doing."""
1151 facility should only be used if you really know what you are doing."""
1136
1152
1137 assert type(exc_tuple)==type(()) , \
1153 assert type(exc_tuple)==type(()) , \
1138 "The custom exceptions must be given AS A TUPLE."
1154 "The custom exceptions must be given AS A TUPLE."
1139
1155
1140 def dummy_handler(self,etype,value,tb):
1156 def dummy_handler(self,etype,value,tb):
1141 print '*** Simple custom exception handler ***'
1157 print '*** Simple custom exception handler ***'
1142 print 'Exception type :',etype
1158 print 'Exception type :',etype
1143 print 'Exception value:',value
1159 print 'Exception value:',value
1144 print 'Traceback :',tb
1160 print 'Traceback :',tb
1145 print 'Source code :','\n'.join(self.buffer)
1161 print 'Source code :','\n'.join(self.buffer)
1146
1162
1147 if handler is None: handler = dummy_handler
1163 if handler is None: handler = dummy_handler
1148
1164
1149 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1165 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1150 self.custom_exceptions = exc_tuple
1166 self.custom_exceptions = exc_tuple
1151
1167
1152 def excepthook(self, etype, value, tb):
1168 def excepthook(self, etype, value, tb):
1153 """One more defense for GUI apps that call sys.excepthook.
1169 """One more defense for GUI apps that call sys.excepthook.
1154
1170
1155 GUI frameworks like wxPython trap exceptions and call
1171 GUI frameworks like wxPython trap exceptions and call
1156 sys.excepthook themselves. I guess this is a feature that
1172 sys.excepthook themselves. I guess this is a feature that
1157 enables them to keep running after exceptions that would
1173 enables them to keep running after exceptions that would
1158 otherwise kill their mainloop. This is a bother for IPython
1174 otherwise kill their mainloop. This is a bother for IPython
1159 which excepts to catch all of the program exceptions with a try:
1175 which excepts to catch all of the program exceptions with a try:
1160 except: statement.
1176 except: statement.
1161
1177
1162 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1178 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1163 any app directly invokes sys.excepthook, it will look to the user like
1179 any app directly invokes sys.excepthook, it will look to the user like
1164 IPython crashed. In order to work around this, we can disable the
1180 IPython crashed. In order to work around this, we can disable the
1165 CrashHandler and replace it with this excepthook instead, which prints a
1181 CrashHandler and replace it with this excepthook instead, which prints a
1166 regular traceback using our InteractiveTB. In this fashion, apps which
1182 regular traceback using our InteractiveTB. In this fashion, apps which
1167 call sys.excepthook will generate a regular-looking exception from
1183 call sys.excepthook will generate a regular-looking exception from
1168 IPython, and the CrashHandler will only be triggered by real IPython
1184 IPython, and the CrashHandler will only be triggered by real IPython
1169 crashes.
1185 crashes.
1170
1186
1171 This hook should be used sparingly, only in places which are not likely
1187 This hook should be used sparingly, only in places which are not likely
1172 to be true IPython errors.
1188 to be true IPython errors.
1173 """
1189 """
1174 self.showtraceback((etype,value,tb),tb_offset=0)
1190 self.showtraceback((etype,value,tb),tb_offset=0)
1175
1191
1176 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1192 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1177 exception_only=False):
1193 exception_only=False):
1178 """Display the exception that just occurred.
1194 """Display the exception that just occurred.
1179
1195
1180 If nothing is known about the exception, this is the method which
1196 If nothing is known about the exception, this is the method which
1181 should be used throughout the code for presenting user tracebacks,
1197 should be used throughout the code for presenting user tracebacks,
1182 rather than directly invoking the InteractiveTB object.
1198 rather than directly invoking the InteractiveTB object.
1183
1199
1184 A specific showsyntaxerror() also exists, but this method can take
1200 A specific showsyntaxerror() also exists, but this method can take
1185 care of calling it if needed, so unless you are explicitly catching a
1201 care of calling it if needed, so unless you are explicitly catching a
1186 SyntaxError exception, don't try to analyze the stack manually and
1202 SyntaxError exception, don't try to analyze the stack manually and
1187 simply call this method."""
1203 simply call this method."""
1188
1204
1189 try:
1205 try:
1190 if exc_tuple is None:
1206 if exc_tuple is None:
1191 etype, value, tb = sys.exc_info()
1207 etype, value, tb = sys.exc_info()
1192 else:
1208 else:
1193 etype, value, tb = exc_tuple
1209 etype, value, tb = exc_tuple
1194
1210
1195 if etype is None:
1211 if etype is None:
1196 if hasattr(sys, 'last_type'):
1212 if hasattr(sys, 'last_type'):
1197 etype, value, tb = sys.last_type, sys.last_value, \
1213 etype, value, tb = sys.last_type, sys.last_value, \
1198 sys.last_traceback
1214 sys.last_traceback
1199 else:
1215 else:
1200 self.write('No traceback available to show.\n')
1216 self.write('No traceback available to show.\n')
1201 return
1217 return
1202
1218
1203 if etype is SyntaxError:
1219 if etype is SyntaxError:
1204 # Though this won't be called by syntax errors in the input
1220 # Though this won't be called by syntax errors in the input
1205 # line, there may be SyntaxError cases whith imported code.
1221 # line, there may be SyntaxError cases whith imported code.
1206 self.showsyntaxerror(filename)
1222 self.showsyntaxerror(filename)
1207 elif etype is UsageError:
1223 elif etype is UsageError:
1208 print "UsageError:", value
1224 print "UsageError:", value
1209 else:
1225 else:
1210 # WARNING: these variables are somewhat deprecated and not
1226 # WARNING: these variables are somewhat deprecated and not
1211 # necessarily safe to use in a threaded environment, but tools
1227 # necessarily safe to use in a threaded environment, but tools
1212 # like pdb depend on their existence, so let's set them. If we
1228 # like pdb depend on their existence, so let's set them. If we
1213 # find problems in the field, we'll need to revisit their use.
1229 # find problems in the field, we'll need to revisit their use.
1214 sys.last_type = etype
1230 sys.last_type = etype
1215 sys.last_value = value
1231 sys.last_value = value
1216 sys.last_traceback = tb
1232 sys.last_traceback = tb
1217
1233
1218 if etype in self.custom_exceptions:
1234 if etype in self.custom_exceptions:
1219 self.CustomTB(etype,value,tb)
1235 self.CustomTB(etype,value,tb)
1220 else:
1236 else:
1221 if exception_only:
1237 if exception_only:
1222 m = ('An exception has occurred, use %tb to see the '
1238 m = ('An exception has occurred, use %tb to see the '
1223 'full traceback.')
1239 'full traceback.')
1224 print m
1240 print m
1225 self.InteractiveTB.show_exception_only(etype, value)
1241 self.InteractiveTB.show_exception_only(etype, value)
1226 else:
1242 else:
1227 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1243 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1228 if self.InteractiveTB.call_pdb:
1244 if self.InteractiveTB.call_pdb:
1229 # pdb mucks up readline, fix it back
1245 # pdb mucks up readline, fix it back
1230 self.set_completer()
1246 self.set_completer()
1231
1247
1232 except KeyboardInterrupt:
1248 except KeyboardInterrupt:
1233 self.write("\nKeyboardInterrupt\n")
1249 self.write("\nKeyboardInterrupt\n")
1234
1250
1235
1251
1236 def showsyntaxerror(self, filename=None):
1252 def showsyntaxerror(self, filename=None):
1237 """Display the syntax error that just occurred.
1253 """Display the syntax error that just occurred.
1238
1254
1239 This doesn't display a stack trace because there isn't one.
1255 This doesn't display a stack trace because there isn't one.
1240
1256
1241 If a filename is given, it is stuffed in the exception instead
1257 If a filename is given, it is stuffed in the exception instead
1242 of what was there before (because Python's parser always uses
1258 of what was there before (because Python's parser always uses
1243 "<string>" when reading from a string).
1259 "<string>" when reading from a string).
1244 """
1260 """
1245 etype, value, last_traceback = sys.exc_info()
1261 etype, value, last_traceback = sys.exc_info()
1246
1262
1247 # See note about these variables in showtraceback() above
1263 # See note about these variables in showtraceback() above
1248 sys.last_type = etype
1264 sys.last_type = etype
1249 sys.last_value = value
1265 sys.last_value = value
1250 sys.last_traceback = last_traceback
1266 sys.last_traceback = last_traceback
1251
1267
1252 if filename and etype is SyntaxError:
1268 if filename and etype is SyntaxError:
1253 # Work hard to stuff the correct filename in the exception
1269 # Work hard to stuff the correct filename in the exception
1254 try:
1270 try:
1255 msg, (dummy_filename, lineno, offset, line) = value
1271 msg, (dummy_filename, lineno, offset, line) = value
1256 except:
1272 except:
1257 # Not the format we expect; leave it alone
1273 # Not the format we expect; leave it alone
1258 pass
1274 pass
1259 else:
1275 else:
1260 # Stuff in the right filename
1276 # Stuff in the right filename
1261 try:
1277 try:
1262 # Assume SyntaxError is a class exception
1278 # Assume SyntaxError is a class exception
1263 value = SyntaxError(msg, (filename, lineno, offset, line))
1279 value = SyntaxError(msg, (filename, lineno, offset, line))
1264 except:
1280 except:
1265 # If that failed, assume SyntaxError is a string
1281 # If that failed, assume SyntaxError is a string
1266 value = msg, (filename, lineno, offset, line)
1282 value = msg, (filename, lineno, offset, line)
1267 self.SyntaxTB(etype,value,[])
1283 self.SyntaxTB(etype,value,[])
1268
1284
1269 #-------------------------------------------------------------------------
1285 #-------------------------------------------------------------------------
1270 # Things related to tab completion
1286 # Things related to tab completion
1271 #-------------------------------------------------------------------------
1287 #-------------------------------------------------------------------------
1272
1288
1273 def complete(self, text):
1289 def complete(self, text):
1274 """Return a sorted list of all possible completions on text.
1290 """Return a sorted list of all possible completions on text.
1275
1291
1276 Inputs:
1292 Inputs:
1277
1293
1278 - text: a string of text to be completed on.
1294 - text: a string of text to be completed on.
1279
1295
1280 This is a wrapper around the completion mechanism, similar to what
1296 This is a wrapper around the completion mechanism, similar to what
1281 readline does at the command line when the TAB key is hit. By
1297 readline does at the command line when the TAB key is hit. By
1282 exposing it as a method, it can be used by other non-readline
1298 exposing it as a method, it can be used by other non-readline
1283 environments (such as GUIs) for text completion.
1299 environments (such as GUIs) for text completion.
1284
1300
1285 Simple usage example:
1301 Simple usage example:
1286
1302
1287 In [7]: x = 'hello'
1303 In [7]: x = 'hello'
1288
1304
1289 In [8]: x
1305 In [8]: x
1290 Out[8]: 'hello'
1306 Out[8]: 'hello'
1291
1307
1292 In [9]: print x
1308 In [9]: print x
1293 hello
1309 hello
1294
1310
1295 In [10]: _ip.complete('x.l')
1311 In [10]: _ip.complete('x.l')
1296 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1312 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1297 """
1313 """
1298
1314
1299 # Inject names into __builtin__ so we can complete on the added names.
1315 # Inject names into __builtin__ so we can complete on the added names.
1300 with self.builtin_trap:
1316 with self.builtin_trap:
1301 complete = self.Completer.complete
1317 complete = self.Completer.complete
1302 state = 0
1318 state = 0
1303 # use a dict so we get unique keys, since ipyhton's multiple
1319 # use a dict so we get unique keys, since ipyhton's multiple
1304 # completers can return duplicates. When we make 2.4 a requirement,
1320 # completers can return duplicates. When we make 2.4 a requirement,
1305 # start using sets instead, which are faster.
1321 # start using sets instead, which are faster.
1306 comps = {}
1322 comps = {}
1307 while True:
1323 while True:
1308 newcomp = complete(text,state,line_buffer=text)
1324 newcomp = complete(text,state,line_buffer=text)
1309 if newcomp is None:
1325 if newcomp is None:
1310 break
1326 break
1311 comps[newcomp] = 1
1327 comps[newcomp] = 1
1312 state += 1
1328 state += 1
1313 outcomps = comps.keys()
1329 outcomps = comps.keys()
1314 outcomps.sort()
1330 outcomps.sort()
1315 #print "T:",text,"OC:",outcomps # dbg
1331 #print "T:",text,"OC:",outcomps # dbg
1316 #print "vars:",self.user_ns.keys()
1332 #print "vars:",self.user_ns.keys()
1317 return outcomps
1333 return outcomps
1318
1334
1319 def set_custom_completer(self,completer,pos=0):
1335 def set_custom_completer(self,completer,pos=0):
1320 """Adds a new custom completer function.
1336 """Adds a new custom completer function.
1321
1337
1322 The position argument (defaults to 0) is the index in the completers
1338 The position argument (defaults to 0) is the index in the completers
1323 list where you want the completer to be inserted."""
1339 list where you want the completer to be inserted."""
1324
1340
1325 newcomp = new.instancemethod(completer,self.Completer,
1341 newcomp = new.instancemethod(completer,self.Completer,
1326 self.Completer.__class__)
1342 self.Completer.__class__)
1327 self.Completer.matchers.insert(pos,newcomp)
1343 self.Completer.matchers.insert(pos,newcomp)
1328
1344
1329 def set_completer(self):
1345 def set_completer(self):
1330 """Reset readline's completer to be our own."""
1346 """Reset readline's completer to be our own."""
1331 self.readline.set_completer(self.Completer.complete)
1347 self.readline.set_completer(self.Completer.complete)
1332
1348
1333 def set_completer_frame(self, frame=None):
1349 def set_completer_frame(self, frame=None):
1334 """Set the frame of the completer."""
1350 """Set the frame of the completer."""
1335 if frame:
1351 if frame:
1336 self.Completer.namespace = frame.f_locals
1352 self.Completer.namespace = frame.f_locals
1337 self.Completer.global_namespace = frame.f_globals
1353 self.Completer.global_namespace = frame.f_globals
1338 else:
1354 else:
1339 self.Completer.namespace = self.user_ns
1355 self.Completer.namespace = self.user_ns
1340 self.Completer.global_namespace = self.user_global_ns
1356 self.Completer.global_namespace = self.user_global_ns
1341
1357
1342 #-------------------------------------------------------------------------
1358 #-------------------------------------------------------------------------
1343 # Things related to readline
1359 # Things related to readline
1344 #-------------------------------------------------------------------------
1360 #-------------------------------------------------------------------------
1345
1361
1346 def init_readline(self):
1362 def init_readline(self):
1347 """Command history completion/saving/reloading."""
1363 """Command history completion/saving/reloading."""
1348
1364
1349 if self.readline_use:
1365 if self.readline_use:
1350 import IPython.utils.rlineimpl as readline
1366 import IPython.utils.rlineimpl as readline
1351
1367
1352 self.rl_next_input = None
1368 self.rl_next_input = None
1353 self.rl_do_indent = False
1369 self.rl_do_indent = False
1354
1370
1355 if not self.readline_use or not readline.have_readline:
1371 if not self.readline_use or not readline.have_readline:
1356 self.has_readline = False
1372 self.has_readline = False
1357 self.readline = None
1373 self.readline = None
1358 # Set a number of methods that depend on readline to be no-op
1374 # Set a number of methods that depend on readline to be no-op
1359 self.savehist = no_op
1375 self.savehist = no_op
1360 self.reloadhist = no_op
1376 self.reloadhist = no_op
1361 self.set_completer = no_op
1377 self.set_completer = no_op
1362 self.set_custom_completer = no_op
1378 self.set_custom_completer = no_op
1363 self.set_completer_frame = no_op
1379 self.set_completer_frame = no_op
1364 warn('Readline services not available or not loaded.')
1380 warn('Readline services not available or not loaded.')
1365 else:
1381 else:
1366 self.has_readline = True
1382 self.has_readline = True
1367 self.readline = readline
1383 self.readline = readline
1368 sys.modules['readline'] = readline
1384 sys.modules['readline'] = readline
1369 import atexit
1385 import atexit
1370 from IPython.core.completer import IPCompleter
1386 from IPython.core.completer import IPCompleter
1371 self.Completer = IPCompleter(self,
1387 self.Completer = IPCompleter(self,
1372 self.user_ns,
1388 self.user_ns,
1373 self.user_global_ns,
1389 self.user_global_ns,
1374 self.readline_omit__names,
1390 self.readline_omit__names,
1375 self.alias_manager.alias_table)
1391 self.alias_manager.alias_table)
1376 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1392 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1377 self.strdispatchers['complete_command'] = sdisp
1393 self.strdispatchers['complete_command'] = sdisp
1378 self.Completer.custom_completers = sdisp
1394 self.Completer.custom_completers = sdisp
1379 # Platform-specific configuration
1395 # Platform-specific configuration
1380 if os.name == 'nt':
1396 if os.name == 'nt':
1381 self.readline_startup_hook = readline.set_pre_input_hook
1397 self.readline_startup_hook = readline.set_pre_input_hook
1382 else:
1398 else:
1383 self.readline_startup_hook = readline.set_startup_hook
1399 self.readline_startup_hook = readline.set_startup_hook
1384
1400
1385 # Load user's initrc file (readline config)
1401 # Load user's initrc file (readline config)
1386 # Or if libedit is used, load editrc.
1402 # Or if libedit is used, load editrc.
1387 inputrc_name = os.environ.get('INPUTRC')
1403 inputrc_name = os.environ.get('INPUTRC')
1388 if inputrc_name is None:
1404 if inputrc_name is None:
1389 home_dir = get_home_dir()
1405 home_dir = get_home_dir()
1390 if home_dir is not None:
1406 if home_dir is not None:
1391 inputrc_name = '.inputrc'
1407 inputrc_name = '.inputrc'
1392 if readline.uses_libedit:
1408 if readline.uses_libedit:
1393 inputrc_name = '.editrc'
1409 inputrc_name = '.editrc'
1394 inputrc_name = os.path.join(home_dir, inputrc_name)
1410 inputrc_name = os.path.join(home_dir, inputrc_name)
1395 if os.path.isfile(inputrc_name):
1411 if os.path.isfile(inputrc_name):
1396 try:
1412 try:
1397 readline.read_init_file(inputrc_name)
1413 readline.read_init_file(inputrc_name)
1398 except:
1414 except:
1399 warn('Problems reading readline initialization file <%s>'
1415 warn('Problems reading readline initialization file <%s>'
1400 % inputrc_name)
1416 % inputrc_name)
1401
1417
1402 # save this in sys so embedded copies can restore it properly
1418 # save this in sys so embedded copies can restore it properly
1403 sys.ipcompleter = self.Completer.complete
1419 sys.ipcompleter = self.Completer.complete
1404 self.set_completer()
1420 self.set_completer()
1405
1421
1406 # Configure readline according to user's prefs
1422 # Configure readline according to user's prefs
1407 # This is only done if GNU readline is being used. If libedit
1423 # This is only done if GNU readline is being used. If libedit
1408 # is being used (as on Leopard) the readline config is
1424 # is being used (as on Leopard) the readline config is
1409 # not run as the syntax for libedit is different.
1425 # not run as the syntax for libedit is different.
1410 if not readline.uses_libedit:
1426 if not readline.uses_libedit:
1411 for rlcommand in self.readline_parse_and_bind:
1427 for rlcommand in self.readline_parse_and_bind:
1412 #print "loading rl:",rlcommand # dbg
1428 #print "loading rl:",rlcommand # dbg
1413 readline.parse_and_bind(rlcommand)
1429 readline.parse_and_bind(rlcommand)
1414
1430
1415 # Remove some chars from the delimiters list. If we encounter
1431 # Remove some chars from the delimiters list. If we encounter
1416 # unicode chars, discard them.
1432 # unicode chars, discard them.
1417 delims = readline.get_completer_delims().encode("ascii", "ignore")
1433 delims = readline.get_completer_delims().encode("ascii", "ignore")
1418 delims = delims.translate(string._idmap,
1434 delims = delims.translate(string._idmap,
1419 self.readline_remove_delims)
1435 self.readline_remove_delims)
1420 readline.set_completer_delims(delims)
1436 readline.set_completer_delims(delims)
1421 # otherwise we end up with a monster history after a while:
1437 # otherwise we end up with a monster history after a while:
1422 readline.set_history_length(1000)
1438 readline.set_history_length(1000)
1423 try:
1439 try:
1424 #print '*** Reading readline history' # dbg
1440 #print '*** Reading readline history' # dbg
1425 readline.read_history_file(self.histfile)
1441 readline.read_history_file(self.histfile)
1426 except IOError:
1442 except IOError:
1427 pass # It doesn't exist yet.
1443 pass # It doesn't exist yet.
1428
1444
1429 atexit.register(self.atexit_operations)
1445 atexit.register(self.atexit_operations)
1430 del atexit
1446 del atexit
1431
1447
1432 # Configure auto-indent for all platforms
1448 # Configure auto-indent for all platforms
1433 self.set_autoindent(self.autoindent)
1449 self.set_autoindent(self.autoindent)
1434
1450
1435 def set_next_input(self, s):
1451 def set_next_input(self, s):
1436 """ Sets the 'default' input string for the next command line.
1452 """ Sets the 'default' input string for the next command line.
1437
1453
1438 Requires readline.
1454 Requires readline.
1439
1455
1440 Example:
1456 Example:
1441
1457
1442 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1458 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1443 [D:\ipython]|2> Hello Word_ # cursor is here
1459 [D:\ipython]|2> Hello Word_ # cursor is here
1444 """
1460 """
1445
1461
1446 self.rl_next_input = s
1462 self.rl_next_input = s
1447
1463
1448 # Maybe move this to the terminal subclass?
1464 # Maybe move this to the terminal subclass?
1449 def pre_readline(self):
1465 def pre_readline(self):
1450 """readline hook to be used at the start of each line.
1466 """readline hook to be used at the start of each line.
1451
1467
1452 Currently it handles auto-indent only."""
1468 Currently it handles auto-indent only."""
1453
1469
1454 if self.rl_do_indent:
1470 if self.rl_do_indent:
1455 self.readline.insert_text(self._indent_current_str())
1471 self.readline.insert_text(self._indent_current_str())
1456 if self.rl_next_input is not None:
1472 if self.rl_next_input is not None:
1457 self.readline.insert_text(self.rl_next_input)
1473 self.readline.insert_text(self.rl_next_input)
1458 self.rl_next_input = None
1474 self.rl_next_input = None
1459
1475
1460 def _indent_current_str(self):
1476 def _indent_current_str(self):
1461 """return the current level of indentation as a string"""
1477 """return the current level of indentation as a string"""
1462 return self.indent_current_nsp * ' '
1478 return self.indent_current_nsp * ' '
1463
1479
1464 #-------------------------------------------------------------------------
1480 #-------------------------------------------------------------------------
1465 # Things related to magics
1481 # Things related to magics
1466 #-------------------------------------------------------------------------
1482 #-------------------------------------------------------------------------
1467
1483
1468 def init_magics(self):
1484 def init_magics(self):
1469 # Set user colors (don't do it in the constructor above so that it
1485 # Set user colors (don't do it in the constructor above so that it
1470 # doesn't crash if colors option is invalid)
1486 # doesn't crash if colors option is invalid)
1471 self.magic_colors(self.colors)
1487 self.magic_colors(self.colors)
1472 # History was moved to a separate module
1488 # History was moved to a separate module
1473 from . import history
1489 from . import history
1474 history.init_ipython(self)
1490 history.init_ipython(self)
1475
1491
1476 def magic(self,arg_s):
1492 def magic(self,arg_s):
1477 """Call a magic function by name.
1493 """Call a magic function by name.
1478
1494
1479 Input: a string containing the name of the magic function to call and any
1495 Input: a string containing the name of the magic function to call and any
1480 additional arguments to be passed to the magic.
1496 additional arguments to be passed to the magic.
1481
1497
1482 magic('name -opt foo bar') is equivalent to typing at the ipython
1498 magic('name -opt foo bar') is equivalent to typing at the ipython
1483 prompt:
1499 prompt:
1484
1500
1485 In[1]: %name -opt foo bar
1501 In[1]: %name -opt foo bar
1486
1502
1487 To call a magic without arguments, simply use magic('name').
1503 To call a magic without arguments, simply use magic('name').
1488
1504
1489 This provides a proper Python function to call IPython's magics in any
1505 This provides a proper Python function to call IPython's magics in any
1490 valid Python code you can type at the interpreter, including loops and
1506 valid Python code you can type at the interpreter, including loops and
1491 compound statements.
1507 compound statements.
1492 """
1508 """
1493 args = arg_s.split(' ',1)
1509 args = arg_s.split(' ',1)
1494 magic_name = args[0]
1510 magic_name = args[0]
1495 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1511 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1496
1512
1497 try:
1513 try:
1498 magic_args = args[1]
1514 magic_args = args[1]
1499 except IndexError:
1515 except IndexError:
1500 magic_args = ''
1516 magic_args = ''
1501 fn = getattr(self,'magic_'+magic_name,None)
1517 fn = getattr(self,'magic_'+magic_name,None)
1502 if fn is None:
1518 if fn is None:
1503 error("Magic function `%s` not found." % magic_name)
1519 error("Magic function `%s` not found." % magic_name)
1504 else:
1520 else:
1505 magic_args = self.var_expand(magic_args,1)
1521 magic_args = self.var_expand(magic_args,1)
1506 with nested(self.builtin_trap,):
1522 with nested(self.builtin_trap,):
1507 result = fn(magic_args)
1523 result = fn(magic_args)
1508 return result
1524 return result
1509
1525
1510 def define_magic(self, magicname, func):
1526 def define_magic(self, magicname, func):
1511 """Expose own function as magic function for ipython
1527 """Expose own function as magic function for ipython
1512
1528
1513 def foo_impl(self,parameter_s=''):
1529 def foo_impl(self,parameter_s=''):
1514 'My very own magic!. (Use docstrings, IPython reads them).'
1530 'My very own magic!. (Use docstrings, IPython reads them).'
1515 print 'Magic function. Passed parameter is between < >:'
1531 print 'Magic function. Passed parameter is between < >:'
1516 print '<%s>' % parameter_s
1532 print '<%s>' % parameter_s
1517 print 'The self object is:',self
1533 print 'The self object is:',self
1518
1534
1519 self.define_magic('foo',foo_impl)
1535 self.define_magic('foo',foo_impl)
1520 """
1536 """
1521
1537
1522 import new
1538 import new
1523 im = new.instancemethod(func,self, self.__class__)
1539 im = new.instancemethod(func,self, self.__class__)
1524 old = getattr(self, "magic_" + magicname, None)
1540 old = getattr(self, "magic_" + magicname, None)
1525 setattr(self, "magic_" + magicname, im)
1541 setattr(self, "magic_" + magicname, im)
1526 return old
1542 return old
1527
1543
1528 #-------------------------------------------------------------------------
1544 #-------------------------------------------------------------------------
1529 # Things related to macros
1545 # Things related to macros
1530 #-------------------------------------------------------------------------
1546 #-------------------------------------------------------------------------
1531
1547
1532 def define_macro(self, name, themacro):
1548 def define_macro(self, name, themacro):
1533 """Define a new macro
1549 """Define a new macro
1534
1550
1535 Parameters
1551 Parameters
1536 ----------
1552 ----------
1537 name : str
1553 name : str
1538 The name of the macro.
1554 The name of the macro.
1539 themacro : str or Macro
1555 themacro : str or Macro
1540 The action to do upon invoking the macro. If a string, a new
1556 The action to do upon invoking the macro. If a string, a new
1541 Macro object is created by passing the string to it.
1557 Macro object is created by passing the string to it.
1542 """
1558 """
1543
1559
1544 from IPython.core import macro
1560 from IPython.core import macro
1545
1561
1546 if isinstance(themacro, basestring):
1562 if isinstance(themacro, basestring):
1547 themacro = macro.Macro(themacro)
1563 themacro = macro.Macro(themacro)
1548 if not isinstance(themacro, macro.Macro):
1564 if not isinstance(themacro, macro.Macro):
1549 raise ValueError('A macro must be a string or a Macro instance.')
1565 raise ValueError('A macro must be a string or a Macro instance.')
1550 self.user_ns[name] = themacro
1566 self.user_ns[name] = themacro
1551
1567
1552 #-------------------------------------------------------------------------
1568 #-------------------------------------------------------------------------
1553 # Things related to the running of system commands
1569 # Things related to the running of system commands
1554 #-------------------------------------------------------------------------
1570 #-------------------------------------------------------------------------
1555
1571
1556 def system(self, cmd):
1572 def system(self, cmd):
1557 """Make a system call, using IPython."""
1573 """Make a system call, using IPython."""
1558 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1574 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1559
1575
1560 #-------------------------------------------------------------------------
1576 #-------------------------------------------------------------------------
1561 # Things related to aliases
1577 # Things related to aliases
1562 #-------------------------------------------------------------------------
1578 #-------------------------------------------------------------------------
1563
1579
1564 def init_alias(self):
1580 def init_alias(self):
1565 self.alias_manager = AliasManager(shell=self, config=self.config)
1581 self.alias_manager = AliasManager(shell=self, config=self.config)
1566 self.ns_table['alias'] = self.alias_manager.alias_table,
1582 self.ns_table['alias'] = self.alias_manager.alias_table,
1567
1583
1568 #-------------------------------------------------------------------------
1584 #-------------------------------------------------------------------------
1569 # Things related to extensions and plugins
1585 # Things related to extensions and plugins
1570 #-------------------------------------------------------------------------
1586 #-------------------------------------------------------------------------
1571
1587
1572 def init_extension_manager(self):
1588 def init_extension_manager(self):
1573 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1589 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1574
1590
1575 def init_plugin_manager(self):
1591 def init_plugin_manager(self):
1576 self.plugin_manager = PluginManager(config=self.config)
1592 self.plugin_manager = PluginManager(config=self.config)
1577
1593
1578 #-------------------------------------------------------------------------
1594 #-------------------------------------------------------------------------
1579 # Things related to the prefilter
1595 # Things related to the prefilter
1580 #-------------------------------------------------------------------------
1596 #-------------------------------------------------------------------------
1581
1597
1582 def init_prefilter(self):
1598 def init_prefilter(self):
1583 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1599 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1584 # Ultimately this will be refactored in the new interpreter code, but
1600 # Ultimately this will be refactored in the new interpreter code, but
1585 # for now, we should expose the main prefilter method (there's legacy
1601 # for now, we should expose the main prefilter method (there's legacy
1586 # code out there that may rely on this).
1602 # code out there that may rely on this).
1587 self.prefilter = self.prefilter_manager.prefilter_lines
1603 self.prefilter = self.prefilter_manager.prefilter_lines
1588
1604
1589 #-------------------------------------------------------------------------
1605 #-------------------------------------------------------------------------
1590 # Things related to the running of code
1606 # Things related to the running of code
1591 #-------------------------------------------------------------------------
1607 #-------------------------------------------------------------------------
1592
1608
1593 def ex(self, cmd):
1609 def ex(self, cmd):
1594 """Execute a normal python statement in user namespace."""
1610 """Execute a normal python statement in user namespace."""
1595 with nested(self.builtin_trap,):
1611 with nested(self.builtin_trap,):
1596 exec cmd in self.user_global_ns, self.user_ns
1612 exec cmd in self.user_global_ns, self.user_ns
1597
1613
1598 def ev(self, expr):
1614 def ev(self, expr):
1599 """Evaluate python expression expr in user namespace.
1615 """Evaluate python expression expr in user namespace.
1600
1616
1601 Returns the result of evaluation
1617 Returns the result of evaluation
1602 """
1618 """
1603 with nested(self.builtin_trap,):
1619 with nested(self.builtin_trap,):
1604 return eval(expr, self.user_global_ns, self.user_ns)
1620 return eval(expr, self.user_global_ns, self.user_ns)
1605
1621
1606 def safe_execfile(self, fname, *where, **kw):
1622 def safe_execfile(self, fname, *where, **kw):
1607 """A safe version of the builtin execfile().
1623 """A safe version of the builtin execfile().
1608
1624
1609 This version will never throw an exception, but instead print
1625 This version will never throw an exception, but instead print
1610 helpful error messages to the screen. This only works on pure
1626 helpful error messages to the screen. This only works on pure
1611 Python files with the .py extension.
1627 Python files with the .py extension.
1612
1628
1613 Parameters
1629 Parameters
1614 ----------
1630 ----------
1615 fname : string
1631 fname : string
1616 The name of the file to be executed.
1632 The name of the file to be executed.
1617 where : tuple
1633 where : tuple
1618 One or two namespaces, passed to execfile() as (globals,locals).
1634 One or two namespaces, passed to execfile() as (globals,locals).
1619 If only one is given, it is passed as both.
1635 If only one is given, it is passed as both.
1620 exit_ignore : bool (False)
1636 exit_ignore : bool (False)
1621 If True, then silence SystemExit for non-zero status (it is always
1637 If True, then silence SystemExit for non-zero status (it is always
1622 silenced for zero status, as it is so common).
1638 silenced for zero status, as it is so common).
1623 """
1639 """
1624 kw.setdefault('exit_ignore', False)
1640 kw.setdefault('exit_ignore', False)
1625
1641
1626 fname = os.path.abspath(os.path.expanduser(fname))
1642 fname = os.path.abspath(os.path.expanduser(fname))
1627
1643
1628 # Make sure we have a .py file
1644 # Make sure we have a .py file
1629 if not fname.endswith('.py'):
1645 if not fname.endswith('.py'):
1630 warn('File must end with .py to be run using execfile: <%s>' % fname)
1646 warn('File must end with .py to be run using execfile: <%s>' % fname)
1631
1647
1632 # Make sure we can open the file
1648 # Make sure we can open the file
1633 try:
1649 try:
1634 with open(fname) as thefile:
1650 with open(fname) as thefile:
1635 pass
1651 pass
1636 except:
1652 except:
1637 warn('Could not open file <%s> for safe execution.' % fname)
1653 warn('Could not open file <%s> for safe execution.' % fname)
1638 return
1654 return
1639
1655
1640 # Find things also in current directory. This is needed to mimic the
1656 # Find things also in current directory. This is needed to mimic the
1641 # behavior of running a script from the system command line, where
1657 # behavior of running a script from the system command line, where
1642 # Python inserts the script's directory into sys.path
1658 # Python inserts the script's directory into sys.path
1643 dname = os.path.dirname(fname)
1659 dname = os.path.dirname(fname)
1644
1660
1645 with prepended_to_syspath(dname):
1661 with prepended_to_syspath(dname):
1646 try:
1662 try:
1647 execfile(fname,*where)
1663 execfile(fname,*where)
1648 except SystemExit, status:
1664 except SystemExit, status:
1649 # If the call was made with 0 or None exit status (sys.exit(0)
1665 # If the call was made with 0 or None exit status (sys.exit(0)
1650 # or sys.exit() ), don't bother showing a traceback, as both of
1666 # or sys.exit() ), don't bother showing a traceback, as both of
1651 # these are considered normal by the OS:
1667 # these are considered normal by the OS:
1652 # > python -c'import sys;sys.exit(0)'; echo $?
1668 # > python -c'import sys;sys.exit(0)'; echo $?
1653 # 0
1669 # 0
1654 # > python -c'import sys;sys.exit()'; echo $?
1670 # > python -c'import sys;sys.exit()'; echo $?
1655 # 0
1671 # 0
1656 # For other exit status, we show the exception unless
1672 # For other exit status, we show the exception unless
1657 # explicitly silenced, but only in short form.
1673 # explicitly silenced, but only in short form.
1658 if status.code not in (0, None) and not kw['exit_ignore']:
1674 if status.code not in (0, None) and not kw['exit_ignore']:
1659 self.showtraceback(exception_only=True)
1675 self.showtraceback(exception_only=True)
1660 except:
1676 except:
1661 self.showtraceback()
1677 self.showtraceback()
1662
1678
1663 def safe_execfile_ipy(self, fname):
1679 def safe_execfile_ipy(self, fname):
1664 """Like safe_execfile, but for .ipy files with IPython syntax.
1680 """Like safe_execfile, but for .ipy files with IPython syntax.
1665
1681
1666 Parameters
1682 Parameters
1667 ----------
1683 ----------
1668 fname : str
1684 fname : str
1669 The name of the file to execute. The filename must have a
1685 The name of the file to execute. The filename must have a
1670 .ipy extension.
1686 .ipy extension.
1671 """
1687 """
1672 fname = os.path.abspath(os.path.expanduser(fname))
1688 fname = os.path.abspath(os.path.expanduser(fname))
1673
1689
1674 # Make sure we have a .py file
1690 # Make sure we have a .py file
1675 if not fname.endswith('.ipy'):
1691 if not fname.endswith('.ipy'):
1676 warn('File must end with .py to be run using execfile: <%s>' % fname)
1692 warn('File must end with .py to be run using execfile: <%s>' % fname)
1677
1693
1678 # Make sure we can open the file
1694 # Make sure we can open the file
1679 try:
1695 try:
1680 with open(fname) as thefile:
1696 with open(fname) as thefile:
1681 pass
1697 pass
1682 except:
1698 except:
1683 warn('Could not open file <%s> for safe execution.' % fname)
1699 warn('Could not open file <%s> for safe execution.' % fname)
1684 return
1700 return
1685
1701
1686 # Find things also in current directory. This is needed to mimic the
1702 # Find things also in current directory. This is needed to mimic the
1687 # behavior of running a script from the system command line, where
1703 # behavior of running a script from the system command line, where
1688 # Python inserts the script's directory into sys.path
1704 # Python inserts the script's directory into sys.path
1689 dname = os.path.dirname(fname)
1705 dname = os.path.dirname(fname)
1690
1706
1691 with prepended_to_syspath(dname):
1707 with prepended_to_syspath(dname):
1692 try:
1708 try:
1693 with open(fname) as thefile:
1709 with open(fname) as thefile:
1694 script = thefile.read()
1710 script = thefile.read()
1695 # self.runlines currently captures all exceptions
1711 # self.runlines currently captures all exceptions
1696 # raise in user code. It would be nice if there were
1712 # raise in user code. It would be nice if there were
1697 # versions of runlines, execfile that did raise, so
1713 # versions of runlines, execfile that did raise, so
1698 # we could catch the errors.
1714 # we could catch the errors.
1699 self.runlines(script, clean=True)
1715 self.runlines(script, clean=True)
1700 except:
1716 except:
1701 self.showtraceback()
1717 self.showtraceback()
1702 warn('Unknown failure executing file: <%s>' % fname)
1718 warn('Unknown failure executing file: <%s>' % fname)
1703
1719
1704 def runlines(self, lines, clean=False):
1720 def runlines(self, lines, clean=False):
1705 """Run a string of one or more lines of source.
1721 """Run a string of one or more lines of source.
1706
1722
1707 This method is capable of running a string containing multiple source
1723 This method is capable of running a string containing multiple source
1708 lines, as if they had been entered at the IPython prompt. Since it
1724 lines, as if they had been entered at the IPython prompt. Since it
1709 exposes IPython's processing machinery, the given strings can contain
1725 exposes IPython's processing machinery, the given strings can contain
1710 magic calls (%magic), special shell access (!cmd), etc.
1726 magic calls (%magic), special shell access (!cmd), etc.
1711 """
1727 """
1712
1728
1713 if isinstance(lines, (list, tuple)):
1729 if isinstance(lines, (list, tuple)):
1714 lines = '\n'.join(lines)
1730 lines = '\n'.join(lines)
1715
1731
1716 if clean:
1732 if clean:
1717 lines = self._cleanup_ipy_script(lines)
1733 lines = self._cleanup_ipy_script(lines)
1718
1734
1719 # We must start with a clean buffer, in case this is run from an
1735 # We must start with a clean buffer, in case this is run from an
1720 # interactive IPython session (via a magic, for example).
1736 # interactive IPython session (via a magic, for example).
1721 self.resetbuffer()
1737 self.resetbuffer()
1722 lines = lines.splitlines()
1738 lines = lines.splitlines()
1723 more = 0
1739 more = 0
1724
1740
1725 with nested(self.builtin_trap, self.display_trap):
1741 with nested(self.builtin_trap, self.display_trap):
1726 for line in lines:
1742 for line in lines:
1727 # skip blank lines so we don't mess up the prompt counter, but do
1743 # skip blank lines so we don't mess up the prompt counter, but do
1728 # NOT skip even a blank line if we are in a code block (more is
1744 # NOT skip even a blank line if we are in a code block (more is
1729 # true)
1745 # true)
1730
1746
1731 if line or more:
1747 if line or more:
1732 # push to raw history, so hist line numbers stay in sync
1748 # push to raw history, so hist line numbers stay in sync
1733 self.input_hist_raw.append("# " + line + "\n")
1749 self.input_hist_raw.append("# " + line + "\n")
1734 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
1750 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
1735 more = self.push_line(prefiltered)
1751 more = self.push_line(prefiltered)
1736 # IPython's runsource returns None if there was an error
1752 # IPython's runsource returns None if there was an error
1737 # compiling the code. This allows us to stop processing right
1753 # compiling the code. This allows us to stop processing right
1738 # away, so the user gets the error message at the right place.
1754 # away, so the user gets the error message at the right place.
1739 if more is None:
1755 if more is None:
1740 break
1756 break
1741 else:
1757 else:
1742 self.input_hist_raw.append("\n")
1758 self.input_hist_raw.append("\n")
1743 # final newline in case the input didn't have it, so that the code
1759 # final newline in case the input didn't have it, so that the code
1744 # actually does get executed
1760 # actually does get executed
1745 if more:
1761 if more:
1746 self.push_line('\n')
1762 self.push_line('\n')
1747
1763
1748 def runsource(self, source, filename='<input>', symbol='single'):
1764 def runsource(self, source, filename='<input>', symbol='single'):
1749 """Compile and run some source in the interpreter.
1765 """Compile and run some source in the interpreter.
1750
1766
1751 Arguments are as for compile_command().
1767 Arguments are as for compile_command().
1752
1768
1753 One several things can happen:
1769 One several things can happen:
1754
1770
1755 1) The input is incorrect; compile_command() raised an
1771 1) The input is incorrect; compile_command() raised an
1756 exception (SyntaxError or OverflowError). A syntax traceback
1772 exception (SyntaxError or OverflowError). A syntax traceback
1757 will be printed by calling the showsyntaxerror() method.
1773 will be printed by calling the showsyntaxerror() method.
1758
1774
1759 2) The input is incomplete, and more input is required;
1775 2) The input is incomplete, and more input is required;
1760 compile_command() returned None. Nothing happens.
1776 compile_command() returned None. Nothing happens.
1761
1777
1762 3) The input is complete; compile_command() returned a code
1778 3) The input is complete; compile_command() returned a code
1763 object. The code is executed by calling self.runcode() (which
1779 object. The code is executed by calling self.runcode() (which
1764 also handles run-time exceptions, except for SystemExit).
1780 also handles run-time exceptions, except for SystemExit).
1765
1781
1766 The return value is:
1782 The return value is:
1767
1783
1768 - True in case 2
1784 - True in case 2
1769
1785
1770 - False in the other cases, unless an exception is raised, where
1786 - False in the other cases, unless an exception is raised, where
1771 None is returned instead. This can be used by external callers to
1787 None is returned instead. This can be used by external callers to
1772 know whether to continue feeding input or not.
1788 know whether to continue feeding input or not.
1773
1789
1774 The return value can be used to decide whether to use sys.ps1 or
1790 The return value can be used to decide whether to use sys.ps1 or
1775 sys.ps2 to prompt the next line."""
1791 sys.ps2 to prompt the next line."""
1776
1792
1777 # if the source code has leading blanks, add 'if 1:\n' to it
1793 # if the source code has leading blanks, add 'if 1:\n' to it
1778 # this allows execution of indented pasted code. It is tempting
1794 # this allows execution of indented pasted code. It is tempting
1779 # to add '\n' at the end of source to run commands like ' a=1'
1795 # to add '\n' at the end of source to run commands like ' a=1'
1780 # directly, but this fails for more complicated scenarios
1796 # directly, but this fails for more complicated scenarios
1781 source=source.encode(self.stdin_encoding)
1797 source=source.encode(self.stdin_encoding)
1782 if source[:1] in [' ', '\t']:
1798 if source[:1] in [' ', '\t']:
1783 source = 'if 1:\n%s' % source
1799 source = 'if 1:\n%s' % source
1784
1800
1785 try:
1801 try:
1786 code = self.compile(source,filename,symbol)
1802 code = self.compile(source,filename,symbol)
1787 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
1803 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
1788 # Case 1
1804 # Case 1
1789 self.showsyntaxerror(filename)
1805 self.showsyntaxerror(filename)
1790 return None
1806 return None
1791
1807
1792 if code is None:
1808 if code is None:
1793 # Case 2
1809 # Case 2
1794 return True
1810 return True
1795
1811
1796 # Case 3
1812 # Case 3
1797 # We store the code object so that threaded shells and
1813 # We store the code object so that threaded shells and
1798 # custom exception handlers can access all this info if needed.
1814 # custom exception handlers can access all this info if needed.
1799 # The source corresponding to this can be obtained from the
1815 # The source corresponding to this can be obtained from the
1800 # buffer attribute as '\n'.join(self.buffer).
1816 # buffer attribute as '\n'.join(self.buffer).
1801 self.code_to_run = code
1817 self.code_to_run = code
1802 # now actually execute the code object
1818 # now actually execute the code object
1803 if self.runcode(code) == 0:
1819 if self.runcode(code) == 0:
1804 return False
1820 return False
1805 else:
1821 else:
1806 return None
1822 return None
1807
1823
1808 def runcode(self,code_obj):
1824 def runcode(self,code_obj):
1809 """Execute a code object.
1825 """Execute a code object.
1810
1826
1811 When an exception occurs, self.showtraceback() is called to display a
1827 When an exception occurs, self.showtraceback() is called to display a
1812 traceback.
1828 traceback.
1813
1829
1814 Return value: a flag indicating whether the code to be run completed
1830 Return value: a flag indicating whether the code to be run completed
1815 successfully:
1831 successfully:
1816
1832
1817 - 0: successful execution.
1833 - 0: successful execution.
1818 - 1: an error occurred.
1834 - 1: an error occurred.
1819 """
1835 """
1820
1836
1821 # Set our own excepthook in case the user code tries to call it
1837 # Set our own excepthook in case the user code tries to call it
1822 # directly, so that the IPython crash handler doesn't get triggered
1838 # directly, so that the IPython crash handler doesn't get triggered
1823 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1839 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1824
1840
1825 # we save the original sys.excepthook in the instance, in case config
1841 # we save the original sys.excepthook in the instance, in case config
1826 # code (such as magics) needs access to it.
1842 # code (such as magics) needs access to it.
1827 self.sys_excepthook = old_excepthook
1843 self.sys_excepthook = old_excepthook
1828 outflag = 1 # happens in more places, so it's easier as default
1844 outflag = 1 # happens in more places, so it's easier as default
1829 try:
1845 try:
1830 try:
1846 try:
1831 self.hooks.pre_runcode_hook()
1847 self.hooks.pre_runcode_hook()
1832 exec code_obj in self.user_global_ns, self.user_ns
1848 exec code_obj in self.user_global_ns, self.user_ns
1833 finally:
1849 finally:
1834 # Reset our crash handler in place
1850 # Reset our crash handler in place
1835 sys.excepthook = old_excepthook
1851 sys.excepthook = old_excepthook
1836 except SystemExit:
1852 except SystemExit:
1837 self.resetbuffer()
1853 self.resetbuffer()
1838 self.showtraceback(exception_only=True)
1854 self.showtraceback(exception_only=True)
1839 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
1855 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
1840 except self.custom_exceptions:
1856 except self.custom_exceptions:
1841 etype,value,tb = sys.exc_info()
1857 etype,value,tb = sys.exc_info()
1842 self.CustomTB(etype,value,tb)
1858 self.CustomTB(etype,value,tb)
1843 except:
1859 except:
1844 self.showtraceback()
1860 self.showtraceback()
1845 else:
1861 else:
1846 outflag = 0
1862 outflag = 0
1847 if softspace(sys.stdout, 0):
1863 if softspace(sys.stdout, 0):
1848 print
1864 print
1849 # Flush out code object which has been run (and source)
1865 # Flush out code object which has been run (and source)
1850 self.code_to_run = None
1866 self.code_to_run = None
1851 return outflag
1867 return outflag
1852
1868
1853 def push_line(self, line):
1869 def push_line(self, line):
1854 """Push a line to the interpreter.
1870 """Push a line to the interpreter.
1855
1871
1856 The line should not have a trailing newline; it may have
1872 The line should not have a trailing newline; it may have
1857 internal newlines. The line is appended to a buffer and the
1873 internal newlines. The line is appended to a buffer and the
1858 interpreter's runsource() method is called with the
1874 interpreter's runsource() method is called with the
1859 concatenated contents of the buffer as source. If this
1875 concatenated contents of the buffer as source. If this
1860 indicates that the command was executed or invalid, the buffer
1876 indicates that the command was executed or invalid, the buffer
1861 is reset; otherwise, the command is incomplete, and the buffer
1877 is reset; otherwise, the command is incomplete, and the buffer
1862 is left as it was after the line was appended. The return
1878 is left as it was after the line was appended. The return
1863 value is 1 if more input is required, 0 if the line was dealt
1879 value is 1 if more input is required, 0 if the line was dealt
1864 with in some way (this is the same as runsource()).
1880 with in some way (this is the same as runsource()).
1865 """
1881 """
1866
1882
1867 # autoindent management should be done here, and not in the
1883 # autoindent management should be done here, and not in the
1868 # interactive loop, since that one is only seen by keyboard input. We
1884 # interactive loop, since that one is only seen by keyboard input. We
1869 # need this done correctly even for code run via runlines (which uses
1885 # need this done correctly even for code run via runlines (which uses
1870 # push).
1886 # push).
1871
1887
1872 #print 'push line: <%s>' % line # dbg
1888 #print 'push line: <%s>' % line # dbg
1873 for subline in line.splitlines():
1889 for subline in line.splitlines():
1874 self._autoindent_update(subline)
1890 self._autoindent_update(subline)
1875 self.buffer.append(line)
1891 self.buffer.append(line)
1876 more = self.runsource('\n'.join(self.buffer), self.filename)
1892 more = self.runsource('\n'.join(self.buffer), self.filename)
1877 if not more:
1893 if not more:
1878 self.resetbuffer()
1894 self.resetbuffer()
1879 return more
1895 return more
1880
1896
1881 def resetbuffer(self):
1897 def resetbuffer(self):
1882 """Reset the input buffer."""
1898 """Reset the input buffer."""
1883 self.buffer[:] = []
1899 self.buffer[:] = []
1884
1900
1885 def _is_secondary_block_start(self, s):
1901 def _is_secondary_block_start(self, s):
1886 if not s.endswith(':'):
1902 if not s.endswith(':'):
1887 return False
1903 return False
1888 if (s.startswith('elif') or
1904 if (s.startswith('elif') or
1889 s.startswith('else') or
1905 s.startswith('else') or
1890 s.startswith('except') or
1906 s.startswith('except') or
1891 s.startswith('finally')):
1907 s.startswith('finally')):
1892 return True
1908 return True
1893
1909
1894 def _cleanup_ipy_script(self, script):
1910 def _cleanup_ipy_script(self, script):
1895 """Make a script safe for self.runlines()
1911 """Make a script safe for self.runlines()
1896
1912
1897 Currently, IPython is lines based, with blocks being detected by
1913 Currently, IPython is lines based, with blocks being detected by
1898 empty lines. This is a problem for block based scripts that may
1914 empty lines. This is a problem for block based scripts that may
1899 not have empty lines after blocks. This script adds those empty
1915 not have empty lines after blocks. This script adds those empty
1900 lines to make scripts safe for running in the current line based
1916 lines to make scripts safe for running in the current line based
1901 IPython.
1917 IPython.
1902 """
1918 """
1903 res = []
1919 res = []
1904 lines = script.splitlines()
1920 lines = script.splitlines()
1905 level = 0
1921 level = 0
1906
1922
1907 for l in lines:
1923 for l in lines:
1908 lstripped = l.lstrip()
1924 lstripped = l.lstrip()
1909 stripped = l.strip()
1925 stripped = l.strip()
1910 if not stripped:
1926 if not stripped:
1911 continue
1927 continue
1912 newlevel = len(l) - len(lstripped)
1928 newlevel = len(l) - len(lstripped)
1913 if level > 0 and newlevel == 0 and \
1929 if level > 0 and newlevel == 0 and \
1914 not self._is_secondary_block_start(stripped):
1930 not self._is_secondary_block_start(stripped):
1915 # add empty line
1931 # add empty line
1916 res.append('')
1932 res.append('')
1917 res.append(l)
1933 res.append(l)
1918 level = newlevel
1934 level = newlevel
1919
1935
1920 return '\n'.join(res) + '\n'
1936 return '\n'.join(res) + '\n'
1921
1937
1922 def _autoindent_update(self,line):
1938 def _autoindent_update(self,line):
1923 """Keep track of the indent level."""
1939 """Keep track of the indent level."""
1924
1940
1925 #debugx('line')
1941 #debugx('line')
1926 #debugx('self.indent_current_nsp')
1942 #debugx('self.indent_current_nsp')
1927 if self.autoindent:
1943 if self.autoindent:
1928 if line:
1944 if line:
1929 inisp = num_ini_spaces(line)
1945 inisp = num_ini_spaces(line)
1930 if inisp < self.indent_current_nsp:
1946 if inisp < self.indent_current_nsp:
1931 self.indent_current_nsp = inisp
1947 self.indent_current_nsp = inisp
1932
1948
1933 if line[-1] == ':':
1949 if line[-1] == ':':
1934 self.indent_current_nsp += 4
1950 self.indent_current_nsp += 4
1935 elif dedent_re.match(line):
1951 elif dedent_re.match(line):
1936 self.indent_current_nsp -= 4
1952 self.indent_current_nsp -= 4
1937 else:
1953 else:
1938 self.indent_current_nsp = 0
1954 self.indent_current_nsp = 0
1939
1955
1940 #-------------------------------------------------------------------------
1956 #-------------------------------------------------------------------------
1941 # Things related to GUI support and pylab
1957 # Things related to GUI support and pylab
1942 #-------------------------------------------------------------------------
1958 #-------------------------------------------------------------------------
1943
1959
1944 def enable_pylab(self, gui=None):
1960 def enable_pylab(self, gui=None):
1945 raise NotImplementedError('Implement enable_pylab in a subclass')
1961 raise NotImplementedError('Implement enable_pylab in a subclass')
1946
1962
1947 #-------------------------------------------------------------------------
1963 #-------------------------------------------------------------------------
1948 # Utilities
1964 # Utilities
1949 #-------------------------------------------------------------------------
1965 #-------------------------------------------------------------------------
1950
1966
1951 def getoutput(self, cmd):
1967 def getoutput(self, cmd):
1952 return getoutput(self.var_expand(cmd,depth=2),
1968 return getoutput(self.var_expand(cmd,depth=2),
1953 header=self.system_header,
1969 header=self.system_header,
1954 verbose=self.system_verbose)
1970 verbose=self.system_verbose)
1955
1971
1956 def getoutputerror(self, cmd):
1972 def getoutputerror(self, cmd):
1957 return getoutputerror(self.var_expand(cmd,depth=2),
1973 return getoutputerror(self.var_expand(cmd,depth=2),
1958 header=self.system_header,
1974 header=self.system_header,
1959 verbose=self.system_verbose)
1975 verbose=self.system_verbose)
1960
1976
1961 def var_expand(self,cmd,depth=0):
1977 def var_expand(self,cmd,depth=0):
1962 """Expand python variables in a string.
1978 """Expand python variables in a string.
1963
1979
1964 The depth argument indicates how many frames above the caller should
1980 The depth argument indicates how many frames above the caller should
1965 be walked to look for the local namespace where to expand variables.
1981 be walked to look for the local namespace where to expand variables.
1966
1982
1967 The global namespace for expansion is always the user's interactive
1983 The global namespace for expansion is always the user's interactive
1968 namespace.
1984 namespace.
1969 """
1985 """
1970
1986
1971 return str(ItplNS(cmd,
1987 return str(ItplNS(cmd,
1972 self.user_ns, # globals
1988 self.user_ns, # globals
1973 # Skip our own frame in searching for locals:
1989 # Skip our own frame in searching for locals:
1974 sys._getframe(depth+1).f_locals # locals
1990 sys._getframe(depth+1).f_locals # locals
1975 ))
1991 ))
1976
1992
1977 def mktempfile(self,data=None):
1993 def mktempfile(self,data=None):
1978 """Make a new tempfile and return its filename.
1994 """Make a new tempfile and return its filename.
1979
1995
1980 This makes a call to tempfile.mktemp, but it registers the created
1996 This makes a call to tempfile.mktemp, but it registers the created
1981 filename internally so ipython cleans it up at exit time.
1997 filename internally so ipython cleans it up at exit time.
1982
1998
1983 Optional inputs:
1999 Optional inputs:
1984
2000
1985 - data(None): if data is given, it gets written out to the temp file
2001 - data(None): if data is given, it gets written out to the temp file
1986 immediately, and the file is closed again."""
2002 immediately, and the file is closed again."""
1987
2003
1988 filename = tempfile.mktemp('.py','ipython_edit_')
2004 filename = tempfile.mktemp('.py','ipython_edit_')
1989 self.tempfiles.append(filename)
2005 self.tempfiles.append(filename)
1990
2006
1991 if data:
2007 if data:
1992 tmp_file = open(filename,'w')
2008 tmp_file = open(filename,'w')
1993 tmp_file.write(data)
2009 tmp_file.write(data)
1994 tmp_file.close()
2010 tmp_file.close()
1995 return filename
2011 return filename
1996
2012
1997 # TODO: This should be removed when Term is refactored.
2013 # TODO: This should be removed when Term is refactored.
1998 def write(self,data):
2014 def write(self,data):
1999 """Write a string to the default output"""
2015 """Write a string to the default output"""
2000 Term.cout.write(data)
2016 IPython.utils.io.Term.cout.write(data)
2001
2017
2002 # TODO: This should be removed when Term is refactored.
2018 # TODO: This should be removed when Term is refactored.
2003 def write_err(self,data):
2019 def write_err(self,data):
2004 """Write a string to the default error output"""
2020 """Write a string to the default error output"""
2005 Term.cerr.write(data)
2021 IPython.utils.io.Term.cerr.write(data)
2006
2022
2007 def ask_yes_no(self,prompt,default=True):
2023 def ask_yes_no(self,prompt,default=True):
2008 if self.quiet:
2024 if self.quiet:
2009 return True
2025 return True
2010 return ask_yes_no(prompt,default)
2026 return ask_yes_no(prompt,default)
2011
2027
2012 #-------------------------------------------------------------------------
2028 #-------------------------------------------------------------------------
2013 # Things related to IPython exiting
2029 # Things related to IPython exiting
2014 #-------------------------------------------------------------------------
2030 #-------------------------------------------------------------------------
2015
2031
2016 def atexit_operations(self):
2032 def atexit_operations(self):
2017 """This will be executed at the time of exit.
2033 """This will be executed at the time of exit.
2018
2034
2019 Saving of persistent data should be performed here.
2035 Saving of persistent data should be performed here.
2020 """
2036 """
2021 self.savehist()
2037 self.savehist()
2022
2038
2023 # Cleanup all tempfiles left around
2039 # Cleanup all tempfiles left around
2024 for tfile in self.tempfiles:
2040 for tfile in self.tempfiles:
2025 try:
2041 try:
2026 os.unlink(tfile)
2042 os.unlink(tfile)
2027 except OSError:
2043 except OSError:
2028 pass
2044 pass
2029
2045
2030 # Clear all user namespaces to release all references cleanly.
2046 # Clear all user namespaces to release all references cleanly.
2031 self.reset()
2047 self.reset()
2032
2048
2033 # Run user hooks
2049 # Run user hooks
2034 self.hooks.shutdown_hook()
2050 self.hooks.shutdown_hook()
2035
2051
2036 def cleanup(self):
2052 def cleanup(self):
2037 self.restore_sys_module_state()
2053 self.restore_sys_module_state()
2038
2054
2039
2055
2040 class InteractiveShellABC(object):
2056 class InteractiveShellABC(object):
2041 """An abstract base class for InteractiveShell."""
2057 """An abstract base class for InteractiveShell."""
2042 __metaclass__ = abc.ABCMeta
2058 __metaclass__ = abc.ABCMeta
2043
2059
2044 InteractiveShellABC.register(InteractiveShell)
2060 InteractiveShellABC.register(InteractiveShell)
@@ -1,41 +1,41 b''
1 """Support for interactive macros in IPython"""
1 """Support for interactive macros in IPython"""
2
2
3 #*****************************************************************************
3 #*****************************************************************************
4 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
4 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
5 #
5 #
6 # Distributed under the terms of the BSD License. The full license is in
6 # Distributed under the terms of the BSD License. The full license is in
7 # the file COPYING, distributed as part of this software.
7 # the file COPYING, distributed as part of this software.
8 #*****************************************************************************
8 #*****************************************************************************
9
9
10 from IPython.utils.io import Term
10 import IPython.utils.io
11 from IPython.core.autocall import IPyAutocall
11 from IPython.core.autocall import IPyAutocall
12
12
13 class Macro(IPyAutocall):
13 class Macro(IPyAutocall):
14 """Simple class to store the value of macros as strings.
14 """Simple class to store the value of macros as strings.
15
15
16 Macro is just a callable that executes a string of IPython
16 Macro is just a callable that executes a string of IPython
17 input when called.
17 input when called.
18
18
19 Args to macro are available in _margv list if you need them.
19 Args to macro are available in _margv list if you need them.
20 """
20 """
21
21
22 def __init__(self,data):
22 def __init__(self,data):
23
23
24 # store the macro value, as a single string which can be evaluated by
24 # store the macro value, as a single string which can be evaluated by
25 # runlines()
25 # runlines()
26 self.value = ''.join(data).rstrip()+'\n'
26 self.value = ''.join(data).rstrip()+'\n'
27
27
28 def __str__(self):
28 def __str__(self):
29 return self.value
29 return self.value
30
30
31 def __repr__(self):
31 def __repr__(self):
32 return 'IPython.macro.Macro(%s)' % repr(self.value)
32 return 'IPython.macro.Macro(%s)' % repr(self.value)
33
33
34 def __call__(self,*args):
34 def __call__(self,*args):
35 Term.cout.flush()
35 IPython.utils.io.Term.cout.flush()
36 self._ip.user_ns['_margv'] = args
36 self._ip.user_ns['_margv'] = args
37 self._ip.runlines(self.value)
37 self._ip.runlines(self.value)
38
38
39 def __getstate__(self):
39 def __getstate__(self):
40 """ needed for safe pickling via %store """
40 """ needed for safe pickling via %store """
41 return {'value': self.value}
41 return {'value': self.value}
@@ -1,3651 +1,3652 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 # print_function was added to __future__ in Python2.6, remove this when we drop
44 # print_function was added to __future__ in Python2.6, remove this when we drop
45 # 2.5 compatibility
45 # 2.5 compatibility
46 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
46 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
47 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
47 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
48
48
49 import IPython
49 import IPython
50 from IPython.core import debugger, oinspect
50 from IPython.core import debugger, oinspect
51 from IPython.core.error import TryNext
51 from IPython.core.error import TryNext
52 from IPython.core.error import UsageError
52 from IPython.core.error import UsageError
53 from IPython.core.fakemodule import FakeModule
53 from IPython.core.fakemodule import FakeModule
54 from IPython.core.macro import Macro
54 from IPython.core.macro import Macro
55 from IPython.core.page import page
55 from IPython.core.page import page
56 from IPython.core.prefilter import ESC_MAGIC
56 from IPython.core.prefilter import ESC_MAGIC
57 from IPython.lib.pylabtools import mpl_runner
57 from IPython.lib.pylabtools import mpl_runner
58 from IPython.lib.inputhook import enable_gui
58 from IPython.lib.inputhook import enable_gui
59 from IPython.external.Itpl import itpl, printpl
59 from IPython.external.Itpl import itpl, printpl
60 from IPython.testing import decorators as testdec
60 from IPython.testing import decorators as testdec
61 from IPython.utils.io import Term, file_read, nlprint
61 from IPython.utils.io import file_read, nlprint
62 import IPython.utils.io
62 from IPython.utils.path import get_py_filename
63 from IPython.utils.path import get_py_filename
63 from IPython.utils.process import arg_split, abbrev_cwd
64 from IPython.utils.process import arg_split, abbrev_cwd
64 from IPython.utils.terminal import set_term_title
65 from IPython.utils.terminal import set_term_title
65 from IPython.utils.text import LSString, SList, StringTypes
66 from IPython.utils.text import LSString, SList, StringTypes
66 from IPython.utils.timing import clock, clock2
67 from IPython.utils.timing import clock, clock2
67 from IPython.utils.warn import warn, error
68 from IPython.utils.warn import warn, error
68 from IPython.utils.ipstruct import Struct
69 from IPython.utils.ipstruct import Struct
69 import IPython.utils.generics
70 import IPython.utils.generics
70
71
71 #-----------------------------------------------------------------------------
72 #-----------------------------------------------------------------------------
72 # Utility functions
73 # Utility functions
73 #-----------------------------------------------------------------------------
74 #-----------------------------------------------------------------------------
74
75
75 def on_off(tag):
76 def on_off(tag):
76 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
77 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
77 return ['OFF','ON'][tag]
78 return ['OFF','ON'][tag]
78
79
79 class Bunch: pass
80 class Bunch: pass
80
81
81 def compress_dhist(dh):
82 def compress_dhist(dh):
82 head, tail = dh[:-10], dh[-10:]
83 head, tail = dh[:-10], dh[-10:]
83
84
84 newhead = []
85 newhead = []
85 done = set()
86 done = set()
86 for h in head:
87 for h in head:
87 if h in done:
88 if h in done:
88 continue
89 continue
89 newhead.append(h)
90 newhead.append(h)
90 done.add(h)
91 done.add(h)
91
92
92 return newhead + tail
93 return newhead + tail
93
94
94
95
95 #***************************************************************************
96 #***************************************************************************
96 # Main class implementing Magic functionality
97 # Main class implementing Magic functionality
97
98
98 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
99 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
99 # on construction of the main InteractiveShell object. Something odd is going
100 # on construction of the main InteractiveShell object. Something odd is going
100 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
101 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
101 # eventually this needs to be clarified.
102 # eventually this needs to be clarified.
102 # BG: This is because InteractiveShell inherits from this, but is itself a
103 # BG: This is because InteractiveShell inherits from this, but is itself a
103 # Configurable. This messes up the MRO in some way. The fix is that we need to
104 # Configurable. This messes up the MRO in some way. The fix is that we need to
104 # make Magic a configurable that InteractiveShell does not subclass.
105 # make Magic a configurable that InteractiveShell does not subclass.
105
106
106 class Magic:
107 class Magic:
107 """Magic functions for InteractiveShell.
108 """Magic functions for InteractiveShell.
108
109
109 Shell functions which can be reached as %function_name. All magic
110 Shell functions which can be reached as %function_name. All magic
110 functions should accept a string, which they can parse for their own
111 functions should accept a string, which they can parse for their own
111 needs. This can make some functions easier to type, eg `%cd ../`
112 needs. This can make some functions easier to type, eg `%cd ../`
112 vs. `%cd("../")`
113 vs. `%cd("../")`
113
114
114 ALL definitions MUST begin with the prefix magic_. The user won't need it
115 ALL definitions MUST begin with the prefix magic_. The user won't need it
115 at the command line, but it is is needed in the definition. """
116 at the command line, but it is is needed in the definition. """
116
117
117 # class globals
118 # class globals
118 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
119 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
119 'Automagic is ON, % prefix NOT needed for magic functions.']
120 'Automagic is ON, % prefix NOT needed for magic functions.']
120
121
121 #......................................................................
122 #......................................................................
122 # some utility functions
123 # some utility functions
123
124
124 def __init__(self,shell):
125 def __init__(self,shell):
125
126
126 self.options_table = {}
127 self.options_table = {}
127 if profile is None:
128 if profile is None:
128 self.magic_prun = self.profile_missing_notice
129 self.magic_prun = self.profile_missing_notice
129 self.shell = shell
130 self.shell = shell
130
131
131 # namespace for holding state we may need
132 # namespace for holding state we may need
132 self._magic_state = Bunch()
133 self._magic_state = Bunch()
133
134
134 def profile_missing_notice(self, *args, **kwargs):
135 def profile_missing_notice(self, *args, **kwargs):
135 error("""\
136 error("""\
136 The profile module could not be found. It has been removed from the standard
137 The profile module could not be found. It has been removed from the standard
137 python packages because of its non-free license. To use profiling, install the
138 python packages because of its non-free license. To use profiling, install the
138 python-profiler package from non-free.""")
139 python-profiler package from non-free.""")
139
140
140 def default_option(self,fn,optstr):
141 def default_option(self,fn,optstr):
141 """Make an entry in the options_table for fn, with value optstr"""
142 """Make an entry in the options_table for fn, with value optstr"""
142
143
143 if fn not in self.lsmagic():
144 if fn not in self.lsmagic():
144 error("%s is not a magic function" % fn)
145 error("%s is not a magic function" % fn)
145 self.options_table[fn] = optstr
146 self.options_table[fn] = optstr
146
147
147 def lsmagic(self):
148 def lsmagic(self):
148 """Return a list of currently available magic functions.
149 """Return a list of currently available magic functions.
149
150
150 Gives a list of the bare names after mangling (['ls','cd', ...], not
151 Gives a list of the bare names after mangling (['ls','cd', ...], not
151 ['magic_ls','magic_cd',...]"""
152 ['magic_ls','magic_cd',...]"""
152
153
153 # FIXME. This needs a cleanup, in the way the magics list is built.
154 # FIXME. This needs a cleanup, in the way the magics list is built.
154
155
155 # magics in class definition
156 # magics in class definition
156 class_magic = lambda fn: fn.startswith('magic_') and \
157 class_magic = lambda fn: fn.startswith('magic_') and \
157 callable(Magic.__dict__[fn])
158 callable(Magic.__dict__[fn])
158 # in instance namespace (run-time user additions)
159 # in instance namespace (run-time user additions)
159 inst_magic = lambda fn: fn.startswith('magic_') and \
160 inst_magic = lambda fn: fn.startswith('magic_') and \
160 callable(self.__dict__[fn])
161 callable(self.__dict__[fn])
161 # and bound magics by user (so they can access self):
162 # and bound magics by user (so they can access self):
162 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
163 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
163 callable(self.__class__.__dict__[fn])
164 callable(self.__class__.__dict__[fn])
164 magics = filter(class_magic,Magic.__dict__.keys()) + \
165 magics = filter(class_magic,Magic.__dict__.keys()) + \
165 filter(inst_magic,self.__dict__.keys()) + \
166 filter(inst_magic,self.__dict__.keys()) + \
166 filter(inst_bound_magic,self.__class__.__dict__.keys())
167 filter(inst_bound_magic,self.__class__.__dict__.keys())
167 out = []
168 out = []
168 for fn in set(magics):
169 for fn in set(magics):
169 out.append(fn.replace('magic_','',1))
170 out.append(fn.replace('magic_','',1))
170 out.sort()
171 out.sort()
171 return out
172 return out
172
173
173 def extract_input_slices(self,slices,raw=False):
174 def extract_input_slices(self,slices,raw=False):
174 """Return as a string a set of input history slices.
175 """Return as a string a set of input history slices.
175
176
176 Inputs:
177 Inputs:
177
178
178 - slices: the set of slices is given as a list of strings (like
179 - slices: the set of slices is given as a list of strings (like
179 ['1','4:8','9'], since this function is for use by magic functions
180 ['1','4:8','9'], since this function is for use by magic functions
180 which get their arguments as strings.
181 which get their arguments as strings.
181
182
182 Optional inputs:
183 Optional inputs:
183
184
184 - raw(False): by default, the processed input is used. If this is
185 - raw(False): by default, the processed input is used. If this is
185 true, the raw input history is used instead.
186 true, the raw input history is used instead.
186
187
187 Note that slices can be called with two notations:
188 Note that slices can be called with two notations:
188
189
189 N:M -> standard python form, means including items N...(M-1).
190 N:M -> standard python form, means including items N...(M-1).
190
191
191 N-M -> include items N..M (closed endpoint)."""
192 N-M -> include items N..M (closed endpoint)."""
192
193
193 if raw:
194 if raw:
194 hist = self.shell.input_hist_raw
195 hist = self.shell.input_hist_raw
195 else:
196 else:
196 hist = self.shell.input_hist
197 hist = self.shell.input_hist
197
198
198 cmds = []
199 cmds = []
199 for chunk in slices:
200 for chunk in slices:
200 if ':' in chunk:
201 if ':' in chunk:
201 ini,fin = map(int,chunk.split(':'))
202 ini,fin = map(int,chunk.split(':'))
202 elif '-' in chunk:
203 elif '-' in chunk:
203 ini,fin = map(int,chunk.split('-'))
204 ini,fin = map(int,chunk.split('-'))
204 fin += 1
205 fin += 1
205 else:
206 else:
206 ini = int(chunk)
207 ini = int(chunk)
207 fin = ini+1
208 fin = ini+1
208 cmds.append(hist[ini:fin])
209 cmds.append(hist[ini:fin])
209 return cmds
210 return cmds
210
211
211 def _ofind(self, oname, namespaces=None):
212 def _ofind(self, oname, namespaces=None):
212 """Find an object in the available namespaces.
213 """Find an object in the available namespaces.
213
214
214 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
215 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
215
216
216 Has special code to detect magic functions.
217 Has special code to detect magic functions.
217 """
218 """
218 oname = oname.strip()
219 oname = oname.strip()
219 alias_ns = None
220 alias_ns = None
220 if namespaces is None:
221 if namespaces is None:
221 # Namespaces to search in:
222 # Namespaces to search in:
222 # Put them in a list. The order is important so that we
223 # Put them in a list. The order is important so that we
223 # find things in the same order that Python finds them.
224 # find things in the same order that Python finds them.
224 namespaces = [ ('Interactive', self.shell.user_ns),
225 namespaces = [ ('Interactive', self.shell.user_ns),
225 ('IPython internal', self.shell.internal_ns),
226 ('IPython internal', self.shell.internal_ns),
226 ('Python builtin', __builtin__.__dict__),
227 ('Python builtin', __builtin__.__dict__),
227 ('Alias', self.shell.alias_manager.alias_table),
228 ('Alias', self.shell.alias_manager.alias_table),
228 ]
229 ]
229 alias_ns = self.shell.alias_manager.alias_table
230 alias_ns = self.shell.alias_manager.alias_table
230
231
231 # initialize results to 'null'
232 # initialize results to 'null'
232 found = False; obj = None; ospace = None; ds = None;
233 found = False; obj = None; ospace = None; ds = None;
233 ismagic = False; isalias = False; parent = None
234 ismagic = False; isalias = False; parent = None
234
235
235 # We need to special-case 'print', which as of python2.6 registers as a
236 # We need to special-case 'print', which as of python2.6 registers as a
236 # function but should only be treated as one if print_function was
237 # function but should only be treated as one if print_function was
237 # loaded with a future import. In this case, just bail.
238 # loaded with a future import. In this case, just bail.
238 if (oname == 'print' and not (self.shell.compile.compiler.flags &
239 if (oname == 'print' and not (self.shell.compile.compiler.flags &
239 __future__.CO_FUTURE_PRINT_FUNCTION)):
240 __future__.CO_FUTURE_PRINT_FUNCTION)):
240 return {'found':found, 'obj':obj, 'namespace':ospace,
241 return {'found':found, 'obj':obj, 'namespace':ospace,
241 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
242 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
242
243
243 # Look for the given name by splitting it in parts. If the head is
244 # Look for the given name by splitting it in parts. If the head is
244 # found, then we look for all the remaining parts as members, and only
245 # found, then we look for all the remaining parts as members, and only
245 # declare success if we can find them all.
246 # declare success if we can find them all.
246 oname_parts = oname.split('.')
247 oname_parts = oname.split('.')
247 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
248 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
248 for nsname,ns in namespaces:
249 for nsname,ns in namespaces:
249 try:
250 try:
250 obj = ns[oname_head]
251 obj = ns[oname_head]
251 except KeyError:
252 except KeyError:
252 continue
253 continue
253 else:
254 else:
254 #print 'oname_rest:', oname_rest # dbg
255 #print 'oname_rest:', oname_rest # dbg
255 for part in oname_rest:
256 for part in oname_rest:
256 try:
257 try:
257 parent = obj
258 parent = obj
258 obj = getattr(obj,part)
259 obj = getattr(obj,part)
259 except:
260 except:
260 # Blanket except b/c some badly implemented objects
261 # Blanket except b/c some badly implemented objects
261 # allow __getattr__ to raise exceptions other than
262 # allow __getattr__ to raise exceptions other than
262 # AttributeError, which then crashes IPython.
263 # AttributeError, which then crashes IPython.
263 break
264 break
264 else:
265 else:
265 # If we finish the for loop (no break), we got all members
266 # If we finish the for loop (no break), we got all members
266 found = True
267 found = True
267 ospace = nsname
268 ospace = nsname
268 if ns == alias_ns:
269 if ns == alias_ns:
269 isalias = True
270 isalias = True
270 break # namespace loop
271 break # namespace loop
271
272
272 # Try to see if it's magic
273 # Try to see if it's magic
273 if not found:
274 if not found:
274 if oname.startswith(ESC_MAGIC):
275 if oname.startswith(ESC_MAGIC):
275 oname = oname[1:]
276 oname = oname[1:]
276 obj = getattr(self,'magic_'+oname,None)
277 obj = getattr(self,'magic_'+oname,None)
277 if obj is not None:
278 if obj is not None:
278 found = True
279 found = True
279 ospace = 'IPython internal'
280 ospace = 'IPython internal'
280 ismagic = True
281 ismagic = True
281
282
282 # Last try: special-case some literals like '', [], {}, etc:
283 # Last try: special-case some literals like '', [], {}, etc:
283 if not found and oname_head in ["''",'""','[]','{}','()']:
284 if not found and oname_head in ["''",'""','[]','{}','()']:
284 obj = eval(oname_head)
285 obj = eval(oname_head)
285 found = True
286 found = True
286 ospace = 'Interactive'
287 ospace = 'Interactive'
287
288
288 return {'found':found, 'obj':obj, 'namespace':ospace,
289 return {'found':found, 'obj':obj, 'namespace':ospace,
289 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
290 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
290
291
291 def arg_err(self,func):
292 def arg_err(self,func):
292 """Print docstring if incorrect arguments were passed"""
293 """Print docstring if incorrect arguments were passed"""
293 print 'Error in arguments:'
294 print 'Error in arguments:'
294 print oinspect.getdoc(func)
295 print oinspect.getdoc(func)
295
296
296 def format_latex(self,strng):
297 def format_latex(self,strng):
297 """Format a string for latex inclusion."""
298 """Format a string for latex inclusion."""
298
299
299 # Characters that need to be escaped for latex:
300 # Characters that need to be escaped for latex:
300 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
301 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
301 # Magic command names as headers:
302 # Magic command names as headers:
302 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
303 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
303 re.MULTILINE)
304 re.MULTILINE)
304 # Magic commands
305 # Magic commands
305 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
306 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
306 re.MULTILINE)
307 re.MULTILINE)
307 # Paragraph continue
308 # Paragraph continue
308 par_re = re.compile(r'\\$',re.MULTILINE)
309 par_re = re.compile(r'\\$',re.MULTILINE)
309
310
310 # The "\n" symbol
311 # The "\n" symbol
311 newline_re = re.compile(r'\\n')
312 newline_re = re.compile(r'\\n')
312
313
313 # Now build the string for output:
314 # Now build the string for output:
314 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
315 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
315 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
316 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
316 strng)
317 strng)
317 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
318 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
318 strng = par_re.sub(r'\\\\',strng)
319 strng = par_re.sub(r'\\\\',strng)
319 strng = escape_re.sub(r'\\\1',strng)
320 strng = escape_re.sub(r'\\\1',strng)
320 strng = newline_re.sub(r'\\textbackslash{}n',strng)
321 strng = newline_re.sub(r'\\textbackslash{}n',strng)
321 return strng
322 return strng
322
323
323 def format_screen(self,strng):
324 def format_screen(self,strng):
324 """Format a string for screen printing.
325 """Format a string for screen printing.
325
326
326 This removes some latex-type format codes."""
327 This removes some latex-type format codes."""
327 # Paragraph continue
328 # Paragraph continue
328 par_re = re.compile(r'\\$',re.MULTILINE)
329 par_re = re.compile(r'\\$',re.MULTILINE)
329 strng = par_re.sub('',strng)
330 strng = par_re.sub('',strng)
330 return strng
331 return strng
331
332
332 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
333 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
333 """Parse options passed to an argument string.
334 """Parse options passed to an argument string.
334
335
335 The interface is similar to that of getopt(), but it returns back a
336 The interface is similar to that of getopt(), but it returns back a
336 Struct with the options as keys and the stripped argument string still
337 Struct with the options as keys and the stripped argument string still
337 as a string.
338 as a string.
338
339
339 arg_str is quoted as a true sys.argv vector by using shlex.split.
340 arg_str is quoted as a true sys.argv vector by using shlex.split.
340 This allows us to easily expand variables, glob files, quote
341 This allows us to easily expand variables, glob files, quote
341 arguments, etc.
342 arguments, etc.
342
343
343 Options:
344 Options:
344 -mode: default 'string'. If given as 'list', the argument string is
345 -mode: default 'string'. If given as 'list', the argument string is
345 returned as a list (split on whitespace) instead of a string.
346 returned as a list (split on whitespace) instead of a string.
346
347
347 -list_all: put all option values in lists. Normally only options
348 -list_all: put all option values in lists. Normally only options
348 appearing more than once are put in a list.
349 appearing more than once are put in a list.
349
350
350 -posix (True): whether to split the input line in POSIX mode or not,
351 -posix (True): whether to split the input line in POSIX mode or not,
351 as per the conventions outlined in the shlex module from the
352 as per the conventions outlined in the shlex module from the
352 standard library."""
353 standard library."""
353
354
354 # inject default options at the beginning of the input line
355 # inject default options at the beginning of the input line
355 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
356 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
356 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
357 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
357
358
358 mode = kw.get('mode','string')
359 mode = kw.get('mode','string')
359 if mode not in ['string','list']:
360 if mode not in ['string','list']:
360 raise ValueError,'incorrect mode given: %s' % mode
361 raise ValueError,'incorrect mode given: %s' % mode
361 # Get options
362 # Get options
362 list_all = kw.get('list_all',0)
363 list_all = kw.get('list_all',0)
363 posix = kw.get('posix', os.name == 'posix')
364 posix = kw.get('posix', os.name == 'posix')
364
365
365 # Check if we have more than one argument to warrant extra processing:
366 # Check if we have more than one argument to warrant extra processing:
366 odict = {} # Dictionary with options
367 odict = {} # Dictionary with options
367 args = arg_str.split()
368 args = arg_str.split()
368 if len(args) >= 1:
369 if len(args) >= 1:
369 # If the list of inputs only has 0 or 1 thing in it, there's no
370 # If the list of inputs only has 0 or 1 thing in it, there's no
370 # need to look for options
371 # need to look for options
371 argv = arg_split(arg_str,posix)
372 argv = arg_split(arg_str,posix)
372 # Do regular option processing
373 # Do regular option processing
373 try:
374 try:
374 opts,args = getopt(argv,opt_str,*long_opts)
375 opts,args = getopt(argv,opt_str,*long_opts)
375 except GetoptError,e:
376 except GetoptError,e:
376 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
377 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
377 " ".join(long_opts)))
378 " ".join(long_opts)))
378 for o,a in opts:
379 for o,a in opts:
379 if o.startswith('--'):
380 if o.startswith('--'):
380 o = o[2:]
381 o = o[2:]
381 else:
382 else:
382 o = o[1:]
383 o = o[1:]
383 try:
384 try:
384 odict[o].append(a)
385 odict[o].append(a)
385 except AttributeError:
386 except AttributeError:
386 odict[o] = [odict[o],a]
387 odict[o] = [odict[o],a]
387 except KeyError:
388 except KeyError:
388 if list_all:
389 if list_all:
389 odict[o] = [a]
390 odict[o] = [a]
390 else:
391 else:
391 odict[o] = a
392 odict[o] = a
392
393
393 # Prepare opts,args for return
394 # Prepare opts,args for return
394 opts = Struct(odict)
395 opts = Struct(odict)
395 if mode == 'string':
396 if mode == 'string':
396 args = ' '.join(args)
397 args = ' '.join(args)
397
398
398 return opts,args
399 return opts,args
399
400
400 #......................................................................
401 #......................................................................
401 # And now the actual magic functions
402 # And now the actual magic functions
402
403
403 # Functions for IPython shell work (vars,funcs, config, etc)
404 # Functions for IPython shell work (vars,funcs, config, etc)
404 def magic_lsmagic(self, parameter_s = ''):
405 def magic_lsmagic(self, parameter_s = ''):
405 """List currently available magic functions."""
406 """List currently available magic functions."""
406 mesc = ESC_MAGIC
407 mesc = ESC_MAGIC
407 print 'Available magic functions:\n'+mesc+\
408 print 'Available magic functions:\n'+mesc+\
408 (' '+mesc).join(self.lsmagic())
409 (' '+mesc).join(self.lsmagic())
409 print '\n' + Magic.auto_status[self.shell.automagic]
410 print '\n' + Magic.auto_status[self.shell.automagic]
410 return None
411 return None
411
412
412 def magic_magic(self, parameter_s = ''):
413 def magic_magic(self, parameter_s = ''):
413 """Print information about the magic function system.
414 """Print information about the magic function system.
414
415
415 Supported formats: -latex, -brief, -rest
416 Supported formats: -latex, -brief, -rest
416 """
417 """
417
418
418 mode = ''
419 mode = ''
419 try:
420 try:
420 if parameter_s.split()[0] == '-latex':
421 if parameter_s.split()[0] == '-latex':
421 mode = 'latex'
422 mode = 'latex'
422 if parameter_s.split()[0] == '-brief':
423 if parameter_s.split()[0] == '-brief':
423 mode = 'brief'
424 mode = 'brief'
424 if parameter_s.split()[0] == '-rest':
425 if parameter_s.split()[0] == '-rest':
425 mode = 'rest'
426 mode = 'rest'
426 rest_docs = []
427 rest_docs = []
427 except:
428 except:
428 pass
429 pass
429
430
430 magic_docs = []
431 magic_docs = []
431 for fname in self.lsmagic():
432 for fname in self.lsmagic():
432 mname = 'magic_' + fname
433 mname = 'magic_' + fname
433 for space in (Magic,self,self.__class__):
434 for space in (Magic,self,self.__class__):
434 try:
435 try:
435 fn = space.__dict__[mname]
436 fn = space.__dict__[mname]
436 except KeyError:
437 except KeyError:
437 pass
438 pass
438 else:
439 else:
439 break
440 break
440 if mode == 'brief':
441 if mode == 'brief':
441 # only first line
442 # only first line
442 if fn.__doc__:
443 if fn.__doc__:
443 fndoc = fn.__doc__.split('\n',1)[0]
444 fndoc = fn.__doc__.split('\n',1)[0]
444 else:
445 else:
445 fndoc = 'No documentation'
446 fndoc = 'No documentation'
446 else:
447 else:
447 if fn.__doc__:
448 if fn.__doc__:
448 fndoc = fn.__doc__.rstrip()
449 fndoc = fn.__doc__.rstrip()
449 else:
450 else:
450 fndoc = 'No documentation'
451 fndoc = 'No documentation'
451
452
452
453
453 if mode == 'rest':
454 if mode == 'rest':
454 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
455 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
455 fname,fndoc))
456 fname,fndoc))
456
457
457 else:
458 else:
458 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
459 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
459 fname,fndoc))
460 fname,fndoc))
460
461
461 magic_docs = ''.join(magic_docs)
462 magic_docs = ''.join(magic_docs)
462
463
463 if mode == 'rest':
464 if mode == 'rest':
464 return "".join(rest_docs)
465 return "".join(rest_docs)
465
466
466 if mode == 'latex':
467 if mode == 'latex':
467 print self.format_latex(magic_docs)
468 print self.format_latex(magic_docs)
468 return
469 return
469 else:
470 else:
470 magic_docs = self.format_screen(magic_docs)
471 magic_docs = self.format_screen(magic_docs)
471 if mode == 'brief':
472 if mode == 'brief':
472 return magic_docs
473 return magic_docs
473
474
474 outmsg = """
475 outmsg = """
475 IPython's 'magic' functions
476 IPython's 'magic' functions
476 ===========================
477 ===========================
477
478
478 The magic function system provides a series of functions which allow you to
479 The magic function system provides a series of functions which allow you to
479 control the behavior of IPython itself, plus a lot of system-type
480 control the behavior of IPython itself, plus a lot of system-type
480 features. All these functions are prefixed with a % character, but parameters
481 features. All these functions are prefixed with a % character, but parameters
481 are given without parentheses or quotes.
482 are given without parentheses or quotes.
482
483
483 NOTE: If you have 'automagic' enabled (via the command line option or with the
484 NOTE: If you have 'automagic' enabled (via the command line option or with the
484 %automagic function), you don't need to type in the % explicitly. By default,
485 %automagic function), you don't need to type in the % explicitly. By default,
485 IPython ships with automagic on, so you should only rarely need the % escape.
486 IPython ships with automagic on, so you should only rarely need the % escape.
486
487
487 Example: typing '%cd mydir' (without the quotes) changes you working directory
488 Example: typing '%cd mydir' (without the quotes) changes you working directory
488 to 'mydir', if it exists.
489 to 'mydir', if it exists.
489
490
490 You can define your own magic functions to extend the system. See the supplied
491 You can define your own magic functions to extend the system. See the supplied
491 ipythonrc and example-magic.py files for details (in your ipython
492 ipythonrc and example-magic.py files for details (in your ipython
492 configuration directory, typically $HOME/.ipython/).
493 configuration directory, typically $HOME/.ipython/).
493
494
494 You can also define your own aliased names for magic functions. In your
495 You can also define your own aliased names for magic functions. In your
495 ipythonrc file, placing a line like:
496 ipythonrc file, placing a line like:
496
497
497 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
498 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
498
499
499 will define %pf as a new name for %profile.
500 will define %pf as a new name for %profile.
500
501
501 You can also call magics in code using the magic() function, which IPython
502 You can also call magics in code using the magic() function, which IPython
502 automatically adds to the builtin namespace. Type 'magic?' for details.
503 automatically adds to the builtin namespace. Type 'magic?' for details.
503
504
504 For a list of the available magic functions, use %lsmagic. For a description
505 For a list of the available magic functions, use %lsmagic. For a description
505 of any of them, type %magic_name?, e.g. '%cd?'.
506 of any of them, type %magic_name?, e.g. '%cd?'.
506
507
507 Currently the magic system has the following functions:\n"""
508 Currently the magic system has the following functions:\n"""
508
509
509 mesc = ESC_MAGIC
510 mesc = ESC_MAGIC
510 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
511 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
511 "\n\n%s%s\n\n%s" % (outmsg,
512 "\n\n%s%s\n\n%s" % (outmsg,
512 magic_docs,mesc,mesc,
513 magic_docs,mesc,mesc,
513 (' '+mesc).join(self.lsmagic()),
514 (' '+mesc).join(self.lsmagic()),
514 Magic.auto_status[self.shell.automagic] ) )
515 Magic.auto_status[self.shell.automagic] ) )
515
516
516 page(outmsg,screen_lines=self.shell.usable_screen_length)
517 page(outmsg,screen_lines=self.shell.usable_screen_length)
517
518
518
519
519 def magic_autoindent(self, parameter_s = ''):
520 def magic_autoindent(self, parameter_s = ''):
520 """Toggle autoindent on/off (if available)."""
521 """Toggle autoindent on/off (if available)."""
521
522
522 self.shell.set_autoindent()
523 self.shell.set_autoindent()
523 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
524 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
524
525
525
526
526 def magic_automagic(self, parameter_s = ''):
527 def magic_automagic(self, parameter_s = ''):
527 """Make magic functions callable without having to type the initial %.
528 """Make magic functions callable without having to type the initial %.
528
529
529 Without argumentsl toggles on/off (when off, you must call it as
530 Without argumentsl toggles on/off (when off, you must call it as
530 %automagic, of course). With arguments it sets the value, and you can
531 %automagic, of course). With arguments it sets the value, and you can
531 use any of (case insensitive):
532 use any of (case insensitive):
532
533
533 - on,1,True: to activate
534 - on,1,True: to activate
534
535
535 - off,0,False: to deactivate.
536 - off,0,False: to deactivate.
536
537
537 Note that magic functions have lowest priority, so if there's a
538 Note that magic functions have lowest priority, so if there's a
538 variable whose name collides with that of a magic fn, automagic won't
539 variable whose name collides with that of a magic fn, automagic won't
539 work for that function (you get the variable instead). However, if you
540 work for that function (you get the variable instead). However, if you
540 delete the variable (del var), the previously shadowed magic function
541 delete the variable (del var), the previously shadowed magic function
541 becomes visible to automagic again."""
542 becomes visible to automagic again."""
542
543
543 arg = parameter_s.lower()
544 arg = parameter_s.lower()
544 if parameter_s in ('on','1','true'):
545 if parameter_s in ('on','1','true'):
545 self.shell.automagic = True
546 self.shell.automagic = True
546 elif parameter_s in ('off','0','false'):
547 elif parameter_s in ('off','0','false'):
547 self.shell.automagic = False
548 self.shell.automagic = False
548 else:
549 else:
549 self.shell.automagic = not self.shell.automagic
550 self.shell.automagic = not self.shell.automagic
550 print '\n' + Magic.auto_status[self.shell.automagic]
551 print '\n' + Magic.auto_status[self.shell.automagic]
551
552
552 @testdec.skip_doctest
553 @testdec.skip_doctest
553 def magic_autocall(self, parameter_s = ''):
554 def magic_autocall(self, parameter_s = ''):
554 """Make functions callable without having to type parentheses.
555 """Make functions callable without having to type parentheses.
555
556
556 Usage:
557 Usage:
557
558
558 %autocall [mode]
559 %autocall [mode]
559
560
560 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
561 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
561 value is toggled on and off (remembering the previous state).
562 value is toggled on and off (remembering the previous state).
562
563
563 In more detail, these values mean:
564 In more detail, these values mean:
564
565
565 0 -> fully disabled
566 0 -> fully disabled
566
567
567 1 -> active, but do not apply if there are no arguments on the line.
568 1 -> active, but do not apply if there are no arguments on the line.
568
569
569 In this mode, you get:
570 In this mode, you get:
570
571
571 In [1]: callable
572 In [1]: callable
572 Out[1]: <built-in function callable>
573 Out[1]: <built-in function callable>
573
574
574 In [2]: callable 'hello'
575 In [2]: callable 'hello'
575 ------> callable('hello')
576 ------> callable('hello')
576 Out[2]: False
577 Out[2]: False
577
578
578 2 -> Active always. Even if no arguments are present, the callable
579 2 -> Active always. Even if no arguments are present, the callable
579 object is called:
580 object is called:
580
581
581 In [2]: float
582 In [2]: float
582 ------> float()
583 ------> float()
583 Out[2]: 0.0
584 Out[2]: 0.0
584
585
585 Note that even with autocall off, you can still use '/' at the start of
586 Note that even with autocall off, you can still use '/' at the start of
586 a line to treat the first argument on the command line as a function
587 a line to treat the first argument on the command line as a function
587 and add parentheses to it:
588 and add parentheses to it:
588
589
589 In [8]: /str 43
590 In [8]: /str 43
590 ------> str(43)
591 ------> str(43)
591 Out[8]: '43'
592 Out[8]: '43'
592
593
593 # all-random (note for auto-testing)
594 # all-random (note for auto-testing)
594 """
595 """
595
596
596 if parameter_s:
597 if parameter_s:
597 arg = int(parameter_s)
598 arg = int(parameter_s)
598 else:
599 else:
599 arg = 'toggle'
600 arg = 'toggle'
600
601
601 if not arg in (0,1,2,'toggle'):
602 if not arg in (0,1,2,'toggle'):
602 error('Valid modes: (0->Off, 1->Smart, 2->Full')
603 error('Valid modes: (0->Off, 1->Smart, 2->Full')
603 return
604 return
604
605
605 if arg in (0,1,2):
606 if arg in (0,1,2):
606 self.shell.autocall = arg
607 self.shell.autocall = arg
607 else: # toggle
608 else: # toggle
608 if self.shell.autocall:
609 if self.shell.autocall:
609 self._magic_state.autocall_save = self.shell.autocall
610 self._magic_state.autocall_save = self.shell.autocall
610 self.shell.autocall = 0
611 self.shell.autocall = 0
611 else:
612 else:
612 try:
613 try:
613 self.shell.autocall = self._magic_state.autocall_save
614 self.shell.autocall = self._magic_state.autocall_save
614 except AttributeError:
615 except AttributeError:
615 self.shell.autocall = self._magic_state.autocall_save = 1
616 self.shell.autocall = self._magic_state.autocall_save = 1
616
617
617 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
618 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
618
619
619 def magic_system_verbose(self, parameter_s = ''):
620 def magic_system_verbose(self, parameter_s = ''):
620 """Set verbose printing of system calls.
621 """Set verbose printing of system calls.
621
622
622 If called without an argument, act as a toggle"""
623 If called without an argument, act as a toggle"""
623
624
624 if parameter_s:
625 if parameter_s:
625 val = bool(eval(parameter_s))
626 val = bool(eval(parameter_s))
626 else:
627 else:
627 val = None
628 val = None
628
629
629 if self.shell.system_verbose:
630 if self.shell.system_verbose:
630 self.shell.system_verbose = False
631 self.shell.system_verbose = False
631 else:
632 else:
632 self.shell.system_verbose = True
633 self.shell.system_verbose = True
633 print "System verbose printing is:",\
634 print "System verbose printing is:",\
634 ['OFF','ON'][self.shell.system_verbose]
635 ['OFF','ON'][self.shell.system_verbose]
635
636
636
637
637 def magic_page(self, parameter_s=''):
638 def magic_page(self, parameter_s=''):
638 """Pretty print the object and display it through a pager.
639 """Pretty print the object and display it through a pager.
639
640
640 %page [options] OBJECT
641 %page [options] OBJECT
641
642
642 If no object is given, use _ (last output).
643 If no object is given, use _ (last output).
643
644
644 Options:
645 Options:
645
646
646 -r: page str(object), don't pretty-print it."""
647 -r: page str(object), don't pretty-print it."""
647
648
648 # After a function contributed by Olivier Aubert, slightly modified.
649 # After a function contributed by Olivier Aubert, slightly modified.
649
650
650 # Process options/args
651 # Process options/args
651 opts,args = self.parse_options(parameter_s,'r')
652 opts,args = self.parse_options(parameter_s,'r')
652 raw = 'r' in opts
653 raw = 'r' in opts
653
654
654 oname = args and args or '_'
655 oname = args and args or '_'
655 info = self._ofind(oname)
656 info = self._ofind(oname)
656 if info['found']:
657 if info['found']:
657 txt = (raw and str or pformat)( info['obj'] )
658 txt = (raw and str or pformat)( info['obj'] )
658 page(txt)
659 page(txt)
659 else:
660 else:
660 print 'Object `%s` not found' % oname
661 print 'Object `%s` not found' % oname
661
662
662 def magic_profile(self, parameter_s=''):
663 def magic_profile(self, parameter_s=''):
663 """Print your currently active IPython profile."""
664 """Print your currently active IPython profile."""
664 if self.shell.profile:
665 if self.shell.profile:
665 printpl('Current IPython profile: $self.shell.profile.')
666 printpl('Current IPython profile: $self.shell.profile.')
666 else:
667 else:
667 print 'No profile active.'
668 print 'No profile active.'
668
669
669 def magic_pinfo(self, parameter_s='', namespaces=None):
670 def magic_pinfo(self, parameter_s='', namespaces=None):
670 """Provide detailed information about an object.
671 """Provide detailed information about an object.
671
672
672 '%pinfo object' is just a synonym for object? or ?object."""
673 '%pinfo object' is just a synonym for object? or ?object."""
673
674
674 #print 'pinfo par: <%s>' % parameter_s # dbg
675 #print 'pinfo par: <%s>' % parameter_s # dbg
675
676
676
677
677 # detail_level: 0 -> obj? , 1 -> obj??
678 # detail_level: 0 -> obj? , 1 -> obj??
678 detail_level = 0
679 detail_level = 0
679 # We need to detect if we got called as 'pinfo pinfo foo', which can
680 # We need to detect if we got called as 'pinfo pinfo foo', which can
680 # happen if the user types 'pinfo foo?' at the cmd line.
681 # happen if the user types 'pinfo foo?' at the cmd line.
681 pinfo,qmark1,oname,qmark2 = \
682 pinfo,qmark1,oname,qmark2 = \
682 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
683 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
683 if pinfo or qmark1 or qmark2:
684 if pinfo or qmark1 or qmark2:
684 detail_level = 1
685 detail_level = 1
685 if "*" in oname:
686 if "*" in oname:
686 self.magic_psearch(oname)
687 self.magic_psearch(oname)
687 else:
688 else:
688 self._inspect('pinfo', oname, detail_level=detail_level,
689 self._inspect('pinfo', oname, detail_level=detail_level,
689 namespaces=namespaces)
690 namespaces=namespaces)
690
691
691 def magic_pdef(self, parameter_s='', namespaces=None):
692 def magic_pdef(self, parameter_s='', namespaces=None):
692 """Print the definition header for any callable object.
693 """Print the definition header for any callable object.
693
694
694 If the object is a class, print the constructor information."""
695 If the object is a class, print the constructor information."""
695 self._inspect('pdef',parameter_s, namespaces)
696 self._inspect('pdef',parameter_s, namespaces)
696
697
697 def magic_pdoc(self, parameter_s='', namespaces=None):
698 def magic_pdoc(self, parameter_s='', namespaces=None):
698 """Print the docstring for an object.
699 """Print the docstring for an object.
699
700
700 If the given object is a class, it will print both the class and the
701 If the given object is a class, it will print both the class and the
701 constructor docstrings."""
702 constructor docstrings."""
702 self._inspect('pdoc',parameter_s, namespaces)
703 self._inspect('pdoc',parameter_s, namespaces)
703
704
704 def magic_psource(self, parameter_s='', namespaces=None):
705 def magic_psource(self, parameter_s='', namespaces=None):
705 """Print (or run through pager) the source code for an object."""
706 """Print (or run through pager) the source code for an object."""
706 self._inspect('psource',parameter_s, namespaces)
707 self._inspect('psource',parameter_s, namespaces)
707
708
708 def magic_pfile(self, parameter_s=''):
709 def magic_pfile(self, parameter_s=''):
709 """Print (or run through pager) the file where an object is defined.
710 """Print (or run through pager) the file where an object is defined.
710
711
711 The file opens at the line where the object definition begins. IPython
712 The file opens at the line where the object definition begins. IPython
712 will honor the environment variable PAGER if set, and otherwise will
713 will honor the environment variable PAGER if set, and otherwise will
713 do its best to print the file in a convenient form.
714 do its best to print the file in a convenient form.
714
715
715 If the given argument is not an object currently defined, IPython will
716 If the given argument is not an object currently defined, IPython will
716 try to interpret it as a filename (automatically adding a .py extension
717 try to interpret it as a filename (automatically adding a .py extension
717 if needed). You can thus use %pfile as a syntax highlighting code
718 if needed). You can thus use %pfile as a syntax highlighting code
718 viewer."""
719 viewer."""
719
720
720 # first interpret argument as an object name
721 # first interpret argument as an object name
721 out = self._inspect('pfile',parameter_s)
722 out = self._inspect('pfile',parameter_s)
722 # if not, try the input as a filename
723 # if not, try the input as a filename
723 if out == 'not found':
724 if out == 'not found':
724 try:
725 try:
725 filename = get_py_filename(parameter_s)
726 filename = get_py_filename(parameter_s)
726 except IOError,msg:
727 except IOError,msg:
727 print msg
728 print msg
728 return
729 return
729 page(self.shell.inspector.format(file(filename).read()))
730 page(self.shell.inspector.format(file(filename).read()))
730
731
731 def _inspect(self,meth,oname,namespaces=None,**kw):
732 def _inspect(self,meth,oname,namespaces=None,**kw):
732 """Generic interface to the inspector system.
733 """Generic interface to the inspector system.
733
734
734 This function is meant to be called by pdef, pdoc & friends."""
735 This function is meant to be called by pdef, pdoc & friends."""
735
736
736 #oname = oname.strip()
737 #oname = oname.strip()
737 #print '1- oname: <%r>' % oname # dbg
738 #print '1- oname: <%r>' % oname # dbg
738 try:
739 try:
739 oname = oname.strip().encode('ascii')
740 oname = oname.strip().encode('ascii')
740 #print '2- oname: <%r>' % oname # dbg
741 #print '2- oname: <%r>' % oname # dbg
741 except UnicodeEncodeError:
742 except UnicodeEncodeError:
742 print 'Python identifiers can only contain ascii characters.'
743 print 'Python identifiers can only contain ascii characters.'
743 return 'not found'
744 return 'not found'
744
745
745 info = Struct(self._ofind(oname, namespaces))
746 info = Struct(self._ofind(oname, namespaces))
746
747
747 if info.found:
748 if info.found:
748 try:
749 try:
749 IPython.utils.generics.inspect_object(info.obj)
750 IPython.utils.generics.inspect_object(info.obj)
750 return
751 return
751 except TryNext:
752 except TryNext:
752 pass
753 pass
753 # Get the docstring of the class property if it exists.
754 # Get the docstring of the class property if it exists.
754 path = oname.split('.')
755 path = oname.split('.')
755 root = '.'.join(path[:-1])
756 root = '.'.join(path[:-1])
756 if info.parent is not None:
757 if info.parent is not None:
757 try:
758 try:
758 target = getattr(info.parent, '__class__')
759 target = getattr(info.parent, '__class__')
759 # The object belongs to a class instance.
760 # The object belongs to a class instance.
760 try:
761 try:
761 target = getattr(target, path[-1])
762 target = getattr(target, path[-1])
762 # The class defines the object.
763 # The class defines the object.
763 if isinstance(target, property):
764 if isinstance(target, property):
764 oname = root + '.__class__.' + path[-1]
765 oname = root + '.__class__.' + path[-1]
765 info = Struct(self._ofind(oname))
766 info = Struct(self._ofind(oname))
766 except AttributeError: pass
767 except AttributeError: pass
767 except AttributeError: pass
768 except AttributeError: pass
768
769
769 pmethod = getattr(self.shell.inspector,meth)
770 pmethod = getattr(self.shell.inspector,meth)
770 formatter = info.ismagic and self.format_screen or None
771 formatter = info.ismagic and self.format_screen or None
771 if meth == 'pdoc':
772 if meth == 'pdoc':
772 pmethod(info.obj,oname,formatter)
773 pmethod(info.obj,oname,formatter)
773 elif meth == 'pinfo':
774 elif meth == 'pinfo':
774 pmethod(info.obj,oname,formatter,info,**kw)
775 pmethod(info.obj,oname,formatter,info,**kw)
775 else:
776 else:
776 pmethod(info.obj,oname)
777 pmethod(info.obj,oname)
777 else:
778 else:
778 print 'Object `%s` not found.' % oname
779 print 'Object `%s` not found.' % oname
779 return 'not found' # so callers can take other action
780 return 'not found' # so callers can take other action
780
781
781 def magic_psearch(self, parameter_s=''):
782 def magic_psearch(self, parameter_s=''):
782 """Search for object in namespaces by wildcard.
783 """Search for object in namespaces by wildcard.
783
784
784 %psearch [options] PATTERN [OBJECT TYPE]
785 %psearch [options] PATTERN [OBJECT TYPE]
785
786
786 Note: ? can be used as a synonym for %psearch, at the beginning or at
787 Note: ? can be used as a synonym for %psearch, at the beginning or at
787 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
788 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
788 rest of the command line must be unchanged (options come first), so
789 rest of the command line must be unchanged (options come first), so
789 for example the following forms are equivalent
790 for example the following forms are equivalent
790
791
791 %psearch -i a* function
792 %psearch -i a* function
792 -i a* function?
793 -i a* function?
793 ?-i a* function
794 ?-i a* function
794
795
795 Arguments:
796 Arguments:
796
797
797 PATTERN
798 PATTERN
798
799
799 where PATTERN is a string containing * as a wildcard similar to its
800 where PATTERN is a string containing * as a wildcard similar to its
800 use in a shell. The pattern is matched in all namespaces on the
801 use in a shell. The pattern is matched in all namespaces on the
801 search path. By default objects starting with a single _ are not
802 search path. By default objects starting with a single _ are not
802 matched, many IPython generated objects have a single
803 matched, many IPython generated objects have a single
803 underscore. The default is case insensitive matching. Matching is
804 underscore. The default is case insensitive matching. Matching is
804 also done on the attributes of objects and not only on the objects
805 also done on the attributes of objects and not only on the objects
805 in a module.
806 in a module.
806
807
807 [OBJECT TYPE]
808 [OBJECT TYPE]
808
809
809 Is the name of a python type from the types module. The name is
810 Is the name of a python type from the types module. The name is
810 given in lowercase without the ending type, ex. StringType is
811 given in lowercase without the ending type, ex. StringType is
811 written string. By adding a type here only objects matching the
812 written string. By adding a type here only objects matching the
812 given type are matched. Using all here makes the pattern match all
813 given type are matched. Using all here makes the pattern match all
813 types (this is the default).
814 types (this is the default).
814
815
815 Options:
816 Options:
816
817
817 -a: makes the pattern match even objects whose names start with a
818 -a: makes the pattern match even objects whose names start with a
818 single underscore. These names are normally ommitted from the
819 single underscore. These names are normally ommitted from the
819 search.
820 search.
820
821
821 -i/-c: make the pattern case insensitive/sensitive. If neither of
822 -i/-c: make the pattern case insensitive/sensitive. If neither of
822 these options is given, the default is read from your ipythonrc
823 these options is given, the default is read from your ipythonrc
823 file. The option name which sets this value is
824 file. The option name which sets this value is
824 'wildcards_case_sensitive'. If this option is not specified in your
825 'wildcards_case_sensitive'. If this option is not specified in your
825 ipythonrc file, IPython's internal default is to do a case sensitive
826 ipythonrc file, IPython's internal default is to do a case sensitive
826 search.
827 search.
827
828
828 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
829 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
829 specifiy can be searched in any of the following namespaces:
830 specifiy can be searched in any of the following namespaces:
830 'builtin', 'user', 'user_global','internal', 'alias', where
831 'builtin', 'user', 'user_global','internal', 'alias', where
831 'builtin' and 'user' are the search defaults. Note that you should
832 'builtin' and 'user' are the search defaults. Note that you should
832 not use quotes when specifying namespaces.
833 not use quotes when specifying namespaces.
833
834
834 'Builtin' contains the python module builtin, 'user' contains all
835 'Builtin' contains the python module builtin, 'user' contains all
835 user data, 'alias' only contain the shell aliases and no python
836 user data, 'alias' only contain the shell aliases and no python
836 objects, 'internal' contains objects used by IPython. The
837 objects, 'internal' contains objects used by IPython. The
837 'user_global' namespace is only used by embedded IPython instances,
838 'user_global' namespace is only used by embedded IPython instances,
838 and it contains module-level globals. You can add namespaces to the
839 and it contains module-level globals. You can add namespaces to the
839 search with -s or exclude them with -e (these options can be given
840 search with -s or exclude them with -e (these options can be given
840 more than once).
841 more than once).
841
842
842 Examples:
843 Examples:
843
844
844 %psearch a* -> objects beginning with an a
845 %psearch a* -> objects beginning with an a
845 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
846 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
846 %psearch a* function -> all functions beginning with an a
847 %psearch a* function -> all functions beginning with an a
847 %psearch re.e* -> objects beginning with an e in module re
848 %psearch re.e* -> objects beginning with an e in module re
848 %psearch r*.e* -> objects that start with e in modules starting in r
849 %psearch r*.e* -> objects that start with e in modules starting in r
849 %psearch r*.* string -> all strings in modules beginning with r
850 %psearch r*.* string -> all strings in modules beginning with r
850
851
851 Case sensitve search:
852 Case sensitve search:
852
853
853 %psearch -c a* list all object beginning with lower case a
854 %psearch -c a* list all object beginning with lower case a
854
855
855 Show objects beginning with a single _:
856 Show objects beginning with a single _:
856
857
857 %psearch -a _* list objects beginning with a single underscore"""
858 %psearch -a _* list objects beginning with a single underscore"""
858 try:
859 try:
859 parameter_s = parameter_s.encode('ascii')
860 parameter_s = parameter_s.encode('ascii')
860 except UnicodeEncodeError:
861 except UnicodeEncodeError:
861 print 'Python identifiers can only contain ascii characters.'
862 print 'Python identifiers can only contain ascii characters.'
862 return
863 return
863
864
864 # default namespaces to be searched
865 # default namespaces to be searched
865 def_search = ['user','builtin']
866 def_search = ['user','builtin']
866
867
867 # Process options/args
868 # Process options/args
868 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
869 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
869 opt = opts.get
870 opt = opts.get
870 shell = self.shell
871 shell = self.shell
871 psearch = shell.inspector.psearch
872 psearch = shell.inspector.psearch
872
873
873 # select case options
874 # select case options
874 if opts.has_key('i'):
875 if opts.has_key('i'):
875 ignore_case = True
876 ignore_case = True
876 elif opts.has_key('c'):
877 elif opts.has_key('c'):
877 ignore_case = False
878 ignore_case = False
878 else:
879 else:
879 ignore_case = not shell.wildcards_case_sensitive
880 ignore_case = not shell.wildcards_case_sensitive
880
881
881 # Build list of namespaces to search from user options
882 # Build list of namespaces to search from user options
882 def_search.extend(opt('s',[]))
883 def_search.extend(opt('s',[]))
883 ns_exclude = ns_exclude=opt('e',[])
884 ns_exclude = ns_exclude=opt('e',[])
884 ns_search = [nm for nm in def_search if nm not in ns_exclude]
885 ns_search = [nm for nm in def_search if nm not in ns_exclude]
885
886
886 # Call the actual search
887 # Call the actual search
887 try:
888 try:
888 psearch(args,shell.ns_table,ns_search,
889 psearch(args,shell.ns_table,ns_search,
889 show_all=opt('a'),ignore_case=ignore_case)
890 show_all=opt('a'),ignore_case=ignore_case)
890 except:
891 except:
891 shell.showtraceback()
892 shell.showtraceback()
892
893
893 def magic_who_ls(self, parameter_s=''):
894 def magic_who_ls(self, parameter_s=''):
894 """Return a sorted list of all interactive variables.
895 """Return a sorted list of all interactive variables.
895
896
896 If arguments are given, only variables of types matching these
897 If arguments are given, only variables of types matching these
897 arguments are returned."""
898 arguments are returned."""
898
899
899 user_ns = self.shell.user_ns
900 user_ns = self.shell.user_ns
900 internal_ns = self.shell.internal_ns
901 internal_ns = self.shell.internal_ns
901 user_ns_hidden = self.shell.user_ns_hidden
902 user_ns_hidden = self.shell.user_ns_hidden
902 out = [ i for i in user_ns
903 out = [ i for i in user_ns
903 if not i.startswith('_') \
904 if not i.startswith('_') \
904 and not (i in internal_ns or i in user_ns_hidden) ]
905 and not (i in internal_ns or i in user_ns_hidden) ]
905
906
906 typelist = parameter_s.split()
907 typelist = parameter_s.split()
907 if typelist:
908 if typelist:
908 typeset = set(typelist)
909 typeset = set(typelist)
909 out = [i for i in out if type(i).__name__ in typeset]
910 out = [i for i in out if type(i).__name__ in typeset]
910
911
911 out.sort()
912 out.sort()
912 return out
913 return out
913
914
914 def magic_who(self, parameter_s=''):
915 def magic_who(self, parameter_s=''):
915 """Print all interactive variables, with some minimal formatting.
916 """Print all interactive variables, with some minimal formatting.
916
917
917 If any arguments are given, only variables whose type matches one of
918 If any arguments are given, only variables whose type matches one of
918 these are printed. For example:
919 these are printed. For example:
919
920
920 %who function str
921 %who function str
921
922
922 will only list functions and strings, excluding all other types of
923 will only list functions and strings, excluding all other types of
923 variables. To find the proper type names, simply use type(var) at a
924 variables. To find the proper type names, simply use type(var) at a
924 command line to see how python prints type names. For example:
925 command line to see how python prints type names. For example:
925
926
926 In [1]: type('hello')\\
927 In [1]: type('hello')\\
927 Out[1]: <type 'str'>
928 Out[1]: <type 'str'>
928
929
929 indicates that the type name for strings is 'str'.
930 indicates that the type name for strings is 'str'.
930
931
931 %who always excludes executed names loaded through your configuration
932 %who always excludes executed names loaded through your configuration
932 file and things which are internal to IPython.
933 file and things which are internal to IPython.
933
934
934 This is deliberate, as typically you may load many modules and the
935 This is deliberate, as typically you may load many modules and the
935 purpose of %who is to show you only what you've manually defined."""
936 purpose of %who is to show you only what you've manually defined."""
936
937
937 varlist = self.magic_who_ls(parameter_s)
938 varlist = self.magic_who_ls(parameter_s)
938 if not varlist:
939 if not varlist:
939 if parameter_s:
940 if parameter_s:
940 print 'No variables match your requested type.'
941 print 'No variables match your requested type.'
941 else:
942 else:
942 print 'Interactive namespace is empty.'
943 print 'Interactive namespace is empty.'
943 return
944 return
944
945
945 # if we have variables, move on...
946 # if we have variables, move on...
946 count = 0
947 count = 0
947 for i in varlist:
948 for i in varlist:
948 print i+'\t',
949 print i+'\t',
949 count += 1
950 count += 1
950 if count > 8:
951 if count > 8:
951 count = 0
952 count = 0
952 print
953 print
953 print
954 print
954
955
955 def magic_whos(self, parameter_s=''):
956 def magic_whos(self, parameter_s=''):
956 """Like %who, but gives some extra information about each variable.
957 """Like %who, but gives some extra information about each variable.
957
958
958 The same type filtering of %who can be applied here.
959 The same type filtering of %who can be applied here.
959
960
960 For all variables, the type is printed. Additionally it prints:
961 For all variables, the type is printed. Additionally it prints:
961
962
962 - For {},[],(): their length.
963 - For {},[],(): their length.
963
964
964 - For numpy and Numeric arrays, a summary with shape, number of
965 - For numpy and Numeric arrays, a summary with shape, number of
965 elements, typecode and size in memory.
966 elements, typecode and size in memory.
966
967
967 - Everything else: a string representation, snipping their middle if
968 - Everything else: a string representation, snipping their middle if
968 too long."""
969 too long."""
969
970
970 varnames = self.magic_who_ls(parameter_s)
971 varnames = self.magic_who_ls(parameter_s)
971 if not varnames:
972 if not varnames:
972 if parameter_s:
973 if parameter_s:
973 print 'No variables match your requested type.'
974 print 'No variables match your requested type.'
974 else:
975 else:
975 print 'Interactive namespace is empty.'
976 print 'Interactive namespace is empty.'
976 return
977 return
977
978
978 # if we have variables, move on...
979 # if we have variables, move on...
979
980
980 # for these types, show len() instead of data:
981 # for these types, show len() instead of data:
981 seq_types = [types.DictType,types.ListType,types.TupleType]
982 seq_types = [types.DictType,types.ListType,types.TupleType]
982
983
983 # for numpy/Numeric arrays, display summary info
984 # for numpy/Numeric arrays, display summary info
984 try:
985 try:
985 import numpy
986 import numpy
986 except ImportError:
987 except ImportError:
987 ndarray_type = None
988 ndarray_type = None
988 else:
989 else:
989 ndarray_type = numpy.ndarray.__name__
990 ndarray_type = numpy.ndarray.__name__
990 try:
991 try:
991 import Numeric
992 import Numeric
992 except ImportError:
993 except ImportError:
993 array_type = None
994 array_type = None
994 else:
995 else:
995 array_type = Numeric.ArrayType.__name__
996 array_type = Numeric.ArrayType.__name__
996
997
997 # Find all variable names and types so we can figure out column sizes
998 # Find all variable names and types so we can figure out column sizes
998 def get_vars(i):
999 def get_vars(i):
999 return self.shell.user_ns[i]
1000 return self.shell.user_ns[i]
1000
1001
1001 # some types are well known and can be shorter
1002 # some types are well known and can be shorter
1002 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
1003 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
1003 def type_name(v):
1004 def type_name(v):
1004 tn = type(v).__name__
1005 tn = type(v).__name__
1005 return abbrevs.get(tn,tn)
1006 return abbrevs.get(tn,tn)
1006
1007
1007 varlist = map(get_vars,varnames)
1008 varlist = map(get_vars,varnames)
1008
1009
1009 typelist = []
1010 typelist = []
1010 for vv in varlist:
1011 for vv in varlist:
1011 tt = type_name(vv)
1012 tt = type_name(vv)
1012
1013
1013 if tt=='instance':
1014 if tt=='instance':
1014 typelist.append( abbrevs.get(str(vv.__class__),
1015 typelist.append( abbrevs.get(str(vv.__class__),
1015 str(vv.__class__)))
1016 str(vv.__class__)))
1016 else:
1017 else:
1017 typelist.append(tt)
1018 typelist.append(tt)
1018
1019
1019 # column labels and # of spaces as separator
1020 # column labels and # of spaces as separator
1020 varlabel = 'Variable'
1021 varlabel = 'Variable'
1021 typelabel = 'Type'
1022 typelabel = 'Type'
1022 datalabel = 'Data/Info'
1023 datalabel = 'Data/Info'
1023 colsep = 3
1024 colsep = 3
1024 # variable format strings
1025 # variable format strings
1025 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1026 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1026 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1027 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1027 aformat = "%s: %s elems, type `%s`, %s bytes"
1028 aformat = "%s: %s elems, type `%s`, %s bytes"
1028 # find the size of the columns to format the output nicely
1029 # find the size of the columns to format the output nicely
1029 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1030 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1030 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1031 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1031 # table header
1032 # table header
1032 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1033 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1033 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1034 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1034 # and the table itself
1035 # and the table itself
1035 kb = 1024
1036 kb = 1024
1036 Mb = 1048576 # kb**2
1037 Mb = 1048576 # kb**2
1037 for vname,var,vtype in zip(varnames,varlist,typelist):
1038 for vname,var,vtype in zip(varnames,varlist,typelist):
1038 print itpl(vformat),
1039 print itpl(vformat),
1039 if vtype in seq_types:
1040 if vtype in seq_types:
1040 print len(var)
1041 print len(var)
1041 elif vtype in [array_type,ndarray_type]:
1042 elif vtype in [array_type,ndarray_type]:
1042 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1043 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1043 if vtype==ndarray_type:
1044 if vtype==ndarray_type:
1044 # numpy
1045 # numpy
1045 vsize = var.size
1046 vsize = var.size
1046 vbytes = vsize*var.itemsize
1047 vbytes = vsize*var.itemsize
1047 vdtype = var.dtype
1048 vdtype = var.dtype
1048 else:
1049 else:
1049 # Numeric
1050 # Numeric
1050 vsize = Numeric.size(var)
1051 vsize = Numeric.size(var)
1051 vbytes = vsize*var.itemsize()
1052 vbytes = vsize*var.itemsize()
1052 vdtype = var.typecode()
1053 vdtype = var.typecode()
1053
1054
1054 if vbytes < 100000:
1055 if vbytes < 100000:
1055 print aformat % (vshape,vsize,vdtype,vbytes)
1056 print aformat % (vshape,vsize,vdtype,vbytes)
1056 else:
1057 else:
1057 print aformat % (vshape,vsize,vdtype,vbytes),
1058 print aformat % (vshape,vsize,vdtype,vbytes),
1058 if vbytes < Mb:
1059 if vbytes < Mb:
1059 print '(%s kb)' % (vbytes/kb,)
1060 print '(%s kb)' % (vbytes/kb,)
1060 else:
1061 else:
1061 print '(%s Mb)' % (vbytes/Mb,)
1062 print '(%s Mb)' % (vbytes/Mb,)
1062 else:
1063 else:
1063 try:
1064 try:
1064 vstr = str(var)
1065 vstr = str(var)
1065 except UnicodeEncodeError:
1066 except UnicodeEncodeError:
1066 vstr = unicode(var).encode(sys.getdefaultencoding(),
1067 vstr = unicode(var).encode(sys.getdefaultencoding(),
1067 'backslashreplace')
1068 'backslashreplace')
1068 vstr = vstr.replace('\n','\\n')
1069 vstr = vstr.replace('\n','\\n')
1069 if len(vstr) < 50:
1070 if len(vstr) < 50:
1070 print vstr
1071 print vstr
1071 else:
1072 else:
1072 printpl(vfmt_short)
1073 printpl(vfmt_short)
1073
1074
1074 def magic_reset(self, parameter_s=''):
1075 def magic_reset(self, parameter_s=''):
1075 """Resets the namespace by removing all names defined by the user.
1076 """Resets the namespace by removing all names defined by the user.
1076
1077
1077 Input/Output history are left around in case you need them.
1078 Input/Output history are left around in case you need them.
1078
1079
1079 Parameters
1080 Parameters
1080 ----------
1081 ----------
1081 -y : force reset without asking for confirmation.
1082 -y : force reset without asking for confirmation.
1082
1083
1083 Examples
1084 Examples
1084 --------
1085 --------
1085 In [6]: a = 1
1086 In [6]: a = 1
1086
1087
1087 In [7]: a
1088 In [7]: a
1088 Out[7]: 1
1089 Out[7]: 1
1089
1090
1090 In [8]: 'a' in _ip.user_ns
1091 In [8]: 'a' in _ip.user_ns
1091 Out[8]: True
1092 Out[8]: True
1092
1093
1093 In [9]: %reset -f
1094 In [9]: %reset -f
1094
1095
1095 In [10]: 'a' in _ip.user_ns
1096 In [10]: 'a' in _ip.user_ns
1096 Out[10]: False
1097 Out[10]: False
1097 """
1098 """
1098
1099
1099 if parameter_s == '-f':
1100 if parameter_s == '-f':
1100 ans = True
1101 ans = True
1101 else:
1102 else:
1102 ans = self.shell.ask_yes_no(
1103 ans = self.shell.ask_yes_no(
1103 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1104 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1104 if not ans:
1105 if not ans:
1105 print 'Nothing done.'
1106 print 'Nothing done.'
1106 return
1107 return
1107 user_ns = self.shell.user_ns
1108 user_ns = self.shell.user_ns
1108 for i in self.magic_who_ls():
1109 for i in self.magic_who_ls():
1109 del(user_ns[i])
1110 del(user_ns[i])
1110
1111
1111 # Also flush the private list of module references kept for script
1112 # Also flush the private list of module references kept for script
1112 # execution protection
1113 # execution protection
1113 self.shell.clear_main_mod_cache()
1114 self.shell.clear_main_mod_cache()
1114
1115
1115 def magic_reset_selective(self, parameter_s=''):
1116 def magic_reset_selective(self, parameter_s=''):
1116 """Resets the namespace by removing names defined by the user.
1117 """Resets the namespace by removing names defined by the user.
1117
1118
1118 Input/Output history are left around in case you need them.
1119 Input/Output history are left around in case you need them.
1119
1120
1120 %reset_selective [-f] regex
1121 %reset_selective [-f] regex
1121
1122
1122 No action is taken if regex is not included
1123 No action is taken if regex is not included
1123
1124
1124 Options
1125 Options
1125 -f : force reset without asking for confirmation.
1126 -f : force reset without asking for confirmation.
1126
1127
1127 Examples
1128 Examples
1128 --------
1129 --------
1129
1130
1130 We first fully reset the namespace so your output looks identical to
1131 We first fully reset the namespace so your output looks identical to
1131 this example for pedagogical reasons; in practice you do not need a
1132 this example for pedagogical reasons; in practice you do not need a
1132 full reset.
1133 full reset.
1133
1134
1134 In [1]: %reset -f
1135 In [1]: %reset -f
1135
1136
1136 Now, with a clean namespace we can make a few variables and use
1137 Now, with a clean namespace we can make a few variables and use
1137 %reset_selective to only delete names that match our regexp:
1138 %reset_selective to only delete names that match our regexp:
1138
1139
1139 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1140 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1140
1141
1141 In [3]: who_ls
1142 In [3]: who_ls
1142 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1143 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1143
1144
1144 In [4]: %reset_selective -f b[2-3]m
1145 In [4]: %reset_selective -f b[2-3]m
1145
1146
1146 In [5]: who_ls
1147 In [5]: who_ls
1147 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1148 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1148
1149
1149 In [6]: %reset_selective -f d
1150 In [6]: %reset_selective -f d
1150
1151
1151 In [7]: who_ls
1152 In [7]: who_ls
1152 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1153 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1153
1154
1154 In [8]: %reset_selective -f c
1155 In [8]: %reset_selective -f c
1155
1156
1156 In [9]: who_ls
1157 In [9]: who_ls
1157 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1158 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1158
1159
1159 In [10]: %reset_selective -f b
1160 In [10]: %reset_selective -f b
1160
1161
1161 In [11]: who_ls
1162 In [11]: who_ls
1162 Out[11]: ['a']
1163 Out[11]: ['a']
1163 """
1164 """
1164
1165
1165 opts, regex = self.parse_options(parameter_s,'f')
1166 opts, regex = self.parse_options(parameter_s,'f')
1166
1167
1167 if opts.has_key('f'):
1168 if opts.has_key('f'):
1168 ans = True
1169 ans = True
1169 else:
1170 else:
1170 ans = self.shell.ask_yes_no(
1171 ans = self.shell.ask_yes_no(
1171 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1172 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1172 if not ans:
1173 if not ans:
1173 print 'Nothing done.'
1174 print 'Nothing done.'
1174 return
1175 return
1175 user_ns = self.shell.user_ns
1176 user_ns = self.shell.user_ns
1176 if not regex:
1177 if not regex:
1177 print 'No regex pattern specified. Nothing done.'
1178 print 'No regex pattern specified. Nothing done.'
1178 return
1179 return
1179 else:
1180 else:
1180 try:
1181 try:
1181 m = re.compile(regex)
1182 m = re.compile(regex)
1182 except TypeError:
1183 except TypeError:
1183 raise TypeError('regex must be a string or compiled pattern')
1184 raise TypeError('regex must be a string or compiled pattern')
1184 for i in self.magic_who_ls():
1185 for i in self.magic_who_ls():
1185 if m.search(i):
1186 if m.search(i):
1186 del(user_ns[i])
1187 del(user_ns[i])
1187
1188
1188 def magic_logstart(self,parameter_s=''):
1189 def magic_logstart(self,parameter_s=''):
1189 """Start logging anywhere in a session.
1190 """Start logging anywhere in a session.
1190
1191
1191 %logstart [-o|-r|-t] [log_name [log_mode]]
1192 %logstart [-o|-r|-t] [log_name [log_mode]]
1192
1193
1193 If no name is given, it defaults to a file named 'ipython_log.py' in your
1194 If no name is given, it defaults to a file named 'ipython_log.py' in your
1194 current directory, in 'rotate' mode (see below).
1195 current directory, in 'rotate' mode (see below).
1195
1196
1196 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1197 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1197 history up to that point and then continues logging.
1198 history up to that point and then continues logging.
1198
1199
1199 %logstart takes a second optional parameter: logging mode. This can be one
1200 %logstart takes a second optional parameter: logging mode. This can be one
1200 of (note that the modes are given unquoted):\\
1201 of (note that the modes are given unquoted):\\
1201 append: well, that says it.\\
1202 append: well, that says it.\\
1202 backup: rename (if exists) to name~ and start name.\\
1203 backup: rename (if exists) to name~ and start name.\\
1203 global: single logfile in your home dir, appended to.\\
1204 global: single logfile in your home dir, appended to.\\
1204 over : overwrite existing log.\\
1205 over : overwrite existing log.\\
1205 rotate: create rotating logs name.1~, name.2~, etc.
1206 rotate: create rotating logs name.1~, name.2~, etc.
1206
1207
1207 Options:
1208 Options:
1208
1209
1209 -o: log also IPython's output. In this mode, all commands which
1210 -o: log also IPython's output. In this mode, all commands which
1210 generate an Out[NN] prompt are recorded to the logfile, right after
1211 generate an Out[NN] prompt are recorded to the logfile, right after
1211 their corresponding input line. The output lines are always
1212 their corresponding input line. The output lines are always
1212 prepended with a '#[Out]# ' marker, so that the log remains valid
1213 prepended with a '#[Out]# ' marker, so that the log remains valid
1213 Python code.
1214 Python code.
1214
1215
1215 Since this marker is always the same, filtering only the output from
1216 Since this marker is always the same, filtering only the output from
1216 a log is very easy, using for example a simple awk call:
1217 a log is very easy, using for example a simple awk call:
1217
1218
1218 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1219 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1219
1220
1220 -r: log 'raw' input. Normally, IPython's logs contain the processed
1221 -r: log 'raw' input. Normally, IPython's logs contain the processed
1221 input, so that user lines are logged in their final form, converted
1222 input, so that user lines are logged in their final form, converted
1222 into valid Python. For example, %Exit is logged as
1223 into valid Python. For example, %Exit is logged as
1223 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1224 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1224 exactly as typed, with no transformations applied.
1225 exactly as typed, with no transformations applied.
1225
1226
1226 -t: put timestamps before each input line logged (these are put in
1227 -t: put timestamps before each input line logged (these are put in
1227 comments)."""
1228 comments)."""
1228
1229
1229 opts,par = self.parse_options(parameter_s,'ort')
1230 opts,par = self.parse_options(parameter_s,'ort')
1230 log_output = 'o' in opts
1231 log_output = 'o' in opts
1231 log_raw_input = 'r' in opts
1232 log_raw_input = 'r' in opts
1232 timestamp = 't' in opts
1233 timestamp = 't' in opts
1233
1234
1234 logger = self.shell.logger
1235 logger = self.shell.logger
1235
1236
1236 # if no args are given, the defaults set in the logger constructor by
1237 # if no args are given, the defaults set in the logger constructor by
1237 # ipytohn remain valid
1238 # ipytohn remain valid
1238 if par:
1239 if par:
1239 try:
1240 try:
1240 logfname,logmode = par.split()
1241 logfname,logmode = par.split()
1241 except:
1242 except:
1242 logfname = par
1243 logfname = par
1243 logmode = 'backup'
1244 logmode = 'backup'
1244 else:
1245 else:
1245 logfname = logger.logfname
1246 logfname = logger.logfname
1246 logmode = logger.logmode
1247 logmode = logger.logmode
1247 # put logfname into rc struct as if it had been called on the command
1248 # put logfname into rc struct as if it had been called on the command
1248 # line, so it ends up saved in the log header Save it in case we need
1249 # line, so it ends up saved in the log header Save it in case we need
1249 # to restore it...
1250 # to restore it...
1250 old_logfile = self.shell.logfile
1251 old_logfile = self.shell.logfile
1251 if logfname:
1252 if logfname:
1252 logfname = os.path.expanduser(logfname)
1253 logfname = os.path.expanduser(logfname)
1253 self.shell.logfile = logfname
1254 self.shell.logfile = logfname
1254
1255
1255 loghead = '# IPython log file\n\n'
1256 loghead = '# IPython log file\n\n'
1256 try:
1257 try:
1257 started = logger.logstart(logfname,loghead,logmode,
1258 started = logger.logstart(logfname,loghead,logmode,
1258 log_output,timestamp,log_raw_input)
1259 log_output,timestamp,log_raw_input)
1259 except:
1260 except:
1260 self.shell.logfile = old_logfile
1261 self.shell.logfile = old_logfile
1261 warn("Couldn't start log: %s" % sys.exc_info()[1])
1262 warn("Couldn't start log: %s" % sys.exc_info()[1])
1262 else:
1263 else:
1263 # log input history up to this point, optionally interleaving
1264 # log input history up to this point, optionally interleaving
1264 # output if requested
1265 # output if requested
1265
1266
1266 if timestamp:
1267 if timestamp:
1267 # disable timestamping for the previous history, since we've
1268 # disable timestamping for the previous history, since we've
1268 # lost those already (no time machine here).
1269 # lost those already (no time machine here).
1269 logger.timestamp = False
1270 logger.timestamp = False
1270
1271
1271 if log_raw_input:
1272 if log_raw_input:
1272 input_hist = self.shell.input_hist_raw
1273 input_hist = self.shell.input_hist_raw
1273 else:
1274 else:
1274 input_hist = self.shell.input_hist
1275 input_hist = self.shell.input_hist
1275
1276
1276 if log_output:
1277 if log_output:
1277 log_write = logger.log_write
1278 log_write = logger.log_write
1278 output_hist = self.shell.output_hist
1279 output_hist = self.shell.output_hist
1279 for n in range(1,len(input_hist)-1):
1280 for n in range(1,len(input_hist)-1):
1280 log_write(input_hist[n].rstrip())
1281 log_write(input_hist[n].rstrip())
1281 if n in output_hist:
1282 if n in output_hist:
1282 log_write(repr(output_hist[n]),'output')
1283 log_write(repr(output_hist[n]),'output')
1283 else:
1284 else:
1284 logger.log_write(input_hist[1:])
1285 logger.log_write(input_hist[1:])
1285 if timestamp:
1286 if timestamp:
1286 # re-enable timestamping
1287 # re-enable timestamping
1287 logger.timestamp = True
1288 logger.timestamp = True
1288
1289
1289 print ('Activating auto-logging. '
1290 print ('Activating auto-logging. '
1290 'Current session state plus future input saved.')
1291 'Current session state plus future input saved.')
1291 logger.logstate()
1292 logger.logstate()
1292
1293
1293 def magic_logstop(self,parameter_s=''):
1294 def magic_logstop(self,parameter_s=''):
1294 """Fully stop logging and close log file.
1295 """Fully stop logging and close log file.
1295
1296
1296 In order to start logging again, a new %logstart call needs to be made,
1297 In order to start logging again, a new %logstart call needs to be made,
1297 possibly (though not necessarily) with a new filename, mode and other
1298 possibly (though not necessarily) with a new filename, mode and other
1298 options."""
1299 options."""
1299 self.logger.logstop()
1300 self.logger.logstop()
1300
1301
1301 def magic_logoff(self,parameter_s=''):
1302 def magic_logoff(self,parameter_s=''):
1302 """Temporarily stop logging.
1303 """Temporarily stop logging.
1303
1304
1304 You must have previously started logging."""
1305 You must have previously started logging."""
1305 self.shell.logger.switch_log(0)
1306 self.shell.logger.switch_log(0)
1306
1307
1307 def magic_logon(self,parameter_s=''):
1308 def magic_logon(self,parameter_s=''):
1308 """Restart logging.
1309 """Restart logging.
1309
1310
1310 This function is for restarting logging which you've temporarily
1311 This function is for restarting logging which you've temporarily
1311 stopped with %logoff. For starting logging for the first time, you
1312 stopped with %logoff. For starting logging for the first time, you
1312 must use the %logstart function, which allows you to specify an
1313 must use the %logstart function, which allows you to specify an
1313 optional log filename."""
1314 optional log filename."""
1314
1315
1315 self.shell.logger.switch_log(1)
1316 self.shell.logger.switch_log(1)
1316
1317
1317 def magic_logstate(self,parameter_s=''):
1318 def magic_logstate(self,parameter_s=''):
1318 """Print the status of the logging system."""
1319 """Print the status of the logging system."""
1319
1320
1320 self.shell.logger.logstate()
1321 self.shell.logger.logstate()
1321
1322
1322 def magic_pdb(self, parameter_s=''):
1323 def magic_pdb(self, parameter_s=''):
1323 """Control the automatic calling of the pdb interactive debugger.
1324 """Control the automatic calling of the pdb interactive debugger.
1324
1325
1325 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1326 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1326 argument it works as a toggle.
1327 argument it works as a toggle.
1327
1328
1328 When an exception is triggered, IPython can optionally call the
1329 When an exception is triggered, IPython can optionally call the
1329 interactive pdb debugger after the traceback printout. %pdb toggles
1330 interactive pdb debugger after the traceback printout. %pdb toggles
1330 this feature on and off.
1331 this feature on and off.
1331
1332
1332 The initial state of this feature is set in your ipythonrc
1333 The initial state of this feature is set in your ipythonrc
1333 configuration file (the variable is called 'pdb').
1334 configuration file (the variable is called 'pdb').
1334
1335
1335 If you want to just activate the debugger AFTER an exception has fired,
1336 If you want to just activate the debugger AFTER an exception has fired,
1336 without having to type '%pdb on' and rerunning your code, you can use
1337 without having to type '%pdb on' and rerunning your code, you can use
1337 the %debug magic."""
1338 the %debug magic."""
1338
1339
1339 par = parameter_s.strip().lower()
1340 par = parameter_s.strip().lower()
1340
1341
1341 if par:
1342 if par:
1342 try:
1343 try:
1343 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1344 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1344 except KeyError:
1345 except KeyError:
1345 print ('Incorrect argument. Use on/1, off/0, '
1346 print ('Incorrect argument. Use on/1, off/0, '
1346 'or nothing for a toggle.')
1347 'or nothing for a toggle.')
1347 return
1348 return
1348 else:
1349 else:
1349 # toggle
1350 # toggle
1350 new_pdb = not self.shell.call_pdb
1351 new_pdb = not self.shell.call_pdb
1351
1352
1352 # set on the shell
1353 # set on the shell
1353 self.shell.call_pdb = new_pdb
1354 self.shell.call_pdb = new_pdb
1354 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1355 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1355
1356
1356 def magic_debug(self, parameter_s=''):
1357 def magic_debug(self, parameter_s=''):
1357 """Activate the interactive debugger in post-mortem mode.
1358 """Activate the interactive debugger in post-mortem mode.
1358
1359
1359 If an exception has just occurred, this lets you inspect its stack
1360 If an exception has just occurred, this lets you inspect its stack
1360 frames interactively. Note that this will always work only on the last
1361 frames interactively. Note that this will always work only on the last
1361 traceback that occurred, so you must call this quickly after an
1362 traceback that occurred, so you must call this quickly after an
1362 exception that you wish to inspect has fired, because if another one
1363 exception that you wish to inspect has fired, because if another one
1363 occurs, it clobbers the previous one.
1364 occurs, it clobbers the previous one.
1364
1365
1365 If you want IPython to automatically do this on every exception, see
1366 If you want IPython to automatically do this on every exception, see
1366 the %pdb magic for more details.
1367 the %pdb magic for more details.
1367 """
1368 """
1368 self.shell.debugger(force=True)
1369 self.shell.debugger(force=True)
1369
1370
1370 @testdec.skip_doctest
1371 @testdec.skip_doctest
1371 def magic_prun(self, parameter_s ='',user_mode=1,
1372 def magic_prun(self, parameter_s ='',user_mode=1,
1372 opts=None,arg_lst=None,prog_ns=None):
1373 opts=None,arg_lst=None,prog_ns=None):
1373
1374
1374 """Run a statement through the python code profiler.
1375 """Run a statement through the python code profiler.
1375
1376
1376 Usage:
1377 Usage:
1377 %prun [options] statement
1378 %prun [options] statement
1378
1379
1379 The given statement (which doesn't require quote marks) is run via the
1380 The given statement (which doesn't require quote marks) is run via the
1380 python profiler in a manner similar to the profile.run() function.
1381 python profiler in a manner similar to the profile.run() function.
1381 Namespaces are internally managed to work correctly; profile.run
1382 Namespaces are internally managed to work correctly; profile.run
1382 cannot be used in IPython because it makes certain assumptions about
1383 cannot be used in IPython because it makes certain assumptions about
1383 namespaces which do not hold under IPython.
1384 namespaces which do not hold under IPython.
1384
1385
1385 Options:
1386 Options:
1386
1387
1387 -l <limit>: you can place restrictions on what or how much of the
1388 -l <limit>: you can place restrictions on what or how much of the
1388 profile gets printed. The limit value can be:
1389 profile gets printed. The limit value can be:
1389
1390
1390 * A string: only information for function names containing this string
1391 * A string: only information for function names containing this string
1391 is printed.
1392 is printed.
1392
1393
1393 * An integer: only these many lines are printed.
1394 * An integer: only these many lines are printed.
1394
1395
1395 * A float (between 0 and 1): this fraction of the report is printed
1396 * A float (between 0 and 1): this fraction of the report is printed
1396 (for example, use a limit of 0.4 to see the topmost 40% only).
1397 (for example, use a limit of 0.4 to see the topmost 40% only).
1397
1398
1398 You can combine several limits with repeated use of the option. For
1399 You can combine several limits with repeated use of the option. For
1399 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1400 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1400 information about class constructors.
1401 information about class constructors.
1401
1402
1402 -r: return the pstats.Stats object generated by the profiling. This
1403 -r: return the pstats.Stats object generated by the profiling. This
1403 object has all the information about the profile in it, and you can
1404 object has all the information about the profile in it, and you can
1404 later use it for further analysis or in other functions.
1405 later use it for further analysis or in other functions.
1405
1406
1406 -s <key>: sort profile by given key. You can provide more than one key
1407 -s <key>: sort profile by given key. You can provide more than one key
1407 by using the option several times: '-s key1 -s key2 -s key3...'. The
1408 by using the option several times: '-s key1 -s key2 -s key3...'. The
1408 default sorting key is 'time'.
1409 default sorting key is 'time'.
1409
1410
1410 The following is copied verbatim from the profile documentation
1411 The following is copied verbatim from the profile documentation
1411 referenced below:
1412 referenced below:
1412
1413
1413 When more than one key is provided, additional keys are used as
1414 When more than one key is provided, additional keys are used as
1414 secondary criteria when the there is equality in all keys selected
1415 secondary criteria when the there is equality in all keys selected
1415 before them.
1416 before them.
1416
1417
1417 Abbreviations can be used for any key names, as long as the
1418 Abbreviations can be used for any key names, as long as the
1418 abbreviation is unambiguous. The following are the keys currently
1419 abbreviation is unambiguous. The following are the keys currently
1419 defined:
1420 defined:
1420
1421
1421 Valid Arg Meaning
1422 Valid Arg Meaning
1422 "calls" call count
1423 "calls" call count
1423 "cumulative" cumulative time
1424 "cumulative" cumulative time
1424 "file" file name
1425 "file" file name
1425 "module" file name
1426 "module" file name
1426 "pcalls" primitive call count
1427 "pcalls" primitive call count
1427 "line" line number
1428 "line" line number
1428 "name" function name
1429 "name" function name
1429 "nfl" name/file/line
1430 "nfl" name/file/line
1430 "stdname" standard name
1431 "stdname" standard name
1431 "time" internal time
1432 "time" internal time
1432
1433
1433 Note that all sorts on statistics are in descending order (placing
1434 Note that all sorts on statistics are in descending order (placing
1434 most time consuming items first), where as name, file, and line number
1435 most time consuming items first), where as name, file, and line number
1435 searches are in ascending order (i.e., alphabetical). The subtle
1436 searches are in ascending order (i.e., alphabetical). The subtle
1436 distinction between "nfl" and "stdname" is that the standard name is a
1437 distinction between "nfl" and "stdname" is that the standard name is a
1437 sort of the name as printed, which means that the embedded line
1438 sort of the name as printed, which means that the embedded line
1438 numbers get compared in an odd way. For example, lines 3, 20, and 40
1439 numbers get compared in an odd way. For example, lines 3, 20, and 40
1439 would (if the file names were the same) appear in the string order
1440 would (if the file names were the same) appear in the string order
1440 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1441 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1441 line numbers. In fact, sort_stats("nfl") is the same as
1442 line numbers. In fact, sort_stats("nfl") is the same as
1442 sort_stats("name", "file", "line").
1443 sort_stats("name", "file", "line").
1443
1444
1444 -T <filename>: save profile results as shown on screen to a text
1445 -T <filename>: save profile results as shown on screen to a text
1445 file. The profile is still shown on screen.
1446 file. The profile is still shown on screen.
1446
1447
1447 -D <filename>: save (via dump_stats) profile statistics to given
1448 -D <filename>: save (via dump_stats) profile statistics to given
1448 filename. This data is in a format understod by the pstats module, and
1449 filename. This data is in a format understod by the pstats module, and
1449 is generated by a call to the dump_stats() method of profile
1450 is generated by a call to the dump_stats() method of profile
1450 objects. The profile is still shown on screen.
1451 objects. The profile is still shown on screen.
1451
1452
1452 If you want to run complete programs under the profiler's control, use
1453 If you want to run complete programs under the profiler's control, use
1453 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1454 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1454 contains profiler specific options as described here.
1455 contains profiler specific options as described here.
1455
1456
1456 You can read the complete documentation for the profile module with::
1457 You can read the complete documentation for the profile module with::
1457
1458
1458 In [1]: import profile; profile.help()
1459 In [1]: import profile; profile.help()
1459 """
1460 """
1460
1461
1461 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1462 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1462 # protect user quote marks
1463 # protect user quote marks
1463 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1464 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1464
1465
1465 if user_mode: # regular user call
1466 if user_mode: # regular user call
1466 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1467 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1467 list_all=1)
1468 list_all=1)
1468 namespace = self.shell.user_ns
1469 namespace = self.shell.user_ns
1469 else: # called to run a program by %run -p
1470 else: # called to run a program by %run -p
1470 try:
1471 try:
1471 filename = get_py_filename(arg_lst[0])
1472 filename = get_py_filename(arg_lst[0])
1472 except IOError,msg:
1473 except IOError,msg:
1473 error(msg)
1474 error(msg)
1474 return
1475 return
1475
1476
1476 arg_str = 'execfile(filename,prog_ns)'
1477 arg_str = 'execfile(filename,prog_ns)'
1477 namespace = locals()
1478 namespace = locals()
1478
1479
1479 opts.merge(opts_def)
1480 opts.merge(opts_def)
1480
1481
1481 prof = profile.Profile()
1482 prof = profile.Profile()
1482 try:
1483 try:
1483 prof = prof.runctx(arg_str,namespace,namespace)
1484 prof = prof.runctx(arg_str,namespace,namespace)
1484 sys_exit = ''
1485 sys_exit = ''
1485 except SystemExit:
1486 except SystemExit:
1486 sys_exit = """*** SystemExit exception caught in code being profiled."""
1487 sys_exit = """*** SystemExit exception caught in code being profiled."""
1487
1488
1488 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1489 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1489
1490
1490 lims = opts.l
1491 lims = opts.l
1491 if lims:
1492 if lims:
1492 lims = [] # rebuild lims with ints/floats/strings
1493 lims = [] # rebuild lims with ints/floats/strings
1493 for lim in opts.l:
1494 for lim in opts.l:
1494 try:
1495 try:
1495 lims.append(int(lim))
1496 lims.append(int(lim))
1496 except ValueError:
1497 except ValueError:
1497 try:
1498 try:
1498 lims.append(float(lim))
1499 lims.append(float(lim))
1499 except ValueError:
1500 except ValueError:
1500 lims.append(lim)
1501 lims.append(lim)
1501
1502
1502 # Trap output.
1503 # Trap output.
1503 stdout_trap = StringIO()
1504 stdout_trap = StringIO()
1504
1505
1505 if hasattr(stats,'stream'):
1506 if hasattr(stats,'stream'):
1506 # In newer versions of python, the stats object has a 'stream'
1507 # In newer versions of python, the stats object has a 'stream'
1507 # attribute to write into.
1508 # attribute to write into.
1508 stats.stream = stdout_trap
1509 stats.stream = stdout_trap
1509 stats.print_stats(*lims)
1510 stats.print_stats(*lims)
1510 else:
1511 else:
1511 # For older versions, we manually redirect stdout during printing
1512 # For older versions, we manually redirect stdout during printing
1512 sys_stdout = sys.stdout
1513 sys_stdout = sys.stdout
1513 try:
1514 try:
1514 sys.stdout = stdout_trap
1515 sys.stdout = stdout_trap
1515 stats.print_stats(*lims)
1516 stats.print_stats(*lims)
1516 finally:
1517 finally:
1517 sys.stdout = sys_stdout
1518 sys.stdout = sys_stdout
1518
1519
1519 output = stdout_trap.getvalue()
1520 output = stdout_trap.getvalue()
1520 output = output.rstrip()
1521 output = output.rstrip()
1521
1522
1522 page(output,screen_lines=self.shell.usable_screen_length)
1523 page(output,screen_lines=self.shell.usable_screen_length)
1523 print sys_exit,
1524 print sys_exit,
1524
1525
1525 dump_file = opts.D[0]
1526 dump_file = opts.D[0]
1526 text_file = opts.T[0]
1527 text_file = opts.T[0]
1527 if dump_file:
1528 if dump_file:
1528 prof.dump_stats(dump_file)
1529 prof.dump_stats(dump_file)
1529 print '\n*** Profile stats marshalled to file',\
1530 print '\n*** Profile stats marshalled to file',\
1530 `dump_file`+'.',sys_exit
1531 `dump_file`+'.',sys_exit
1531 if text_file:
1532 if text_file:
1532 pfile = file(text_file,'w')
1533 pfile = file(text_file,'w')
1533 pfile.write(output)
1534 pfile.write(output)
1534 pfile.close()
1535 pfile.close()
1535 print '\n*** Profile printout saved to text file',\
1536 print '\n*** Profile printout saved to text file',\
1536 `text_file`+'.',sys_exit
1537 `text_file`+'.',sys_exit
1537
1538
1538 if opts.has_key('r'):
1539 if opts.has_key('r'):
1539 return stats
1540 return stats
1540 else:
1541 else:
1541 return None
1542 return None
1542
1543
1543 @testdec.skip_doctest
1544 @testdec.skip_doctest
1544 def magic_run(self, parameter_s ='',runner=None,
1545 def magic_run(self, parameter_s ='',runner=None,
1545 file_finder=get_py_filename):
1546 file_finder=get_py_filename):
1546 """Run the named file inside IPython as a program.
1547 """Run the named file inside IPython as a program.
1547
1548
1548 Usage:\\
1549 Usage:\\
1549 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1550 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1550
1551
1551 Parameters after the filename are passed as command-line arguments to
1552 Parameters after the filename are passed as command-line arguments to
1552 the program (put in sys.argv). Then, control returns to IPython's
1553 the program (put in sys.argv). Then, control returns to IPython's
1553 prompt.
1554 prompt.
1554
1555
1555 This is similar to running at a system prompt:\\
1556 This is similar to running at a system prompt:\\
1556 $ python file args\\
1557 $ python file args\\
1557 but with the advantage of giving you IPython's tracebacks, and of
1558 but with the advantage of giving you IPython's tracebacks, and of
1558 loading all variables into your interactive namespace for further use
1559 loading all variables into your interactive namespace for further use
1559 (unless -p is used, see below).
1560 (unless -p is used, see below).
1560
1561
1561 The file is executed in a namespace initially consisting only of
1562 The file is executed in a namespace initially consisting only of
1562 __name__=='__main__' and sys.argv constructed as indicated. It thus
1563 __name__=='__main__' and sys.argv constructed as indicated. It thus
1563 sees its environment as if it were being run as a stand-alone program
1564 sees its environment as if it were being run as a stand-alone program
1564 (except for sharing global objects such as previously imported
1565 (except for sharing global objects such as previously imported
1565 modules). But after execution, the IPython interactive namespace gets
1566 modules). But after execution, the IPython interactive namespace gets
1566 updated with all variables defined in the program (except for __name__
1567 updated with all variables defined in the program (except for __name__
1567 and sys.argv). This allows for very convenient loading of code for
1568 and sys.argv). This allows for very convenient loading of code for
1568 interactive work, while giving each program a 'clean sheet' to run in.
1569 interactive work, while giving each program a 'clean sheet' to run in.
1569
1570
1570 Options:
1571 Options:
1571
1572
1572 -n: __name__ is NOT set to '__main__', but to the running file's name
1573 -n: __name__ is NOT set to '__main__', but to the running file's name
1573 without extension (as python does under import). This allows running
1574 without extension (as python does under import). This allows running
1574 scripts and reloading the definitions in them without calling code
1575 scripts and reloading the definitions in them without calling code
1575 protected by an ' if __name__ == "__main__" ' clause.
1576 protected by an ' if __name__ == "__main__" ' clause.
1576
1577
1577 -i: run the file in IPython's namespace instead of an empty one. This
1578 -i: run the file in IPython's namespace instead of an empty one. This
1578 is useful if you are experimenting with code written in a text editor
1579 is useful if you are experimenting with code written in a text editor
1579 which depends on variables defined interactively.
1580 which depends on variables defined interactively.
1580
1581
1581 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1582 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1582 being run. This is particularly useful if IPython is being used to
1583 being run. This is particularly useful if IPython is being used to
1583 run unittests, which always exit with a sys.exit() call. In such
1584 run unittests, which always exit with a sys.exit() call. In such
1584 cases you are interested in the output of the test results, not in
1585 cases you are interested in the output of the test results, not in
1585 seeing a traceback of the unittest module.
1586 seeing a traceback of the unittest module.
1586
1587
1587 -t: print timing information at the end of the run. IPython will give
1588 -t: print timing information at the end of the run. IPython will give
1588 you an estimated CPU time consumption for your script, which under
1589 you an estimated CPU time consumption for your script, which under
1589 Unix uses the resource module to avoid the wraparound problems of
1590 Unix uses the resource module to avoid the wraparound problems of
1590 time.clock(). Under Unix, an estimate of time spent on system tasks
1591 time.clock(). Under Unix, an estimate of time spent on system tasks
1591 is also given (for Windows platforms this is reported as 0.0).
1592 is also given (for Windows platforms this is reported as 0.0).
1592
1593
1593 If -t is given, an additional -N<N> option can be given, where <N>
1594 If -t is given, an additional -N<N> option can be given, where <N>
1594 must be an integer indicating how many times you want the script to
1595 must be an integer indicating how many times you want the script to
1595 run. The final timing report will include total and per run results.
1596 run. The final timing report will include total and per run results.
1596
1597
1597 For example (testing the script uniq_stable.py):
1598 For example (testing the script uniq_stable.py):
1598
1599
1599 In [1]: run -t uniq_stable
1600 In [1]: run -t uniq_stable
1600
1601
1601 IPython CPU timings (estimated):\\
1602 IPython CPU timings (estimated):\\
1602 User : 0.19597 s.\\
1603 User : 0.19597 s.\\
1603 System: 0.0 s.\\
1604 System: 0.0 s.\\
1604
1605
1605 In [2]: run -t -N5 uniq_stable
1606 In [2]: run -t -N5 uniq_stable
1606
1607
1607 IPython CPU timings (estimated):\\
1608 IPython CPU timings (estimated):\\
1608 Total runs performed: 5\\
1609 Total runs performed: 5\\
1609 Times : Total Per run\\
1610 Times : Total Per run\\
1610 User : 0.910862 s, 0.1821724 s.\\
1611 User : 0.910862 s, 0.1821724 s.\\
1611 System: 0.0 s, 0.0 s.
1612 System: 0.0 s, 0.0 s.
1612
1613
1613 -d: run your program under the control of pdb, the Python debugger.
1614 -d: run your program under the control of pdb, the Python debugger.
1614 This allows you to execute your program step by step, watch variables,
1615 This allows you to execute your program step by step, watch variables,
1615 etc. Internally, what IPython does is similar to calling:
1616 etc. Internally, what IPython does is similar to calling:
1616
1617
1617 pdb.run('execfile("YOURFILENAME")')
1618 pdb.run('execfile("YOURFILENAME")')
1618
1619
1619 with a breakpoint set on line 1 of your file. You can change the line
1620 with a breakpoint set on line 1 of your file. You can change the line
1620 number for this automatic breakpoint to be <N> by using the -bN option
1621 number for this automatic breakpoint to be <N> by using the -bN option
1621 (where N must be an integer). For example:
1622 (where N must be an integer). For example:
1622
1623
1623 %run -d -b40 myscript
1624 %run -d -b40 myscript
1624
1625
1625 will set the first breakpoint at line 40 in myscript.py. Note that
1626 will set the first breakpoint at line 40 in myscript.py. Note that
1626 the first breakpoint must be set on a line which actually does
1627 the first breakpoint must be set on a line which actually does
1627 something (not a comment or docstring) for it to stop execution.
1628 something (not a comment or docstring) for it to stop execution.
1628
1629
1629 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1630 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1630 first enter 'c' (without qoutes) to start execution up to the first
1631 first enter 'c' (without qoutes) to start execution up to the first
1631 breakpoint.
1632 breakpoint.
1632
1633
1633 Entering 'help' gives information about the use of the debugger. You
1634 Entering 'help' gives information about the use of the debugger. You
1634 can easily see pdb's full documentation with "import pdb;pdb.help()"
1635 can easily see pdb's full documentation with "import pdb;pdb.help()"
1635 at a prompt.
1636 at a prompt.
1636
1637
1637 -p: run program under the control of the Python profiler module (which
1638 -p: run program under the control of the Python profiler module (which
1638 prints a detailed report of execution times, function calls, etc).
1639 prints a detailed report of execution times, function calls, etc).
1639
1640
1640 You can pass other options after -p which affect the behavior of the
1641 You can pass other options after -p which affect the behavior of the
1641 profiler itself. See the docs for %prun for details.
1642 profiler itself. See the docs for %prun for details.
1642
1643
1643 In this mode, the program's variables do NOT propagate back to the
1644 In this mode, the program's variables do NOT propagate back to the
1644 IPython interactive namespace (because they remain in the namespace
1645 IPython interactive namespace (because they remain in the namespace
1645 where the profiler executes them).
1646 where the profiler executes them).
1646
1647
1647 Internally this triggers a call to %prun, see its documentation for
1648 Internally this triggers a call to %prun, see its documentation for
1648 details on the options available specifically for profiling.
1649 details on the options available specifically for profiling.
1649
1650
1650 There is one special usage for which the text above doesn't apply:
1651 There is one special usage for which the text above doesn't apply:
1651 if the filename ends with .ipy, the file is run as ipython script,
1652 if the filename ends with .ipy, the file is run as ipython script,
1652 just as if the commands were written on IPython prompt.
1653 just as if the commands were written on IPython prompt.
1653 """
1654 """
1654
1655
1655 # get arguments and set sys.argv for program to be run.
1656 # get arguments and set sys.argv for program to be run.
1656 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1657 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1657 mode='list',list_all=1)
1658 mode='list',list_all=1)
1658
1659
1659 try:
1660 try:
1660 filename = file_finder(arg_lst[0])
1661 filename = file_finder(arg_lst[0])
1661 except IndexError:
1662 except IndexError:
1662 warn('you must provide at least a filename.')
1663 warn('you must provide at least a filename.')
1663 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1664 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1664 return
1665 return
1665 except IOError,msg:
1666 except IOError,msg:
1666 error(msg)
1667 error(msg)
1667 return
1668 return
1668
1669
1669 if filename.lower().endswith('.ipy'):
1670 if filename.lower().endswith('.ipy'):
1670 self.shell.safe_execfile_ipy(filename)
1671 self.shell.safe_execfile_ipy(filename)
1671 return
1672 return
1672
1673
1673 # Control the response to exit() calls made by the script being run
1674 # Control the response to exit() calls made by the script being run
1674 exit_ignore = opts.has_key('e')
1675 exit_ignore = opts.has_key('e')
1675
1676
1676 # Make sure that the running script gets a proper sys.argv as if it
1677 # Make sure that the running script gets a proper sys.argv as if it
1677 # were run from a system shell.
1678 # were run from a system shell.
1678 save_argv = sys.argv # save it for later restoring
1679 save_argv = sys.argv # save it for later restoring
1679 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1680 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1680
1681
1681 if opts.has_key('i'):
1682 if opts.has_key('i'):
1682 # Run in user's interactive namespace
1683 # Run in user's interactive namespace
1683 prog_ns = self.shell.user_ns
1684 prog_ns = self.shell.user_ns
1684 __name__save = self.shell.user_ns['__name__']
1685 __name__save = self.shell.user_ns['__name__']
1685 prog_ns['__name__'] = '__main__'
1686 prog_ns['__name__'] = '__main__'
1686 main_mod = self.shell.new_main_mod(prog_ns)
1687 main_mod = self.shell.new_main_mod(prog_ns)
1687 else:
1688 else:
1688 # Run in a fresh, empty namespace
1689 # Run in a fresh, empty namespace
1689 if opts.has_key('n'):
1690 if opts.has_key('n'):
1690 name = os.path.splitext(os.path.basename(filename))[0]
1691 name = os.path.splitext(os.path.basename(filename))[0]
1691 else:
1692 else:
1692 name = '__main__'
1693 name = '__main__'
1693
1694
1694 main_mod = self.shell.new_main_mod()
1695 main_mod = self.shell.new_main_mod()
1695 prog_ns = main_mod.__dict__
1696 prog_ns = main_mod.__dict__
1696 prog_ns['__name__'] = name
1697 prog_ns['__name__'] = name
1697
1698
1698 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1699 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1699 # set the __file__ global in the script's namespace
1700 # set the __file__ global in the script's namespace
1700 prog_ns['__file__'] = filename
1701 prog_ns['__file__'] = filename
1701
1702
1702 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1703 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1703 # that, if we overwrite __main__, we replace it at the end
1704 # that, if we overwrite __main__, we replace it at the end
1704 main_mod_name = prog_ns['__name__']
1705 main_mod_name = prog_ns['__name__']
1705
1706
1706 if main_mod_name == '__main__':
1707 if main_mod_name == '__main__':
1707 restore_main = sys.modules['__main__']
1708 restore_main = sys.modules['__main__']
1708 else:
1709 else:
1709 restore_main = False
1710 restore_main = False
1710
1711
1711 # This needs to be undone at the end to prevent holding references to
1712 # This needs to be undone at the end to prevent holding references to
1712 # every single object ever created.
1713 # every single object ever created.
1713 sys.modules[main_mod_name] = main_mod
1714 sys.modules[main_mod_name] = main_mod
1714
1715
1715 stats = None
1716 stats = None
1716 try:
1717 try:
1717 self.shell.savehist()
1718 self.shell.savehist()
1718
1719
1719 if opts.has_key('p'):
1720 if opts.has_key('p'):
1720 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1721 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1721 else:
1722 else:
1722 if opts.has_key('d'):
1723 if opts.has_key('d'):
1723 deb = debugger.Pdb(self.shell.colors)
1724 deb = debugger.Pdb(self.shell.colors)
1724 # reset Breakpoint state, which is moronically kept
1725 # reset Breakpoint state, which is moronically kept
1725 # in a class
1726 # in a class
1726 bdb.Breakpoint.next = 1
1727 bdb.Breakpoint.next = 1
1727 bdb.Breakpoint.bplist = {}
1728 bdb.Breakpoint.bplist = {}
1728 bdb.Breakpoint.bpbynumber = [None]
1729 bdb.Breakpoint.bpbynumber = [None]
1729 # Set an initial breakpoint to stop execution
1730 # Set an initial breakpoint to stop execution
1730 maxtries = 10
1731 maxtries = 10
1731 bp = int(opts.get('b',[1])[0])
1732 bp = int(opts.get('b',[1])[0])
1732 checkline = deb.checkline(filename,bp)
1733 checkline = deb.checkline(filename,bp)
1733 if not checkline:
1734 if not checkline:
1734 for bp in range(bp+1,bp+maxtries+1):
1735 for bp in range(bp+1,bp+maxtries+1):
1735 if deb.checkline(filename,bp):
1736 if deb.checkline(filename,bp):
1736 break
1737 break
1737 else:
1738 else:
1738 msg = ("\nI failed to find a valid line to set "
1739 msg = ("\nI failed to find a valid line to set "
1739 "a breakpoint\n"
1740 "a breakpoint\n"
1740 "after trying up to line: %s.\n"
1741 "after trying up to line: %s.\n"
1741 "Please set a valid breakpoint manually "
1742 "Please set a valid breakpoint manually "
1742 "with the -b option." % bp)
1743 "with the -b option." % bp)
1743 error(msg)
1744 error(msg)
1744 return
1745 return
1745 # if we find a good linenumber, set the breakpoint
1746 # if we find a good linenumber, set the breakpoint
1746 deb.do_break('%s:%s' % (filename,bp))
1747 deb.do_break('%s:%s' % (filename,bp))
1747 # Start file run
1748 # Start file run
1748 print "NOTE: Enter 'c' at the",
1749 print "NOTE: Enter 'c' at the",
1749 print "%s prompt to start your script." % deb.prompt
1750 print "%s prompt to start your script." % deb.prompt
1750 try:
1751 try:
1751 deb.run('execfile("%s")' % filename,prog_ns)
1752 deb.run('execfile("%s")' % filename,prog_ns)
1752
1753
1753 except:
1754 except:
1754 etype, value, tb = sys.exc_info()
1755 etype, value, tb = sys.exc_info()
1755 # Skip three frames in the traceback: the %run one,
1756 # Skip three frames in the traceback: the %run one,
1756 # one inside bdb.py, and the command-line typed by the
1757 # one inside bdb.py, and the command-line typed by the
1757 # user (run by exec in pdb itself).
1758 # user (run by exec in pdb itself).
1758 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1759 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1759 else:
1760 else:
1760 if runner is None:
1761 if runner is None:
1761 runner = self.shell.safe_execfile
1762 runner = self.shell.safe_execfile
1762 if opts.has_key('t'):
1763 if opts.has_key('t'):
1763 # timed execution
1764 # timed execution
1764 try:
1765 try:
1765 nruns = int(opts['N'][0])
1766 nruns = int(opts['N'][0])
1766 if nruns < 1:
1767 if nruns < 1:
1767 error('Number of runs must be >=1')
1768 error('Number of runs must be >=1')
1768 return
1769 return
1769 except (KeyError):
1770 except (KeyError):
1770 nruns = 1
1771 nruns = 1
1771 if nruns == 1:
1772 if nruns == 1:
1772 t0 = clock2()
1773 t0 = clock2()
1773 runner(filename,prog_ns,prog_ns,
1774 runner(filename,prog_ns,prog_ns,
1774 exit_ignore=exit_ignore)
1775 exit_ignore=exit_ignore)
1775 t1 = clock2()
1776 t1 = clock2()
1776 t_usr = t1[0]-t0[0]
1777 t_usr = t1[0]-t0[0]
1777 t_sys = t1[1]-t0[1]
1778 t_sys = t1[1]-t0[1]
1778 print "\nIPython CPU timings (estimated):"
1779 print "\nIPython CPU timings (estimated):"
1779 print " User : %10s s." % t_usr
1780 print " User : %10s s." % t_usr
1780 print " System: %10s s." % t_sys
1781 print " System: %10s s." % t_sys
1781 else:
1782 else:
1782 runs = range(nruns)
1783 runs = range(nruns)
1783 t0 = clock2()
1784 t0 = clock2()
1784 for nr in runs:
1785 for nr in runs:
1785 runner(filename,prog_ns,prog_ns,
1786 runner(filename,prog_ns,prog_ns,
1786 exit_ignore=exit_ignore)
1787 exit_ignore=exit_ignore)
1787 t1 = clock2()
1788 t1 = clock2()
1788 t_usr = t1[0]-t0[0]
1789 t_usr = t1[0]-t0[0]
1789 t_sys = t1[1]-t0[1]
1790 t_sys = t1[1]-t0[1]
1790 print "\nIPython CPU timings (estimated):"
1791 print "\nIPython CPU timings (estimated):"
1791 print "Total runs performed:",nruns
1792 print "Total runs performed:",nruns
1792 print " Times : %10s %10s" % ('Total','Per run')
1793 print " Times : %10s %10s" % ('Total','Per run')
1793 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1794 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1794 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1795 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1795
1796
1796 else:
1797 else:
1797 # regular execution
1798 # regular execution
1798 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1799 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1799
1800
1800 if opts.has_key('i'):
1801 if opts.has_key('i'):
1801 self.shell.user_ns['__name__'] = __name__save
1802 self.shell.user_ns['__name__'] = __name__save
1802 else:
1803 else:
1803 # The shell MUST hold a reference to prog_ns so after %run
1804 # The shell MUST hold a reference to prog_ns so after %run
1804 # exits, the python deletion mechanism doesn't zero it out
1805 # exits, the python deletion mechanism doesn't zero it out
1805 # (leaving dangling references).
1806 # (leaving dangling references).
1806 self.shell.cache_main_mod(prog_ns,filename)
1807 self.shell.cache_main_mod(prog_ns,filename)
1807 # update IPython interactive namespace
1808 # update IPython interactive namespace
1808
1809
1809 # Some forms of read errors on the file may mean the
1810 # Some forms of read errors on the file may mean the
1810 # __name__ key was never set; using pop we don't have to
1811 # __name__ key was never set; using pop we don't have to
1811 # worry about a possible KeyError.
1812 # worry about a possible KeyError.
1812 prog_ns.pop('__name__', None)
1813 prog_ns.pop('__name__', None)
1813
1814
1814 self.shell.user_ns.update(prog_ns)
1815 self.shell.user_ns.update(prog_ns)
1815 finally:
1816 finally:
1816 # It's a bit of a mystery why, but __builtins__ can change from
1817 # It's a bit of a mystery why, but __builtins__ can change from
1817 # being a module to becoming a dict missing some key data after
1818 # being a module to becoming a dict missing some key data after
1818 # %run. As best I can see, this is NOT something IPython is doing
1819 # %run. As best I can see, this is NOT something IPython is doing
1819 # at all, and similar problems have been reported before:
1820 # at all, and similar problems have been reported before:
1820 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1821 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1821 # Since this seems to be done by the interpreter itself, the best
1822 # Since this seems to be done by the interpreter itself, the best
1822 # we can do is to at least restore __builtins__ for the user on
1823 # we can do is to at least restore __builtins__ for the user on
1823 # exit.
1824 # exit.
1824 self.shell.user_ns['__builtins__'] = __builtin__
1825 self.shell.user_ns['__builtins__'] = __builtin__
1825
1826
1826 # Ensure key global structures are restored
1827 # Ensure key global structures are restored
1827 sys.argv = save_argv
1828 sys.argv = save_argv
1828 if restore_main:
1829 if restore_main:
1829 sys.modules['__main__'] = restore_main
1830 sys.modules['__main__'] = restore_main
1830 else:
1831 else:
1831 # Remove from sys.modules the reference to main_mod we'd
1832 # Remove from sys.modules the reference to main_mod we'd
1832 # added. Otherwise it will trap references to objects
1833 # added. Otherwise it will trap references to objects
1833 # contained therein.
1834 # contained therein.
1834 del sys.modules[main_mod_name]
1835 del sys.modules[main_mod_name]
1835
1836
1836 self.shell.reloadhist()
1837 self.shell.reloadhist()
1837
1838
1838 return stats
1839 return stats
1839
1840
1840 @testdec.skip_doctest
1841 @testdec.skip_doctest
1841 def magic_timeit(self, parameter_s =''):
1842 def magic_timeit(self, parameter_s =''):
1842 """Time execution of a Python statement or expression
1843 """Time execution of a Python statement or expression
1843
1844
1844 Usage:\\
1845 Usage:\\
1845 %timeit [-n<N> -r<R> [-t|-c]] statement
1846 %timeit [-n<N> -r<R> [-t|-c]] statement
1846
1847
1847 Time execution of a Python statement or expression using the timeit
1848 Time execution of a Python statement or expression using the timeit
1848 module.
1849 module.
1849
1850
1850 Options:
1851 Options:
1851 -n<N>: execute the given statement <N> times in a loop. If this value
1852 -n<N>: execute the given statement <N> times in a loop. If this value
1852 is not given, a fitting value is chosen.
1853 is not given, a fitting value is chosen.
1853
1854
1854 -r<R>: repeat the loop iteration <R> times and take the best result.
1855 -r<R>: repeat the loop iteration <R> times and take the best result.
1855 Default: 3
1856 Default: 3
1856
1857
1857 -t: use time.time to measure the time, which is the default on Unix.
1858 -t: use time.time to measure the time, which is the default on Unix.
1858 This function measures wall time.
1859 This function measures wall time.
1859
1860
1860 -c: use time.clock to measure the time, which is the default on
1861 -c: use time.clock to measure the time, which is the default on
1861 Windows and measures wall time. On Unix, resource.getrusage is used
1862 Windows and measures wall time. On Unix, resource.getrusage is used
1862 instead and returns the CPU user time.
1863 instead and returns the CPU user time.
1863
1864
1864 -p<P>: use a precision of <P> digits to display the timing result.
1865 -p<P>: use a precision of <P> digits to display the timing result.
1865 Default: 3
1866 Default: 3
1866
1867
1867
1868
1868 Examples:
1869 Examples:
1869
1870
1870 In [1]: %timeit pass
1871 In [1]: %timeit pass
1871 10000000 loops, best of 3: 53.3 ns per loop
1872 10000000 loops, best of 3: 53.3 ns per loop
1872
1873
1873 In [2]: u = None
1874 In [2]: u = None
1874
1875
1875 In [3]: %timeit u is None
1876 In [3]: %timeit u is None
1876 10000000 loops, best of 3: 184 ns per loop
1877 10000000 loops, best of 3: 184 ns per loop
1877
1878
1878 In [4]: %timeit -r 4 u == None
1879 In [4]: %timeit -r 4 u == None
1879 1000000 loops, best of 4: 242 ns per loop
1880 1000000 loops, best of 4: 242 ns per loop
1880
1881
1881 In [5]: import time
1882 In [5]: import time
1882
1883
1883 In [6]: %timeit -n1 time.sleep(2)
1884 In [6]: %timeit -n1 time.sleep(2)
1884 1 loops, best of 3: 2 s per loop
1885 1 loops, best of 3: 2 s per loop
1885
1886
1886
1887
1887 The times reported by %timeit will be slightly higher than those
1888 The times reported by %timeit will be slightly higher than those
1888 reported by the timeit.py script when variables are accessed. This is
1889 reported by the timeit.py script when variables are accessed. This is
1889 due to the fact that %timeit executes the statement in the namespace
1890 due to the fact that %timeit executes the statement in the namespace
1890 of the shell, compared with timeit.py, which uses a single setup
1891 of the shell, compared with timeit.py, which uses a single setup
1891 statement to import function or create variables. Generally, the bias
1892 statement to import function or create variables. Generally, the bias
1892 does not matter as long as results from timeit.py are not mixed with
1893 does not matter as long as results from timeit.py are not mixed with
1893 those from %timeit."""
1894 those from %timeit."""
1894
1895
1895 import timeit
1896 import timeit
1896 import math
1897 import math
1897
1898
1898 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1899 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1899 # certain terminals. Until we figure out a robust way of
1900 # certain terminals. Until we figure out a robust way of
1900 # auto-detecting if the terminal can deal with it, use plain 'us' for
1901 # auto-detecting if the terminal can deal with it, use plain 'us' for
1901 # microseconds. I am really NOT happy about disabling the proper
1902 # microseconds. I am really NOT happy about disabling the proper
1902 # 'micro' prefix, but crashing is worse... If anyone knows what the
1903 # 'micro' prefix, but crashing is worse... If anyone knows what the
1903 # right solution for this is, I'm all ears...
1904 # right solution for this is, I'm all ears...
1904 #
1905 #
1905 # Note: using
1906 # Note: using
1906 #
1907 #
1907 # s = u'\xb5'
1908 # s = u'\xb5'
1908 # s.encode(sys.getdefaultencoding())
1909 # s.encode(sys.getdefaultencoding())
1909 #
1910 #
1910 # is not sufficient, as I've seen terminals where that fails but
1911 # is not sufficient, as I've seen terminals where that fails but
1911 # print s
1912 # print s
1912 #
1913 #
1913 # succeeds
1914 # succeeds
1914 #
1915 #
1915 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1916 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1916
1917
1917 #units = [u"s", u"ms",u'\xb5',"ns"]
1918 #units = [u"s", u"ms",u'\xb5',"ns"]
1918 units = [u"s", u"ms",u'us',"ns"]
1919 units = [u"s", u"ms",u'us',"ns"]
1919
1920
1920 scaling = [1, 1e3, 1e6, 1e9]
1921 scaling = [1, 1e3, 1e6, 1e9]
1921
1922
1922 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1923 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1923 posix=False)
1924 posix=False)
1924 if stmt == "":
1925 if stmt == "":
1925 return
1926 return
1926 timefunc = timeit.default_timer
1927 timefunc = timeit.default_timer
1927 number = int(getattr(opts, "n", 0))
1928 number = int(getattr(opts, "n", 0))
1928 repeat = int(getattr(opts, "r", timeit.default_repeat))
1929 repeat = int(getattr(opts, "r", timeit.default_repeat))
1929 precision = int(getattr(opts, "p", 3))
1930 precision = int(getattr(opts, "p", 3))
1930 if hasattr(opts, "t"):
1931 if hasattr(opts, "t"):
1931 timefunc = time.time
1932 timefunc = time.time
1932 if hasattr(opts, "c"):
1933 if hasattr(opts, "c"):
1933 timefunc = clock
1934 timefunc = clock
1934
1935
1935 timer = timeit.Timer(timer=timefunc)
1936 timer = timeit.Timer(timer=timefunc)
1936 # this code has tight coupling to the inner workings of timeit.Timer,
1937 # this code has tight coupling to the inner workings of timeit.Timer,
1937 # but is there a better way to achieve that the code stmt has access
1938 # but is there a better way to achieve that the code stmt has access
1938 # to the shell namespace?
1939 # to the shell namespace?
1939
1940
1940 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1941 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1941 'setup': "pass"}
1942 'setup': "pass"}
1942 # Track compilation time so it can be reported if too long
1943 # Track compilation time so it can be reported if too long
1943 # Minimum time above which compilation time will be reported
1944 # Minimum time above which compilation time will be reported
1944 tc_min = 0.1
1945 tc_min = 0.1
1945
1946
1946 t0 = clock()
1947 t0 = clock()
1947 code = compile(src, "<magic-timeit>", "exec")
1948 code = compile(src, "<magic-timeit>", "exec")
1948 tc = clock()-t0
1949 tc = clock()-t0
1949
1950
1950 ns = {}
1951 ns = {}
1951 exec code in self.shell.user_ns, ns
1952 exec code in self.shell.user_ns, ns
1952 timer.inner = ns["inner"]
1953 timer.inner = ns["inner"]
1953
1954
1954 if number == 0:
1955 if number == 0:
1955 # determine number so that 0.2 <= total time < 2.0
1956 # determine number so that 0.2 <= total time < 2.0
1956 number = 1
1957 number = 1
1957 for i in range(1, 10):
1958 for i in range(1, 10):
1958 if timer.timeit(number) >= 0.2:
1959 if timer.timeit(number) >= 0.2:
1959 break
1960 break
1960 number *= 10
1961 number *= 10
1961
1962
1962 best = min(timer.repeat(repeat, number)) / number
1963 best = min(timer.repeat(repeat, number)) / number
1963
1964
1964 if best > 0.0 and best < 1000.0:
1965 if best > 0.0 and best < 1000.0:
1965 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1966 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1966 elif best >= 1000.0:
1967 elif best >= 1000.0:
1967 order = 0
1968 order = 0
1968 else:
1969 else:
1969 order = 3
1970 order = 3
1970 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1971 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1971 precision,
1972 precision,
1972 best * scaling[order],
1973 best * scaling[order],
1973 units[order])
1974 units[order])
1974 if tc > tc_min:
1975 if tc > tc_min:
1975 print "Compiler time: %.2f s" % tc
1976 print "Compiler time: %.2f s" % tc
1976
1977
1977 @testdec.skip_doctest
1978 @testdec.skip_doctest
1978 def magic_time(self,parameter_s = ''):
1979 def magic_time(self,parameter_s = ''):
1979 """Time execution of a Python statement or expression.
1980 """Time execution of a Python statement or expression.
1980
1981
1981 The CPU and wall clock times are printed, and the value of the
1982 The CPU and wall clock times are printed, and the value of the
1982 expression (if any) is returned. Note that under Win32, system time
1983 expression (if any) is returned. Note that under Win32, system time
1983 is always reported as 0, since it can not be measured.
1984 is always reported as 0, since it can not be measured.
1984
1985
1985 This function provides very basic timing functionality. In Python
1986 This function provides very basic timing functionality. In Python
1986 2.3, the timeit module offers more control and sophistication, so this
1987 2.3, the timeit module offers more control and sophistication, so this
1987 could be rewritten to use it (patches welcome).
1988 could be rewritten to use it (patches welcome).
1988
1989
1989 Some examples:
1990 Some examples:
1990
1991
1991 In [1]: time 2**128
1992 In [1]: time 2**128
1992 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1993 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1993 Wall time: 0.00
1994 Wall time: 0.00
1994 Out[1]: 340282366920938463463374607431768211456L
1995 Out[1]: 340282366920938463463374607431768211456L
1995
1996
1996 In [2]: n = 1000000
1997 In [2]: n = 1000000
1997
1998
1998 In [3]: time sum(range(n))
1999 In [3]: time sum(range(n))
1999 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
2000 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
2000 Wall time: 1.37
2001 Wall time: 1.37
2001 Out[3]: 499999500000L
2002 Out[3]: 499999500000L
2002
2003
2003 In [4]: time print 'hello world'
2004 In [4]: time print 'hello world'
2004 hello world
2005 hello world
2005 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2006 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2006 Wall time: 0.00
2007 Wall time: 0.00
2007
2008
2008 Note that the time needed by Python to compile the given expression
2009 Note that the time needed by Python to compile the given expression
2009 will be reported if it is more than 0.1s. In this example, the
2010 will be reported if it is more than 0.1s. In this example, the
2010 actual exponentiation is done by Python at compilation time, so while
2011 actual exponentiation is done by Python at compilation time, so while
2011 the expression can take a noticeable amount of time to compute, that
2012 the expression can take a noticeable amount of time to compute, that
2012 time is purely due to the compilation:
2013 time is purely due to the compilation:
2013
2014
2014 In [5]: time 3**9999;
2015 In [5]: time 3**9999;
2015 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2016 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2016 Wall time: 0.00 s
2017 Wall time: 0.00 s
2017
2018
2018 In [6]: time 3**999999;
2019 In [6]: time 3**999999;
2019 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2020 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2020 Wall time: 0.00 s
2021 Wall time: 0.00 s
2021 Compiler : 0.78 s
2022 Compiler : 0.78 s
2022 """
2023 """
2023
2024
2024 # fail immediately if the given expression can't be compiled
2025 # fail immediately if the given expression can't be compiled
2025
2026
2026 expr = self.shell.prefilter(parameter_s,False)
2027 expr = self.shell.prefilter(parameter_s,False)
2027
2028
2028 # Minimum time above which compilation time will be reported
2029 # Minimum time above which compilation time will be reported
2029 tc_min = 0.1
2030 tc_min = 0.1
2030
2031
2031 try:
2032 try:
2032 mode = 'eval'
2033 mode = 'eval'
2033 t0 = clock()
2034 t0 = clock()
2034 code = compile(expr,'<timed eval>',mode)
2035 code = compile(expr,'<timed eval>',mode)
2035 tc = clock()-t0
2036 tc = clock()-t0
2036 except SyntaxError:
2037 except SyntaxError:
2037 mode = 'exec'
2038 mode = 'exec'
2038 t0 = clock()
2039 t0 = clock()
2039 code = compile(expr,'<timed exec>',mode)
2040 code = compile(expr,'<timed exec>',mode)
2040 tc = clock()-t0
2041 tc = clock()-t0
2041 # skew measurement as little as possible
2042 # skew measurement as little as possible
2042 glob = self.shell.user_ns
2043 glob = self.shell.user_ns
2043 clk = clock2
2044 clk = clock2
2044 wtime = time.time
2045 wtime = time.time
2045 # time execution
2046 # time execution
2046 wall_st = wtime()
2047 wall_st = wtime()
2047 if mode=='eval':
2048 if mode=='eval':
2048 st = clk()
2049 st = clk()
2049 out = eval(code,glob)
2050 out = eval(code,glob)
2050 end = clk()
2051 end = clk()
2051 else:
2052 else:
2052 st = clk()
2053 st = clk()
2053 exec code in glob
2054 exec code in glob
2054 end = clk()
2055 end = clk()
2055 out = None
2056 out = None
2056 wall_end = wtime()
2057 wall_end = wtime()
2057 # Compute actual times and report
2058 # Compute actual times and report
2058 wall_time = wall_end-wall_st
2059 wall_time = wall_end-wall_st
2059 cpu_user = end[0]-st[0]
2060 cpu_user = end[0]-st[0]
2060 cpu_sys = end[1]-st[1]
2061 cpu_sys = end[1]-st[1]
2061 cpu_tot = cpu_user+cpu_sys
2062 cpu_tot = cpu_user+cpu_sys
2062 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2063 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2063 (cpu_user,cpu_sys,cpu_tot)
2064 (cpu_user,cpu_sys,cpu_tot)
2064 print "Wall time: %.2f s" % wall_time
2065 print "Wall time: %.2f s" % wall_time
2065 if tc > tc_min:
2066 if tc > tc_min:
2066 print "Compiler : %.2f s" % tc
2067 print "Compiler : %.2f s" % tc
2067 return out
2068 return out
2068
2069
2069 @testdec.skip_doctest
2070 @testdec.skip_doctest
2070 def magic_macro(self,parameter_s = ''):
2071 def magic_macro(self,parameter_s = ''):
2071 """Define a set of input lines as a macro for future re-execution.
2072 """Define a set of input lines as a macro for future re-execution.
2072
2073
2073 Usage:\\
2074 Usage:\\
2074 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2075 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2075
2076
2076 Options:
2077 Options:
2077
2078
2078 -r: use 'raw' input. By default, the 'processed' history is used,
2079 -r: use 'raw' input. By default, the 'processed' history is used,
2079 so that magics are loaded in their transformed version to valid
2080 so that magics are loaded in their transformed version to valid
2080 Python. If this option is given, the raw input as typed as the
2081 Python. If this option is given, the raw input as typed as the
2081 command line is used instead.
2082 command line is used instead.
2082
2083
2083 This will define a global variable called `name` which is a string
2084 This will define a global variable called `name` which is a string
2084 made of joining the slices and lines you specify (n1,n2,... numbers
2085 made of joining the slices and lines you specify (n1,n2,... numbers
2085 above) from your input history into a single string. This variable
2086 above) from your input history into a single string. This variable
2086 acts like an automatic function which re-executes those lines as if
2087 acts like an automatic function which re-executes those lines as if
2087 you had typed them. You just type 'name' at the prompt and the code
2088 you had typed them. You just type 'name' at the prompt and the code
2088 executes.
2089 executes.
2089
2090
2090 The notation for indicating number ranges is: n1-n2 means 'use line
2091 The notation for indicating number ranges is: n1-n2 means 'use line
2091 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2092 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2092 using the lines numbered 5,6 and 7.
2093 using the lines numbered 5,6 and 7.
2093
2094
2094 Note: as a 'hidden' feature, you can also use traditional python slice
2095 Note: as a 'hidden' feature, you can also use traditional python slice
2095 notation, where N:M means numbers N through M-1.
2096 notation, where N:M means numbers N through M-1.
2096
2097
2097 For example, if your history contains (%hist prints it):
2098 For example, if your history contains (%hist prints it):
2098
2099
2099 44: x=1
2100 44: x=1
2100 45: y=3
2101 45: y=3
2101 46: z=x+y
2102 46: z=x+y
2102 47: print x
2103 47: print x
2103 48: a=5
2104 48: a=5
2104 49: print 'x',x,'y',y
2105 49: print 'x',x,'y',y
2105
2106
2106 you can create a macro with lines 44 through 47 (included) and line 49
2107 you can create a macro with lines 44 through 47 (included) and line 49
2107 called my_macro with:
2108 called my_macro with:
2108
2109
2109 In [55]: %macro my_macro 44-47 49
2110 In [55]: %macro my_macro 44-47 49
2110
2111
2111 Now, typing `my_macro` (without quotes) will re-execute all this code
2112 Now, typing `my_macro` (without quotes) will re-execute all this code
2112 in one pass.
2113 in one pass.
2113
2114
2114 You don't need to give the line-numbers in order, and any given line
2115 You don't need to give the line-numbers in order, and any given line
2115 number can appear multiple times. You can assemble macros with any
2116 number can appear multiple times. You can assemble macros with any
2116 lines from your input history in any order.
2117 lines from your input history in any order.
2117
2118
2118 The macro is a simple object which holds its value in an attribute,
2119 The macro is a simple object which holds its value in an attribute,
2119 but IPython's display system checks for macros and executes them as
2120 but IPython's display system checks for macros and executes them as
2120 code instead of printing them when you type their name.
2121 code instead of printing them when you type their name.
2121
2122
2122 You can view a macro's contents by explicitly printing it with:
2123 You can view a macro's contents by explicitly printing it with:
2123
2124
2124 'print macro_name'.
2125 'print macro_name'.
2125
2126
2126 For one-off cases which DON'T contain magic function calls in them you
2127 For one-off cases which DON'T contain magic function calls in them you
2127 can obtain similar results by explicitly executing slices from your
2128 can obtain similar results by explicitly executing slices from your
2128 input history with:
2129 input history with:
2129
2130
2130 In [60]: exec In[44:48]+In[49]"""
2131 In [60]: exec In[44:48]+In[49]"""
2131
2132
2132 opts,args = self.parse_options(parameter_s,'r',mode='list')
2133 opts,args = self.parse_options(parameter_s,'r',mode='list')
2133 if not args:
2134 if not args:
2134 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2135 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2135 macs.sort()
2136 macs.sort()
2136 return macs
2137 return macs
2137 if len(args) == 1:
2138 if len(args) == 1:
2138 raise UsageError(
2139 raise UsageError(
2139 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2140 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2140 name,ranges = args[0], args[1:]
2141 name,ranges = args[0], args[1:]
2141
2142
2142 #print 'rng',ranges # dbg
2143 #print 'rng',ranges # dbg
2143 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2144 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2144 macro = Macro(lines)
2145 macro = Macro(lines)
2145 self.shell.define_macro(name, macro)
2146 self.shell.define_macro(name, macro)
2146 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2147 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2147 print 'Macro contents:'
2148 print 'Macro contents:'
2148 print macro,
2149 print macro,
2149
2150
2150 def magic_save(self,parameter_s = ''):
2151 def magic_save(self,parameter_s = ''):
2151 """Save a set of lines to a given filename.
2152 """Save a set of lines to a given filename.
2152
2153
2153 Usage:\\
2154 Usage:\\
2154 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2155 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2155
2156
2156 Options:
2157 Options:
2157
2158
2158 -r: use 'raw' input. By default, the 'processed' history is used,
2159 -r: use 'raw' input. By default, the 'processed' history is used,
2159 so that magics are loaded in their transformed version to valid
2160 so that magics are loaded in their transformed version to valid
2160 Python. If this option is given, the raw input as typed as the
2161 Python. If this option is given, the raw input as typed as the
2161 command line is used instead.
2162 command line is used instead.
2162
2163
2163 This function uses the same syntax as %macro for line extraction, but
2164 This function uses the same syntax as %macro for line extraction, but
2164 instead of creating a macro it saves the resulting string to the
2165 instead of creating a macro it saves the resulting string to the
2165 filename you specify.
2166 filename you specify.
2166
2167
2167 It adds a '.py' extension to the file if you don't do so yourself, and
2168 It adds a '.py' extension to the file if you don't do so yourself, and
2168 it asks for confirmation before overwriting existing files."""
2169 it asks for confirmation before overwriting existing files."""
2169
2170
2170 opts,args = self.parse_options(parameter_s,'r',mode='list')
2171 opts,args = self.parse_options(parameter_s,'r',mode='list')
2171 fname,ranges = args[0], args[1:]
2172 fname,ranges = args[0], args[1:]
2172 if not fname.endswith('.py'):
2173 if not fname.endswith('.py'):
2173 fname += '.py'
2174 fname += '.py'
2174 if os.path.isfile(fname):
2175 if os.path.isfile(fname):
2175 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2176 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2176 if ans.lower() not in ['y','yes']:
2177 if ans.lower() not in ['y','yes']:
2177 print 'Operation cancelled.'
2178 print 'Operation cancelled.'
2178 return
2179 return
2179 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2180 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2180 f = file(fname,'w')
2181 f = file(fname,'w')
2181 f.write(cmds)
2182 f.write(cmds)
2182 f.close()
2183 f.close()
2183 print 'The following commands were written to file `%s`:' % fname
2184 print 'The following commands were written to file `%s`:' % fname
2184 print cmds
2185 print cmds
2185
2186
2186 def _edit_macro(self,mname,macro):
2187 def _edit_macro(self,mname,macro):
2187 """open an editor with the macro data in a file"""
2188 """open an editor with the macro data in a file"""
2188 filename = self.shell.mktempfile(macro.value)
2189 filename = self.shell.mktempfile(macro.value)
2189 self.shell.hooks.editor(filename)
2190 self.shell.hooks.editor(filename)
2190
2191
2191 # and make a new macro object, to replace the old one
2192 # and make a new macro object, to replace the old one
2192 mfile = open(filename)
2193 mfile = open(filename)
2193 mvalue = mfile.read()
2194 mvalue = mfile.read()
2194 mfile.close()
2195 mfile.close()
2195 self.shell.user_ns[mname] = Macro(mvalue)
2196 self.shell.user_ns[mname] = Macro(mvalue)
2196
2197
2197 def magic_ed(self,parameter_s=''):
2198 def magic_ed(self,parameter_s=''):
2198 """Alias to %edit."""
2199 """Alias to %edit."""
2199 return self.magic_edit(parameter_s)
2200 return self.magic_edit(parameter_s)
2200
2201
2201 @testdec.skip_doctest
2202 @testdec.skip_doctest
2202 def magic_edit(self,parameter_s='',last_call=['','']):
2203 def magic_edit(self,parameter_s='',last_call=['','']):
2203 """Bring up an editor and execute the resulting code.
2204 """Bring up an editor and execute the resulting code.
2204
2205
2205 Usage:
2206 Usage:
2206 %edit [options] [args]
2207 %edit [options] [args]
2207
2208
2208 %edit runs IPython's editor hook. The default version of this hook is
2209 %edit runs IPython's editor hook. The default version of this hook is
2209 set to call the __IPYTHON__.rc.editor command. This is read from your
2210 set to call the __IPYTHON__.rc.editor command. This is read from your
2210 environment variable $EDITOR. If this isn't found, it will default to
2211 environment variable $EDITOR. If this isn't found, it will default to
2211 vi under Linux/Unix and to notepad under Windows. See the end of this
2212 vi under Linux/Unix and to notepad under Windows. See the end of this
2212 docstring for how to change the editor hook.
2213 docstring for how to change the editor hook.
2213
2214
2214 You can also set the value of this editor via the command line option
2215 You can also set the value of this editor via the command line option
2215 '-editor' or in your ipythonrc file. This is useful if you wish to use
2216 '-editor' or in your ipythonrc file. This is useful if you wish to use
2216 specifically for IPython an editor different from your typical default
2217 specifically for IPython an editor different from your typical default
2217 (and for Windows users who typically don't set environment variables).
2218 (and for Windows users who typically don't set environment variables).
2218
2219
2219 This command allows you to conveniently edit multi-line code right in
2220 This command allows you to conveniently edit multi-line code right in
2220 your IPython session.
2221 your IPython session.
2221
2222
2222 If called without arguments, %edit opens up an empty editor with a
2223 If called without arguments, %edit opens up an empty editor with a
2223 temporary file and will execute the contents of this file when you
2224 temporary file and will execute the contents of this file when you
2224 close it (don't forget to save it!).
2225 close it (don't forget to save it!).
2225
2226
2226
2227
2227 Options:
2228 Options:
2228
2229
2229 -n <number>: open the editor at a specified line number. By default,
2230 -n <number>: open the editor at a specified line number. By default,
2230 the IPython editor hook uses the unix syntax 'editor +N filename', but
2231 the IPython editor hook uses the unix syntax 'editor +N filename', but
2231 you can configure this by providing your own modified hook if your
2232 you can configure this by providing your own modified hook if your
2232 favorite editor supports line-number specifications with a different
2233 favorite editor supports line-number specifications with a different
2233 syntax.
2234 syntax.
2234
2235
2235 -p: this will call the editor with the same data as the previous time
2236 -p: this will call the editor with the same data as the previous time
2236 it was used, regardless of how long ago (in your current session) it
2237 it was used, regardless of how long ago (in your current session) it
2237 was.
2238 was.
2238
2239
2239 -r: use 'raw' input. This option only applies to input taken from the
2240 -r: use 'raw' input. This option only applies to input taken from the
2240 user's history. By default, the 'processed' history is used, so that
2241 user's history. By default, the 'processed' history is used, so that
2241 magics are loaded in their transformed version to valid Python. If
2242 magics are loaded in their transformed version to valid Python. If
2242 this option is given, the raw input as typed as the command line is
2243 this option is given, the raw input as typed as the command line is
2243 used instead. When you exit the editor, it will be executed by
2244 used instead. When you exit the editor, it will be executed by
2244 IPython's own processor.
2245 IPython's own processor.
2245
2246
2246 -x: do not execute the edited code immediately upon exit. This is
2247 -x: do not execute the edited code immediately upon exit. This is
2247 mainly useful if you are editing programs which need to be called with
2248 mainly useful if you are editing programs which need to be called with
2248 command line arguments, which you can then do using %run.
2249 command line arguments, which you can then do using %run.
2249
2250
2250
2251
2251 Arguments:
2252 Arguments:
2252
2253
2253 If arguments are given, the following possibilites exist:
2254 If arguments are given, the following possibilites exist:
2254
2255
2255 - The arguments are numbers or pairs of colon-separated numbers (like
2256 - The arguments are numbers or pairs of colon-separated numbers (like
2256 1 4:8 9). These are interpreted as lines of previous input to be
2257 1 4:8 9). These are interpreted as lines of previous input to be
2257 loaded into the editor. The syntax is the same of the %macro command.
2258 loaded into the editor. The syntax is the same of the %macro command.
2258
2259
2259 - If the argument doesn't start with a number, it is evaluated as a
2260 - If the argument doesn't start with a number, it is evaluated as a
2260 variable and its contents loaded into the editor. You can thus edit
2261 variable and its contents loaded into the editor. You can thus edit
2261 any string which contains python code (including the result of
2262 any string which contains python code (including the result of
2262 previous edits).
2263 previous edits).
2263
2264
2264 - If the argument is the name of an object (other than a string),
2265 - If the argument is the name of an object (other than a string),
2265 IPython will try to locate the file where it was defined and open the
2266 IPython will try to locate the file where it was defined and open the
2266 editor at the point where it is defined. You can use `%edit function`
2267 editor at the point where it is defined. You can use `%edit function`
2267 to load an editor exactly at the point where 'function' is defined,
2268 to load an editor exactly at the point where 'function' is defined,
2268 edit it and have the file be executed automatically.
2269 edit it and have the file be executed automatically.
2269
2270
2270 If the object is a macro (see %macro for details), this opens up your
2271 If the object is a macro (see %macro for details), this opens up your
2271 specified editor with a temporary file containing the macro's data.
2272 specified editor with a temporary file containing the macro's data.
2272 Upon exit, the macro is reloaded with the contents of the file.
2273 Upon exit, the macro is reloaded with the contents of the file.
2273
2274
2274 Note: opening at an exact line is only supported under Unix, and some
2275 Note: opening at an exact line is only supported under Unix, and some
2275 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2276 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2276 '+NUMBER' parameter necessary for this feature. Good editors like
2277 '+NUMBER' parameter necessary for this feature. Good editors like
2277 (X)Emacs, vi, jed, pico and joe all do.
2278 (X)Emacs, vi, jed, pico and joe all do.
2278
2279
2279 - If the argument is not found as a variable, IPython will look for a
2280 - If the argument is not found as a variable, IPython will look for a
2280 file with that name (adding .py if necessary) and load it into the
2281 file with that name (adding .py if necessary) and load it into the
2281 editor. It will execute its contents with execfile() when you exit,
2282 editor. It will execute its contents with execfile() when you exit,
2282 loading any code in the file into your interactive namespace.
2283 loading any code in the file into your interactive namespace.
2283
2284
2284 After executing your code, %edit will return as output the code you
2285 After executing your code, %edit will return as output the code you
2285 typed in the editor (except when it was an existing file). This way
2286 typed in the editor (except when it was an existing file). This way
2286 you can reload the code in further invocations of %edit as a variable,
2287 you can reload the code in further invocations of %edit as a variable,
2287 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2288 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2288 the output.
2289 the output.
2289
2290
2290 Note that %edit is also available through the alias %ed.
2291 Note that %edit is also available through the alias %ed.
2291
2292
2292 This is an example of creating a simple function inside the editor and
2293 This is an example of creating a simple function inside the editor and
2293 then modifying it. First, start up the editor:
2294 then modifying it. First, start up the editor:
2294
2295
2295 In [1]: ed
2296 In [1]: ed
2296 Editing... done. Executing edited code...
2297 Editing... done. Executing edited code...
2297 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2298 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2298
2299
2299 We can then call the function foo():
2300 We can then call the function foo():
2300
2301
2301 In [2]: foo()
2302 In [2]: foo()
2302 foo() was defined in an editing session
2303 foo() was defined in an editing session
2303
2304
2304 Now we edit foo. IPython automatically loads the editor with the
2305 Now we edit foo. IPython automatically loads the editor with the
2305 (temporary) file where foo() was previously defined:
2306 (temporary) file where foo() was previously defined:
2306
2307
2307 In [3]: ed foo
2308 In [3]: ed foo
2308 Editing... done. Executing edited code...
2309 Editing... done. Executing edited code...
2309
2310
2310 And if we call foo() again we get the modified version:
2311 And if we call foo() again we get the modified version:
2311
2312
2312 In [4]: foo()
2313 In [4]: foo()
2313 foo() has now been changed!
2314 foo() has now been changed!
2314
2315
2315 Here is an example of how to edit a code snippet successive
2316 Here is an example of how to edit a code snippet successive
2316 times. First we call the editor:
2317 times. First we call the editor:
2317
2318
2318 In [5]: ed
2319 In [5]: ed
2319 Editing... done. Executing edited code...
2320 Editing... done. Executing edited code...
2320 hello
2321 hello
2321 Out[5]: "print 'hello'n"
2322 Out[5]: "print 'hello'n"
2322
2323
2323 Now we call it again with the previous output (stored in _):
2324 Now we call it again with the previous output (stored in _):
2324
2325
2325 In [6]: ed _
2326 In [6]: ed _
2326 Editing... done. Executing edited code...
2327 Editing... done. Executing edited code...
2327 hello world
2328 hello world
2328 Out[6]: "print 'hello world'n"
2329 Out[6]: "print 'hello world'n"
2329
2330
2330 Now we call it with the output #8 (stored in _8, also as Out[8]):
2331 Now we call it with the output #8 (stored in _8, also as Out[8]):
2331
2332
2332 In [7]: ed _8
2333 In [7]: ed _8
2333 Editing... done. Executing edited code...
2334 Editing... done. Executing edited code...
2334 hello again
2335 hello again
2335 Out[7]: "print 'hello again'n"
2336 Out[7]: "print 'hello again'n"
2336
2337
2337
2338
2338 Changing the default editor hook:
2339 Changing the default editor hook:
2339
2340
2340 If you wish to write your own editor hook, you can put it in a
2341 If you wish to write your own editor hook, you can put it in a
2341 configuration file which you load at startup time. The default hook
2342 configuration file which you load at startup time. The default hook
2342 is defined in the IPython.core.hooks module, and you can use that as a
2343 is defined in the IPython.core.hooks module, and you can use that as a
2343 starting example for further modifications. That file also has
2344 starting example for further modifications. That file also has
2344 general instructions on how to set a new hook for use once you've
2345 general instructions on how to set a new hook for use once you've
2345 defined it."""
2346 defined it."""
2346
2347
2347 # FIXME: This function has become a convoluted mess. It needs a
2348 # FIXME: This function has become a convoluted mess. It needs a
2348 # ground-up rewrite with clean, simple logic.
2349 # ground-up rewrite with clean, simple logic.
2349
2350
2350 def make_filename(arg):
2351 def make_filename(arg):
2351 "Make a filename from the given args"
2352 "Make a filename from the given args"
2352 try:
2353 try:
2353 filename = get_py_filename(arg)
2354 filename = get_py_filename(arg)
2354 except IOError:
2355 except IOError:
2355 if args.endswith('.py'):
2356 if args.endswith('.py'):
2356 filename = arg
2357 filename = arg
2357 else:
2358 else:
2358 filename = None
2359 filename = None
2359 return filename
2360 return filename
2360
2361
2361 # custom exceptions
2362 # custom exceptions
2362 class DataIsObject(Exception): pass
2363 class DataIsObject(Exception): pass
2363
2364
2364 opts,args = self.parse_options(parameter_s,'prxn:')
2365 opts,args = self.parse_options(parameter_s,'prxn:')
2365 # Set a few locals from the options for convenience:
2366 # Set a few locals from the options for convenience:
2366 opts_p = opts.has_key('p')
2367 opts_p = opts.has_key('p')
2367 opts_r = opts.has_key('r')
2368 opts_r = opts.has_key('r')
2368
2369
2369 # Default line number value
2370 # Default line number value
2370 lineno = opts.get('n',None)
2371 lineno = opts.get('n',None)
2371
2372
2372 if opts_p:
2373 if opts_p:
2373 args = '_%s' % last_call[0]
2374 args = '_%s' % last_call[0]
2374 if not self.shell.user_ns.has_key(args):
2375 if not self.shell.user_ns.has_key(args):
2375 args = last_call[1]
2376 args = last_call[1]
2376
2377
2377 # use last_call to remember the state of the previous call, but don't
2378 # use last_call to remember the state of the previous call, but don't
2378 # let it be clobbered by successive '-p' calls.
2379 # let it be clobbered by successive '-p' calls.
2379 try:
2380 try:
2380 last_call[0] = self.shell.outputcache.prompt_count
2381 last_call[0] = self.shell.outputcache.prompt_count
2381 if not opts_p:
2382 if not opts_p:
2382 last_call[1] = parameter_s
2383 last_call[1] = parameter_s
2383 except:
2384 except:
2384 pass
2385 pass
2385
2386
2386 # by default this is done with temp files, except when the given
2387 # by default this is done with temp files, except when the given
2387 # arg is a filename
2388 # arg is a filename
2388 use_temp = 1
2389 use_temp = 1
2389
2390
2390 if re.match(r'\d',args):
2391 if re.match(r'\d',args):
2391 # Mode where user specifies ranges of lines, like in %macro.
2392 # Mode where user specifies ranges of lines, like in %macro.
2392 # This means that you can't edit files whose names begin with
2393 # This means that you can't edit files whose names begin with
2393 # numbers this way. Tough.
2394 # numbers this way. Tough.
2394 ranges = args.split()
2395 ranges = args.split()
2395 data = ''.join(self.extract_input_slices(ranges,opts_r))
2396 data = ''.join(self.extract_input_slices(ranges,opts_r))
2396 elif args.endswith('.py'):
2397 elif args.endswith('.py'):
2397 filename = make_filename(args)
2398 filename = make_filename(args)
2398 data = ''
2399 data = ''
2399 use_temp = 0
2400 use_temp = 0
2400 elif args:
2401 elif args:
2401 try:
2402 try:
2402 # Load the parameter given as a variable. If not a string,
2403 # Load the parameter given as a variable. If not a string,
2403 # process it as an object instead (below)
2404 # process it as an object instead (below)
2404
2405
2405 #print '*** args',args,'type',type(args) # dbg
2406 #print '*** args',args,'type',type(args) # dbg
2406 data = eval(args,self.shell.user_ns)
2407 data = eval(args,self.shell.user_ns)
2407 if not type(data) in StringTypes:
2408 if not type(data) in StringTypes:
2408 raise DataIsObject
2409 raise DataIsObject
2409
2410
2410 except (NameError,SyntaxError):
2411 except (NameError,SyntaxError):
2411 # given argument is not a variable, try as a filename
2412 # given argument is not a variable, try as a filename
2412 filename = make_filename(args)
2413 filename = make_filename(args)
2413 if filename is None:
2414 if filename is None:
2414 warn("Argument given (%s) can't be found as a variable "
2415 warn("Argument given (%s) can't be found as a variable "
2415 "or as a filename." % args)
2416 "or as a filename." % args)
2416 return
2417 return
2417
2418
2418 data = ''
2419 data = ''
2419 use_temp = 0
2420 use_temp = 0
2420 except DataIsObject:
2421 except DataIsObject:
2421
2422
2422 # macros have a special edit function
2423 # macros have a special edit function
2423 if isinstance(data,Macro):
2424 if isinstance(data,Macro):
2424 self._edit_macro(args,data)
2425 self._edit_macro(args,data)
2425 return
2426 return
2426
2427
2427 # For objects, try to edit the file where they are defined
2428 # For objects, try to edit the file where they are defined
2428 try:
2429 try:
2429 filename = inspect.getabsfile(data)
2430 filename = inspect.getabsfile(data)
2430 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2431 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2431 # class created by %edit? Try to find source
2432 # class created by %edit? Try to find source
2432 # by looking for method definitions instead, the
2433 # by looking for method definitions instead, the
2433 # __module__ in those classes is FakeModule.
2434 # __module__ in those classes is FakeModule.
2434 attrs = [getattr(data, aname) for aname in dir(data)]
2435 attrs = [getattr(data, aname) for aname in dir(data)]
2435 for attr in attrs:
2436 for attr in attrs:
2436 if not inspect.ismethod(attr):
2437 if not inspect.ismethod(attr):
2437 continue
2438 continue
2438 filename = inspect.getabsfile(attr)
2439 filename = inspect.getabsfile(attr)
2439 if filename and 'fakemodule' not in filename.lower():
2440 if filename and 'fakemodule' not in filename.lower():
2440 # change the attribute to be the edit target instead
2441 # change the attribute to be the edit target instead
2441 data = attr
2442 data = attr
2442 break
2443 break
2443
2444
2444 datafile = 1
2445 datafile = 1
2445 except TypeError:
2446 except TypeError:
2446 filename = make_filename(args)
2447 filename = make_filename(args)
2447 datafile = 1
2448 datafile = 1
2448 warn('Could not find file where `%s` is defined.\n'
2449 warn('Could not find file where `%s` is defined.\n'
2449 'Opening a file named `%s`' % (args,filename))
2450 'Opening a file named `%s`' % (args,filename))
2450 # Now, make sure we can actually read the source (if it was in
2451 # Now, make sure we can actually read the source (if it was in
2451 # a temp file it's gone by now).
2452 # a temp file it's gone by now).
2452 if datafile:
2453 if datafile:
2453 try:
2454 try:
2454 if lineno is None:
2455 if lineno is None:
2455 lineno = inspect.getsourcelines(data)[1]
2456 lineno = inspect.getsourcelines(data)[1]
2456 except IOError:
2457 except IOError:
2457 filename = make_filename(args)
2458 filename = make_filename(args)
2458 if filename is None:
2459 if filename is None:
2459 warn('The file `%s` where `%s` was defined cannot '
2460 warn('The file `%s` where `%s` was defined cannot '
2460 'be read.' % (filename,data))
2461 'be read.' % (filename,data))
2461 return
2462 return
2462 use_temp = 0
2463 use_temp = 0
2463 else:
2464 else:
2464 data = ''
2465 data = ''
2465
2466
2466 if use_temp:
2467 if use_temp:
2467 filename = self.shell.mktempfile(data)
2468 filename = self.shell.mktempfile(data)
2468 print 'IPython will make a temporary file named:',filename
2469 print 'IPython will make a temporary file named:',filename
2469
2470
2470 # do actual editing here
2471 # do actual editing here
2471 print 'Editing...',
2472 print 'Editing...',
2472 sys.stdout.flush()
2473 sys.stdout.flush()
2473 try:
2474 try:
2474 # Quote filenames that may have spaces in them
2475 # Quote filenames that may have spaces in them
2475 if ' ' in filename:
2476 if ' ' in filename:
2476 filename = "%s" % filename
2477 filename = "%s" % filename
2477 self.shell.hooks.editor(filename,lineno)
2478 self.shell.hooks.editor(filename,lineno)
2478 except TryNext:
2479 except TryNext:
2479 warn('Could not open editor')
2480 warn('Could not open editor')
2480 return
2481 return
2481
2482
2482 # XXX TODO: should this be generalized for all string vars?
2483 # XXX TODO: should this be generalized for all string vars?
2483 # For now, this is special-cased to blocks created by cpaste
2484 # For now, this is special-cased to blocks created by cpaste
2484 if args.strip() == 'pasted_block':
2485 if args.strip() == 'pasted_block':
2485 self.shell.user_ns['pasted_block'] = file_read(filename)
2486 self.shell.user_ns['pasted_block'] = file_read(filename)
2486
2487
2487 if opts.has_key('x'): # -x prevents actual execution
2488 if opts.has_key('x'): # -x prevents actual execution
2488 print
2489 print
2489 else:
2490 else:
2490 print 'done. Executing edited code...'
2491 print 'done. Executing edited code...'
2491 if opts_r:
2492 if opts_r:
2492 self.shell.runlines(file_read(filename))
2493 self.shell.runlines(file_read(filename))
2493 else:
2494 else:
2494 self.shell.safe_execfile(filename,self.shell.user_ns,
2495 self.shell.safe_execfile(filename,self.shell.user_ns,
2495 self.shell.user_ns)
2496 self.shell.user_ns)
2496
2497
2497
2498
2498 if use_temp:
2499 if use_temp:
2499 try:
2500 try:
2500 return open(filename).read()
2501 return open(filename).read()
2501 except IOError,msg:
2502 except IOError,msg:
2502 if msg.filename == filename:
2503 if msg.filename == filename:
2503 warn('File not found. Did you forget to save?')
2504 warn('File not found. Did you forget to save?')
2504 return
2505 return
2505 else:
2506 else:
2506 self.shell.showtraceback()
2507 self.shell.showtraceback()
2507
2508
2508 def magic_xmode(self,parameter_s = ''):
2509 def magic_xmode(self,parameter_s = ''):
2509 """Switch modes for the exception handlers.
2510 """Switch modes for the exception handlers.
2510
2511
2511 Valid modes: Plain, Context and Verbose.
2512 Valid modes: Plain, Context and Verbose.
2512
2513
2513 If called without arguments, acts as a toggle."""
2514 If called without arguments, acts as a toggle."""
2514
2515
2515 def xmode_switch_err(name):
2516 def xmode_switch_err(name):
2516 warn('Error changing %s exception modes.\n%s' %
2517 warn('Error changing %s exception modes.\n%s' %
2517 (name,sys.exc_info()[1]))
2518 (name,sys.exc_info()[1]))
2518
2519
2519 shell = self.shell
2520 shell = self.shell
2520 new_mode = parameter_s.strip().capitalize()
2521 new_mode = parameter_s.strip().capitalize()
2521 try:
2522 try:
2522 shell.InteractiveTB.set_mode(mode=new_mode)
2523 shell.InteractiveTB.set_mode(mode=new_mode)
2523 print 'Exception reporting mode:',shell.InteractiveTB.mode
2524 print 'Exception reporting mode:',shell.InteractiveTB.mode
2524 except:
2525 except:
2525 xmode_switch_err('user')
2526 xmode_switch_err('user')
2526
2527
2527 def magic_colors(self,parameter_s = ''):
2528 def magic_colors(self,parameter_s = ''):
2528 """Switch color scheme for prompts, info system and exception handlers.
2529 """Switch color scheme for prompts, info system and exception handlers.
2529
2530
2530 Currently implemented schemes: NoColor, Linux, LightBG.
2531 Currently implemented schemes: NoColor, Linux, LightBG.
2531
2532
2532 Color scheme names are not case-sensitive."""
2533 Color scheme names are not case-sensitive."""
2533
2534
2534 def color_switch_err(name):
2535 def color_switch_err(name):
2535 warn('Error changing %s color schemes.\n%s' %
2536 warn('Error changing %s color schemes.\n%s' %
2536 (name,sys.exc_info()[1]))
2537 (name,sys.exc_info()[1]))
2537
2538
2538
2539
2539 new_scheme = parameter_s.strip()
2540 new_scheme = parameter_s.strip()
2540 if not new_scheme:
2541 if not new_scheme:
2541 raise UsageError(
2542 raise UsageError(
2542 "%colors: you must specify a color scheme. See '%colors?'")
2543 "%colors: you must specify a color scheme. See '%colors?'")
2543 return
2544 return
2544 # local shortcut
2545 # local shortcut
2545 shell = self.shell
2546 shell = self.shell
2546
2547
2547 import IPython.utils.rlineimpl as readline
2548 import IPython.utils.rlineimpl as readline
2548
2549
2549 if not readline.have_readline and sys.platform == "win32":
2550 if not readline.have_readline and sys.platform == "win32":
2550 msg = """\
2551 msg = """\
2551 Proper color support under MS Windows requires the pyreadline library.
2552 Proper color support under MS Windows requires the pyreadline library.
2552 You can find it at:
2553 You can find it at:
2553 http://ipython.scipy.org/moin/PyReadline/Intro
2554 http://ipython.scipy.org/moin/PyReadline/Intro
2554 Gary's readline needs the ctypes module, from:
2555 Gary's readline needs the ctypes module, from:
2555 http://starship.python.net/crew/theller/ctypes
2556 http://starship.python.net/crew/theller/ctypes
2556 (Note that ctypes is already part of Python versions 2.5 and newer).
2557 (Note that ctypes is already part of Python versions 2.5 and newer).
2557
2558
2558 Defaulting color scheme to 'NoColor'"""
2559 Defaulting color scheme to 'NoColor'"""
2559 new_scheme = 'NoColor'
2560 new_scheme = 'NoColor'
2560 warn(msg)
2561 warn(msg)
2561
2562
2562 # readline option is 0
2563 # readline option is 0
2563 if not shell.has_readline:
2564 if not shell.has_readline:
2564 new_scheme = 'NoColor'
2565 new_scheme = 'NoColor'
2565
2566
2566 # Set prompt colors
2567 # Set prompt colors
2567 try:
2568 try:
2568 shell.outputcache.set_colors(new_scheme)
2569 shell.outputcache.set_colors(new_scheme)
2569 except:
2570 except:
2570 color_switch_err('prompt')
2571 color_switch_err('prompt')
2571 else:
2572 else:
2572 shell.colors = \
2573 shell.colors = \
2573 shell.outputcache.color_table.active_scheme_name
2574 shell.outputcache.color_table.active_scheme_name
2574 # Set exception colors
2575 # Set exception colors
2575 try:
2576 try:
2576 shell.InteractiveTB.set_colors(scheme = new_scheme)
2577 shell.InteractiveTB.set_colors(scheme = new_scheme)
2577 shell.SyntaxTB.set_colors(scheme = new_scheme)
2578 shell.SyntaxTB.set_colors(scheme = new_scheme)
2578 except:
2579 except:
2579 color_switch_err('exception')
2580 color_switch_err('exception')
2580
2581
2581 # Set info (for 'object?') colors
2582 # Set info (for 'object?') colors
2582 if shell.color_info:
2583 if shell.color_info:
2583 try:
2584 try:
2584 shell.inspector.set_active_scheme(new_scheme)
2585 shell.inspector.set_active_scheme(new_scheme)
2585 except:
2586 except:
2586 color_switch_err('object inspector')
2587 color_switch_err('object inspector')
2587 else:
2588 else:
2588 shell.inspector.set_active_scheme('NoColor')
2589 shell.inspector.set_active_scheme('NoColor')
2589
2590
2590 def magic_color_info(self,parameter_s = ''):
2591 def magic_color_info(self,parameter_s = ''):
2591 """Toggle color_info.
2592 """Toggle color_info.
2592
2593
2593 The color_info configuration parameter controls whether colors are
2594 The color_info configuration parameter controls whether colors are
2594 used for displaying object details (by things like %psource, %pfile or
2595 used for displaying object details (by things like %psource, %pfile or
2595 the '?' system). This function toggles this value with each call.
2596 the '?' system). This function toggles this value with each call.
2596
2597
2597 Note that unless you have a fairly recent pager (less works better
2598 Note that unless you have a fairly recent pager (less works better
2598 than more) in your system, using colored object information displays
2599 than more) in your system, using colored object information displays
2599 will not work properly. Test it and see."""
2600 will not work properly. Test it and see."""
2600
2601
2601 self.shell.color_info = not self.shell.color_info
2602 self.shell.color_info = not self.shell.color_info
2602 self.magic_colors(self.shell.colors)
2603 self.magic_colors(self.shell.colors)
2603 print 'Object introspection functions have now coloring:',
2604 print 'Object introspection functions have now coloring:',
2604 print ['OFF','ON'][int(self.shell.color_info)]
2605 print ['OFF','ON'][int(self.shell.color_info)]
2605
2606
2606 def magic_Pprint(self, parameter_s=''):
2607 def magic_Pprint(self, parameter_s=''):
2607 """Toggle pretty printing on/off."""
2608 """Toggle pretty printing on/off."""
2608
2609
2609 self.shell.pprint = 1 - self.shell.pprint
2610 self.shell.pprint = 1 - self.shell.pprint
2610 print 'Pretty printing has been turned', \
2611 print 'Pretty printing has been turned', \
2611 ['OFF','ON'][self.shell.pprint]
2612 ['OFF','ON'][self.shell.pprint]
2612
2613
2613 def magic_Exit(self, parameter_s=''):
2614 def magic_Exit(self, parameter_s=''):
2614 """Exit IPython without confirmation."""
2615 """Exit IPython without confirmation."""
2615
2616
2616 self.shell.ask_exit()
2617 self.shell.ask_exit()
2617
2618
2618 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2619 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2619 magic_exit = magic_quit = magic_Quit = magic_Exit
2620 magic_exit = magic_quit = magic_Quit = magic_Exit
2620
2621
2621 #......................................................................
2622 #......................................................................
2622 # Functions to implement unix shell-type things
2623 # Functions to implement unix shell-type things
2623
2624
2624 @testdec.skip_doctest
2625 @testdec.skip_doctest
2625 def magic_alias(self, parameter_s = ''):
2626 def magic_alias(self, parameter_s = ''):
2626 """Define an alias for a system command.
2627 """Define an alias for a system command.
2627
2628
2628 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2629 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2629
2630
2630 Then, typing 'alias_name params' will execute the system command 'cmd
2631 Then, typing 'alias_name params' will execute the system command 'cmd
2631 params' (from your underlying operating system).
2632 params' (from your underlying operating system).
2632
2633
2633 Aliases have lower precedence than magic functions and Python normal
2634 Aliases have lower precedence than magic functions and Python normal
2634 variables, so if 'foo' is both a Python variable and an alias, the
2635 variables, so if 'foo' is both a Python variable and an alias, the
2635 alias can not be executed until 'del foo' removes the Python variable.
2636 alias can not be executed until 'del foo' removes the Python variable.
2636
2637
2637 You can use the %l specifier in an alias definition to represent the
2638 You can use the %l specifier in an alias definition to represent the
2638 whole line when the alias is called. For example:
2639 whole line when the alias is called. For example:
2639
2640
2640 In [2]: alias all echo "Input in brackets: <%l>"
2641 In [2]: alias all echo "Input in brackets: <%l>"
2641 In [3]: all hello world
2642 In [3]: all hello world
2642 Input in brackets: <hello world>
2643 Input in brackets: <hello world>
2643
2644
2644 You can also define aliases with parameters using %s specifiers (one
2645 You can also define aliases with parameters using %s specifiers (one
2645 per parameter):
2646 per parameter):
2646
2647
2647 In [1]: alias parts echo first %s second %s
2648 In [1]: alias parts echo first %s second %s
2648 In [2]: %parts A B
2649 In [2]: %parts A B
2649 first A second B
2650 first A second B
2650 In [3]: %parts A
2651 In [3]: %parts A
2651 Incorrect number of arguments: 2 expected.
2652 Incorrect number of arguments: 2 expected.
2652 parts is an alias to: 'echo first %s second %s'
2653 parts is an alias to: 'echo first %s second %s'
2653
2654
2654 Note that %l and %s are mutually exclusive. You can only use one or
2655 Note that %l and %s are mutually exclusive. You can only use one or
2655 the other in your aliases.
2656 the other in your aliases.
2656
2657
2657 Aliases expand Python variables just like system calls using ! or !!
2658 Aliases expand Python variables just like system calls using ! or !!
2658 do: all expressions prefixed with '$' get expanded. For details of
2659 do: all expressions prefixed with '$' get expanded. For details of
2659 the semantic rules, see PEP-215:
2660 the semantic rules, see PEP-215:
2660 http://www.python.org/peps/pep-0215.html. This is the library used by
2661 http://www.python.org/peps/pep-0215.html. This is the library used by
2661 IPython for variable expansion. If you want to access a true shell
2662 IPython for variable expansion. If you want to access a true shell
2662 variable, an extra $ is necessary to prevent its expansion by IPython:
2663 variable, an extra $ is necessary to prevent its expansion by IPython:
2663
2664
2664 In [6]: alias show echo
2665 In [6]: alias show echo
2665 In [7]: PATH='A Python string'
2666 In [7]: PATH='A Python string'
2666 In [8]: show $PATH
2667 In [8]: show $PATH
2667 A Python string
2668 A Python string
2668 In [9]: show $$PATH
2669 In [9]: show $$PATH
2669 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2670 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2670
2671
2671 You can use the alias facility to acess all of $PATH. See the %rehash
2672 You can use the alias facility to acess all of $PATH. See the %rehash
2672 and %rehashx functions, which automatically create aliases for the
2673 and %rehashx functions, which automatically create aliases for the
2673 contents of your $PATH.
2674 contents of your $PATH.
2674
2675
2675 If called with no parameters, %alias prints the current alias table."""
2676 If called with no parameters, %alias prints the current alias table."""
2676
2677
2677 par = parameter_s.strip()
2678 par = parameter_s.strip()
2678 if not par:
2679 if not par:
2679 stored = self.db.get('stored_aliases', {} )
2680 stored = self.db.get('stored_aliases', {} )
2680 aliases = sorted(self.shell.alias_manager.aliases)
2681 aliases = sorted(self.shell.alias_manager.aliases)
2681 # for k, v in stored:
2682 # for k, v in stored:
2682 # atab.append(k, v[0])
2683 # atab.append(k, v[0])
2683
2684
2684 print "Total number of aliases:", len(aliases)
2685 print "Total number of aliases:", len(aliases)
2685 return aliases
2686 return aliases
2686
2687
2687 # Now try to define a new one
2688 # Now try to define a new one
2688 try:
2689 try:
2689 alias,cmd = par.split(None, 1)
2690 alias,cmd = par.split(None, 1)
2690 except:
2691 except:
2691 print oinspect.getdoc(self.magic_alias)
2692 print oinspect.getdoc(self.magic_alias)
2692 else:
2693 else:
2693 self.shell.alias_manager.soft_define_alias(alias, cmd)
2694 self.shell.alias_manager.soft_define_alias(alias, cmd)
2694 # end magic_alias
2695 # end magic_alias
2695
2696
2696 def magic_unalias(self, parameter_s = ''):
2697 def magic_unalias(self, parameter_s = ''):
2697 """Remove an alias"""
2698 """Remove an alias"""
2698
2699
2699 aname = parameter_s.strip()
2700 aname = parameter_s.strip()
2700 self.shell.alias_manager.undefine_alias(aname)
2701 self.shell.alias_manager.undefine_alias(aname)
2701 stored = self.db.get('stored_aliases', {} )
2702 stored = self.db.get('stored_aliases', {} )
2702 if aname in stored:
2703 if aname in stored:
2703 print "Removing %stored alias",aname
2704 print "Removing %stored alias",aname
2704 del stored[aname]
2705 del stored[aname]
2705 self.db['stored_aliases'] = stored
2706 self.db['stored_aliases'] = stored
2706
2707
2707
2708
2708 def magic_rehashx(self, parameter_s = ''):
2709 def magic_rehashx(self, parameter_s = ''):
2709 """Update the alias table with all executable files in $PATH.
2710 """Update the alias table with all executable files in $PATH.
2710
2711
2711 This version explicitly checks that every entry in $PATH is a file
2712 This version explicitly checks that every entry in $PATH is a file
2712 with execute access (os.X_OK), so it is much slower than %rehash.
2713 with execute access (os.X_OK), so it is much slower than %rehash.
2713
2714
2714 Under Windows, it checks executability as a match agains a
2715 Under Windows, it checks executability as a match agains a
2715 '|'-separated string of extensions, stored in the IPython config
2716 '|'-separated string of extensions, stored in the IPython config
2716 variable win_exec_ext. This defaults to 'exe|com|bat'.
2717 variable win_exec_ext. This defaults to 'exe|com|bat'.
2717
2718
2718 This function also resets the root module cache of module completer,
2719 This function also resets the root module cache of module completer,
2719 used on slow filesystems.
2720 used on slow filesystems.
2720 """
2721 """
2721 from IPython.core.alias import InvalidAliasError
2722 from IPython.core.alias import InvalidAliasError
2722
2723
2723 # for the benefit of module completer in ipy_completers.py
2724 # for the benefit of module completer in ipy_completers.py
2724 del self.db['rootmodules']
2725 del self.db['rootmodules']
2725
2726
2726 path = [os.path.abspath(os.path.expanduser(p)) for p in
2727 path = [os.path.abspath(os.path.expanduser(p)) for p in
2727 os.environ.get('PATH','').split(os.pathsep)]
2728 os.environ.get('PATH','').split(os.pathsep)]
2728 path = filter(os.path.isdir,path)
2729 path = filter(os.path.isdir,path)
2729
2730
2730 syscmdlist = []
2731 syscmdlist = []
2731 # Now define isexec in a cross platform manner.
2732 # Now define isexec in a cross platform manner.
2732 if os.name == 'posix':
2733 if os.name == 'posix':
2733 isexec = lambda fname:os.path.isfile(fname) and \
2734 isexec = lambda fname:os.path.isfile(fname) and \
2734 os.access(fname,os.X_OK)
2735 os.access(fname,os.X_OK)
2735 else:
2736 else:
2736 try:
2737 try:
2737 winext = os.environ['pathext'].replace(';','|').replace('.','')
2738 winext = os.environ['pathext'].replace(';','|').replace('.','')
2738 except KeyError:
2739 except KeyError:
2739 winext = 'exe|com|bat|py'
2740 winext = 'exe|com|bat|py'
2740 if 'py' not in winext:
2741 if 'py' not in winext:
2741 winext += '|py'
2742 winext += '|py'
2742 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2743 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2743 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2744 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2744 savedir = os.getcwd()
2745 savedir = os.getcwd()
2745
2746
2746 # Now walk the paths looking for executables to alias.
2747 # Now walk the paths looking for executables to alias.
2747 try:
2748 try:
2748 # write the whole loop for posix/Windows so we don't have an if in
2749 # write the whole loop for posix/Windows so we don't have an if in
2749 # the innermost part
2750 # the innermost part
2750 if os.name == 'posix':
2751 if os.name == 'posix':
2751 for pdir in path:
2752 for pdir in path:
2752 os.chdir(pdir)
2753 os.chdir(pdir)
2753 for ff in os.listdir(pdir):
2754 for ff in os.listdir(pdir):
2754 if isexec(ff):
2755 if isexec(ff):
2755 try:
2756 try:
2756 # Removes dots from the name since ipython
2757 # Removes dots from the name since ipython
2757 # will assume names with dots to be python.
2758 # will assume names with dots to be python.
2758 self.shell.alias_manager.define_alias(
2759 self.shell.alias_manager.define_alias(
2759 ff.replace('.',''), ff)
2760 ff.replace('.',''), ff)
2760 except InvalidAliasError:
2761 except InvalidAliasError:
2761 pass
2762 pass
2762 else:
2763 else:
2763 syscmdlist.append(ff)
2764 syscmdlist.append(ff)
2764 else:
2765 else:
2765 no_alias = self.shell.alias_manager.no_alias
2766 no_alias = self.shell.alias_manager.no_alias
2766 for pdir in path:
2767 for pdir in path:
2767 os.chdir(pdir)
2768 os.chdir(pdir)
2768 for ff in os.listdir(pdir):
2769 for ff in os.listdir(pdir):
2769 base, ext = os.path.splitext(ff)
2770 base, ext = os.path.splitext(ff)
2770 if isexec(ff) and base.lower() not in no_alias:
2771 if isexec(ff) and base.lower() not in no_alias:
2771 if ext.lower() == '.exe':
2772 if ext.lower() == '.exe':
2772 ff = base
2773 ff = base
2773 try:
2774 try:
2774 # Removes dots from the name since ipython
2775 # Removes dots from the name since ipython
2775 # will assume names with dots to be python.
2776 # will assume names with dots to be python.
2776 self.shell.alias_manager.define_alias(
2777 self.shell.alias_manager.define_alias(
2777 base.lower().replace('.',''), ff)
2778 base.lower().replace('.',''), ff)
2778 except InvalidAliasError:
2779 except InvalidAliasError:
2779 pass
2780 pass
2780 syscmdlist.append(ff)
2781 syscmdlist.append(ff)
2781 db = self.db
2782 db = self.db
2782 db['syscmdlist'] = syscmdlist
2783 db['syscmdlist'] = syscmdlist
2783 finally:
2784 finally:
2784 os.chdir(savedir)
2785 os.chdir(savedir)
2785
2786
2786 def magic_pwd(self, parameter_s = ''):
2787 def magic_pwd(self, parameter_s = ''):
2787 """Return the current working directory path."""
2788 """Return the current working directory path."""
2788 return os.getcwd()
2789 return os.getcwd()
2789
2790
2790 def magic_cd(self, parameter_s=''):
2791 def magic_cd(self, parameter_s=''):
2791 """Change the current working directory.
2792 """Change the current working directory.
2792
2793
2793 This command automatically maintains an internal list of directories
2794 This command automatically maintains an internal list of directories
2794 you visit during your IPython session, in the variable _dh. The
2795 you visit during your IPython session, in the variable _dh. The
2795 command %dhist shows this history nicely formatted. You can also
2796 command %dhist shows this history nicely formatted. You can also
2796 do 'cd -<tab>' to see directory history conveniently.
2797 do 'cd -<tab>' to see directory history conveniently.
2797
2798
2798 Usage:
2799 Usage:
2799
2800
2800 cd 'dir': changes to directory 'dir'.
2801 cd 'dir': changes to directory 'dir'.
2801
2802
2802 cd -: changes to the last visited directory.
2803 cd -: changes to the last visited directory.
2803
2804
2804 cd -<n>: changes to the n-th directory in the directory history.
2805 cd -<n>: changes to the n-th directory in the directory history.
2805
2806
2806 cd --foo: change to directory that matches 'foo' in history
2807 cd --foo: change to directory that matches 'foo' in history
2807
2808
2808 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2809 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2809 (note: cd <bookmark_name> is enough if there is no
2810 (note: cd <bookmark_name> is enough if there is no
2810 directory <bookmark_name>, but a bookmark with the name exists.)
2811 directory <bookmark_name>, but a bookmark with the name exists.)
2811 'cd -b <tab>' allows you to tab-complete bookmark names.
2812 'cd -b <tab>' allows you to tab-complete bookmark names.
2812
2813
2813 Options:
2814 Options:
2814
2815
2815 -q: quiet. Do not print the working directory after the cd command is
2816 -q: quiet. Do not print the working directory after the cd command is
2816 executed. By default IPython's cd command does print this directory,
2817 executed. By default IPython's cd command does print this directory,
2817 since the default prompts do not display path information.
2818 since the default prompts do not display path information.
2818
2819
2819 Note that !cd doesn't work for this purpose because the shell where
2820 Note that !cd doesn't work for this purpose because the shell where
2820 !command runs is immediately discarded after executing 'command'."""
2821 !command runs is immediately discarded after executing 'command'."""
2821
2822
2822 parameter_s = parameter_s.strip()
2823 parameter_s = parameter_s.strip()
2823 #bkms = self.shell.persist.get("bookmarks",{})
2824 #bkms = self.shell.persist.get("bookmarks",{})
2824
2825
2825 oldcwd = os.getcwd()
2826 oldcwd = os.getcwd()
2826 numcd = re.match(r'(-)(\d+)$',parameter_s)
2827 numcd = re.match(r'(-)(\d+)$',parameter_s)
2827 # jump in directory history by number
2828 # jump in directory history by number
2828 if numcd:
2829 if numcd:
2829 nn = int(numcd.group(2))
2830 nn = int(numcd.group(2))
2830 try:
2831 try:
2831 ps = self.shell.user_ns['_dh'][nn]
2832 ps = self.shell.user_ns['_dh'][nn]
2832 except IndexError:
2833 except IndexError:
2833 print 'The requested directory does not exist in history.'
2834 print 'The requested directory does not exist in history.'
2834 return
2835 return
2835 else:
2836 else:
2836 opts = {}
2837 opts = {}
2837 elif parameter_s.startswith('--'):
2838 elif parameter_s.startswith('--'):
2838 ps = None
2839 ps = None
2839 fallback = None
2840 fallback = None
2840 pat = parameter_s[2:]
2841 pat = parameter_s[2:]
2841 dh = self.shell.user_ns['_dh']
2842 dh = self.shell.user_ns['_dh']
2842 # first search only by basename (last component)
2843 # first search only by basename (last component)
2843 for ent in reversed(dh):
2844 for ent in reversed(dh):
2844 if pat in os.path.basename(ent) and os.path.isdir(ent):
2845 if pat in os.path.basename(ent) and os.path.isdir(ent):
2845 ps = ent
2846 ps = ent
2846 break
2847 break
2847
2848
2848 if fallback is None and pat in ent and os.path.isdir(ent):
2849 if fallback is None and pat in ent and os.path.isdir(ent):
2849 fallback = ent
2850 fallback = ent
2850
2851
2851 # if we have no last part match, pick the first full path match
2852 # if we have no last part match, pick the first full path match
2852 if ps is None:
2853 if ps is None:
2853 ps = fallback
2854 ps = fallback
2854
2855
2855 if ps is None:
2856 if ps is None:
2856 print "No matching entry in directory history"
2857 print "No matching entry in directory history"
2857 return
2858 return
2858 else:
2859 else:
2859 opts = {}
2860 opts = {}
2860
2861
2861
2862
2862 else:
2863 else:
2863 #turn all non-space-escaping backslashes to slashes,
2864 #turn all non-space-escaping backslashes to slashes,
2864 # for c:\windows\directory\names\
2865 # for c:\windows\directory\names\
2865 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2866 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2866 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2867 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2867 # jump to previous
2868 # jump to previous
2868 if ps == '-':
2869 if ps == '-':
2869 try:
2870 try:
2870 ps = self.shell.user_ns['_dh'][-2]
2871 ps = self.shell.user_ns['_dh'][-2]
2871 except IndexError:
2872 except IndexError:
2872 raise UsageError('%cd -: No previous directory to change to.')
2873 raise UsageError('%cd -: No previous directory to change to.')
2873 # jump to bookmark if needed
2874 # jump to bookmark if needed
2874 else:
2875 else:
2875 if not os.path.isdir(ps) or opts.has_key('b'):
2876 if not os.path.isdir(ps) or opts.has_key('b'):
2876 bkms = self.db.get('bookmarks', {})
2877 bkms = self.db.get('bookmarks', {})
2877
2878
2878 if bkms.has_key(ps):
2879 if bkms.has_key(ps):
2879 target = bkms[ps]
2880 target = bkms[ps]
2880 print '(bookmark:%s) -> %s' % (ps,target)
2881 print '(bookmark:%s) -> %s' % (ps,target)
2881 ps = target
2882 ps = target
2882 else:
2883 else:
2883 if opts.has_key('b'):
2884 if opts.has_key('b'):
2884 raise UsageError("Bookmark '%s' not found. "
2885 raise UsageError("Bookmark '%s' not found. "
2885 "Use '%%bookmark -l' to see your bookmarks." % ps)
2886 "Use '%%bookmark -l' to see your bookmarks." % ps)
2886
2887
2887 # at this point ps should point to the target dir
2888 # at this point ps should point to the target dir
2888 if ps:
2889 if ps:
2889 try:
2890 try:
2890 os.chdir(os.path.expanduser(ps))
2891 os.chdir(os.path.expanduser(ps))
2891 if self.shell.term_title:
2892 if self.shell.term_title:
2892 set_term_title('IPython: ' + abbrev_cwd())
2893 set_term_title('IPython: ' + abbrev_cwd())
2893 except OSError:
2894 except OSError:
2894 print sys.exc_info()[1]
2895 print sys.exc_info()[1]
2895 else:
2896 else:
2896 cwd = os.getcwd()
2897 cwd = os.getcwd()
2897 dhist = self.shell.user_ns['_dh']
2898 dhist = self.shell.user_ns['_dh']
2898 if oldcwd != cwd:
2899 if oldcwd != cwd:
2899 dhist.append(cwd)
2900 dhist.append(cwd)
2900 self.db['dhist'] = compress_dhist(dhist)[-100:]
2901 self.db['dhist'] = compress_dhist(dhist)[-100:]
2901
2902
2902 else:
2903 else:
2903 os.chdir(self.shell.home_dir)
2904 os.chdir(self.shell.home_dir)
2904 if self.shell.term_title:
2905 if self.shell.term_title:
2905 set_term_title('IPython: ' + '~')
2906 set_term_title('IPython: ' + '~')
2906 cwd = os.getcwd()
2907 cwd = os.getcwd()
2907 dhist = self.shell.user_ns['_dh']
2908 dhist = self.shell.user_ns['_dh']
2908
2909
2909 if oldcwd != cwd:
2910 if oldcwd != cwd:
2910 dhist.append(cwd)
2911 dhist.append(cwd)
2911 self.db['dhist'] = compress_dhist(dhist)[-100:]
2912 self.db['dhist'] = compress_dhist(dhist)[-100:]
2912 if not 'q' in opts and self.shell.user_ns['_dh']:
2913 if not 'q' in opts and self.shell.user_ns['_dh']:
2913 print self.shell.user_ns['_dh'][-1]
2914 print self.shell.user_ns['_dh'][-1]
2914
2915
2915
2916
2916 def magic_env(self, parameter_s=''):
2917 def magic_env(self, parameter_s=''):
2917 """List environment variables."""
2918 """List environment variables."""
2918
2919
2919 return os.environ.data
2920 return os.environ.data
2920
2921
2921 def magic_pushd(self, parameter_s=''):
2922 def magic_pushd(self, parameter_s=''):
2922 """Place the current dir on stack and change directory.
2923 """Place the current dir on stack and change directory.
2923
2924
2924 Usage:\\
2925 Usage:\\
2925 %pushd ['dirname']
2926 %pushd ['dirname']
2926 """
2927 """
2927
2928
2928 dir_s = self.shell.dir_stack
2929 dir_s = self.shell.dir_stack
2929 tgt = os.path.expanduser(parameter_s)
2930 tgt = os.path.expanduser(parameter_s)
2930 cwd = os.getcwd().replace(self.home_dir,'~')
2931 cwd = os.getcwd().replace(self.home_dir,'~')
2931 if tgt:
2932 if tgt:
2932 self.magic_cd(parameter_s)
2933 self.magic_cd(parameter_s)
2933 dir_s.insert(0,cwd)
2934 dir_s.insert(0,cwd)
2934 return self.magic_dirs()
2935 return self.magic_dirs()
2935
2936
2936 def magic_popd(self, parameter_s=''):
2937 def magic_popd(self, parameter_s=''):
2937 """Change to directory popped off the top of the stack.
2938 """Change to directory popped off the top of the stack.
2938 """
2939 """
2939 if not self.shell.dir_stack:
2940 if not self.shell.dir_stack:
2940 raise UsageError("%popd on empty stack")
2941 raise UsageError("%popd on empty stack")
2941 top = self.shell.dir_stack.pop(0)
2942 top = self.shell.dir_stack.pop(0)
2942 self.magic_cd(top)
2943 self.magic_cd(top)
2943 print "popd ->",top
2944 print "popd ->",top
2944
2945
2945 def magic_dirs(self, parameter_s=''):
2946 def magic_dirs(self, parameter_s=''):
2946 """Return the current directory stack."""
2947 """Return the current directory stack."""
2947
2948
2948 return self.shell.dir_stack
2949 return self.shell.dir_stack
2949
2950
2950 def magic_dhist(self, parameter_s=''):
2951 def magic_dhist(self, parameter_s=''):
2951 """Print your history of visited directories.
2952 """Print your history of visited directories.
2952
2953
2953 %dhist -> print full history\\
2954 %dhist -> print full history\\
2954 %dhist n -> print last n entries only\\
2955 %dhist n -> print last n entries only\\
2955 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2956 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2956
2957
2957 This history is automatically maintained by the %cd command, and
2958 This history is automatically maintained by the %cd command, and
2958 always available as the global list variable _dh. You can use %cd -<n>
2959 always available as the global list variable _dh. You can use %cd -<n>
2959 to go to directory number <n>.
2960 to go to directory number <n>.
2960
2961
2961 Note that most of time, you should view directory history by entering
2962 Note that most of time, you should view directory history by entering
2962 cd -<TAB>.
2963 cd -<TAB>.
2963
2964
2964 """
2965 """
2965
2966
2966 dh = self.shell.user_ns['_dh']
2967 dh = self.shell.user_ns['_dh']
2967 if parameter_s:
2968 if parameter_s:
2968 try:
2969 try:
2969 args = map(int,parameter_s.split())
2970 args = map(int,parameter_s.split())
2970 except:
2971 except:
2971 self.arg_err(Magic.magic_dhist)
2972 self.arg_err(Magic.magic_dhist)
2972 return
2973 return
2973 if len(args) == 1:
2974 if len(args) == 1:
2974 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2975 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2975 elif len(args) == 2:
2976 elif len(args) == 2:
2976 ini,fin = args
2977 ini,fin = args
2977 else:
2978 else:
2978 self.arg_err(Magic.magic_dhist)
2979 self.arg_err(Magic.magic_dhist)
2979 return
2980 return
2980 else:
2981 else:
2981 ini,fin = 0,len(dh)
2982 ini,fin = 0,len(dh)
2982 nlprint(dh,
2983 nlprint(dh,
2983 header = 'Directory history (kept in _dh)',
2984 header = 'Directory history (kept in _dh)',
2984 start=ini,stop=fin)
2985 start=ini,stop=fin)
2985
2986
2986 @testdec.skip_doctest
2987 @testdec.skip_doctest
2987 def magic_sc(self, parameter_s=''):
2988 def magic_sc(self, parameter_s=''):
2988 """Shell capture - execute a shell command and capture its output.
2989 """Shell capture - execute a shell command and capture its output.
2989
2990
2990 DEPRECATED. Suboptimal, retained for backwards compatibility.
2991 DEPRECATED. Suboptimal, retained for backwards compatibility.
2991
2992
2992 You should use the form 'var = !command' instead. Example:
2993 You should use the form 'var = !command' instead. Example:
2993
2994
2994 "%sc -l myfiles = ls ~" should now be written as
2995 "%sc -l myfiles = ls ~" should now be written as
2995
2996
2996 "myfiles = !ls ~"
2997 "myfiles = !ls ~"
2997
2998
2998 myfiles.s, myfiles.l and myfiles.n still apply as documented
2999 myfiles.s, myfiles.l and myfiles.n still apply as documented
2999 below.
3000 below.
3000
3001
3001 --
3002 --
3002 %sc [options] varname=command
3003 %sc [options] varname=command
3003
3004
3004 IPython will run the given command using commands.getoutput(), and
3005 IPython will run the given command using commands.getoutput(), and
3005 will then update the user's interactive namespace with a variable
3006 will then update the user's interactive namespace with a variable
3006 called varname, containing the value of the call. Your command can
3007 called varname, containing the value of the call. Your command can
3007 contain shell wildcards, pipes, etc.
3008 contain shell wildcards, pipes, etc.
3008
3009
3009 The '=' sign in the syntax is mandatory, and the variable name you
3010 The '=' sign in the syntax is mandatory, and the variable name you
3010 supply must follow Python's standard conventions for valid names.
3011 supply must follow Python's standard conventions for valid names.
3011
3012
3012 (A special format without variable name exists for internal use)
3013 (A special format without variable name exists for internal use)
3013
3014
3014 Options:
3015 Options:
3015
3016
3016 -l: list output. Split the output on newlines into a list before
3017 -l: list output. Split the output on newlines into a list before
3017 assigning it to the given variable. By default the output is stored
3018 assigning it to the given variable. By default the output is stored
3018 as a single string.
3019 as a single string.
3019
3020
3020 -v: verbose. Print the contents of the variable.
3021 -v: verbose. Print the contents of the variable.
3021
3022
3022 In most cases you should not need to split as a list, because the
3023 In most cases you should not need to split as a list, because the
3023 returned value is a special type of string which can automatically
3024 returned value is a special type of string which can automatically
3024 provide its contents either as a list (split on newlines) or as a
3025 provide its contents either as a list (split on newlines) or as a
3025 space-separated string. These are convenient, respectively, either
3026 space-separated string. These are convenient, respectively, either
3026 for sequential processing or to be passed to a shell command.
3027 for sequential processing or to be passed to a shell command.
3027
3028
3028 For example:
3029 For example:
3029
3030
3030 # all-random
3031 # all-random
3031
3032
3032 # Capture into variable a
3033 # Capture into variable a
3033 In [1]: sc a=ls *py
3034 In [1]: sc a=ls *py
3034
3035
3035 # a is a string with embedded newlines
3036 # a is a string with embedded newlines
3036 In [2]: a
3037 In [2]: a
3037 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3038 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3038
3039
3039 # which can be seen as a list:
3040 # which can be seen as a list:
3040 In [3]: a.l
3041 In [3]: a.l
3041 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3042 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3042
3043
3043 # or as a whitespace-separated string:
3044 # or as a whitespace-separated string:
3044 In [4]: a.s
3045 In [4]: a.s
3045 Out[4]: 'setup.py win32_manual_post_install.py'
3046 Out[4]: 'setup.py win32_manual_post_install.py'
3046
3047
3047 # a.s is useful to pass as a single command line:
3048 # a.s is useful to pass as a single command line:
3048 In [5]: !wc -l $a.s
3049 In [5]: !wc -l $a.s
3049 146 setup.py
3050 146 setup.py
3050 130 win32_manual_post_install.py
3051 130 win32_manual_post_install.py
3051 276 total
3052 276 total
3052
3053
3053 # while the list form is useful to loop over:
3054 # while the list form is useful to loop over:
3054 In [6]: for f in a.l:
3055 In [6]: for f in a.l:
3055 ...: !wc -l $f
3056 ...: !wc -l $f
3056 ...:
3057 ...:
3057 146 setup.py
3058 146 setup.py
3058 130 win32_manual_post_install.py
3059 130 win32_manual_post_install.py
3059
3060
3060 Similiarly, the lists returned by the -l option are also special, in
3061 Similiarly, the lists returned by the -l option are also special, in
3061 the sense that you can equally invoke the .s attribute on them to
3062 the sense that you can equally invoke the .s attribute on them to
3062 automatically get a whitespace-separated string from their contents:
3063 automatically get a whitespace-separated string from their contents:
3063
3064
3064 In [7]: sc -l b=ls *py
3065 In [7]: sc -l b=ls *py
3065
3066
3066 In [8]: b
3067 In [8]: b
3067 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3068 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3068
3069
3069 In [9]: b.s
3070 In [9]: b.s
3070 Out[9]: 'setup.py win32_manual_post_install.py'
3071 Out[9]: 'setup.py win32_manual_post_install.py'
3071
3072
3072 In summary, both the lists and strings used for ouptut capture have
3073 In summary, both the lists and strings used for ouptut capture have
3073 the following special attributes:
3074 the following special attributes:
3074
3075
3075 .l (or .list) : value as list.
3076 .l (or .list) : value as list.
3076 .n (or .nlstr): value as newline-separated string.
3077 .n (or .nlstr): value as newline-separated string.
3077 .s (or .spstr): value as space-separated string.
3078 .s (or .spstr): value as space-separated string.
3078 """
3079 """
3079
3080
3080 opts,args = self.parse_options(parameter_s,'lv')
3081 opts,args = self.parse_options(parameter_s,'lv')
3081 # Try to get a variable name and command to run
3082 # Try to get a variable name and command to run
3082 try:
3083 try:
3083 # the variable name must be obtained from the parse_options
3084 # the variable name must be obtained from the parse_options
3084 # output, which uses shlex.split to strip options out.
3085 # output, which uses shlex.split to strip options out.
3085 var,_ = args.split('=',1)
3086 var,_ = args.split('=',1)
3086 var = var.strip()
3087 var = var.strip()
3087 # But the the command has to be extracted from the original input
3088 # But the the command has to be extracted from the original input
3088 # parameter_s, not on what parse_options returns, to avoid the
3089 # parameter_s, not on what parse_options returns, to avoid the
3089 # quote stripping which shlex.split performs on it.
3090 # quote stripping which shlex.split performs on it.
3090 _,cmd = parameter_s.split('=',1)
3091 _,cmd = parameter_s.split('=',1)
3091 except ValueError:
3092 except ValueError:
3092 var,cmd = '',''
3093 var,cmd = '',''
3093 # If all looks ok, proceed
3094 # If all looks ok, proceed
3094 out,err = self.shell.getoutputerror(cmd)
3095 out,err = self.shell.getoutputerror(cmd)
3095 if err:
3096 if err:
3096 print >> Term.cerr,err
3097 print >> IPython.utils.io.Term.cerr, err
3097 if opts.has_key('l'):
3098 if opts.has_key('l'):
3098 out = SList(out.split('\n'))
3099 out = SList(out.split('\n'))
3099 else:
3100 else:
3100 out = LSString(out)
3101 out = LSString(out)
3101 if opts.has_key('v'):
3102 if opts.has_key('v'):
3102 print '%s ==\n%s' % (var,pformat(out))
3103 print '%s ==\n%s' % (var,pformat(out))
3103 if var:
3104 if var:
3104 self.shell.user_ns.update({var:out})
3105 self.shell.user_ns.update({var:out})
3105 else:
3106 else:
3106 return out
3107 return out
3107
3108
3108 def magic_sx(self, parameter_s=''):
3109 def magic_sx(self, parameter_s=''):
3109 """Shell execute - run a shell command and capture its output.
3110 """Shell execute - run a shell command and capture its output.
3110
3111
3111 %sx command
3112 %sx command
3112
3113
3113 IPython will run the given command using commands.getoutput(), and
3114 IPython will run the given command using commands.getoutput(), and
3114 return the result formatted as a list (split on '\\n'). Since the
3115 return the result formatted as a list (split on '\\n'). Since the
3115 output is _returned_, it will be stored in ipython's regular output
3116 output is _returned_, it will be stored in ipython's regular output
3116 cache Out[N] and in the '_N' automatic variables.
3117 cache Out[N] and in the '_N' automatic variables.
3117
3118
3118 Notes:
3119 Notes:
3119
3120
3120 1) If an input line begins with '!!', then %sx is automatically
3121 1) If an input line begins with '!!', then %sx is automatically
3121 invoked. That is, while:
3122 invoked. That is, while:
3122 !ls
3123 !ls
3123 causes ipython to simply issue system('ls'), typing
3124 causes ipython to simply issue system('ls'), typing
3124 !!ls
3125 !!ls
3125 is a shorthand equivalent to:
3126 is a shorthand equivalent to:
3126 %sx ls
3127 %sx ls
3127
3128
3128 2) %sx differs from %sc in that %sx automatically splits into a list,
3129 2) %sx differs from %sc in that %sx automatically splits into a list,
3129 like '%sc -l'. The reason for this is to make it as easy as possible
3130 like '%sc -l'. The reason for this is to make it as easy as possible
3130 to process line-oriented shell output via further python commands.
3131 to process line-oriented shell output via further python commands.
3131 %sc is meant to provide much finer control, but requires more
3132 %sc is meant to provide much finer control, but requires more
3132 typing.
3133 typing.
3133
3134
3134 3) Just like %sc -l, this is a list with special attributes:
3135 3) Just like %sc -l, this is a list with special attributes:
3135
3136
3136 .l (or .list) : value as list.
3137 .l (or .list) : value as list.
3137 .n (or .nlstr): value as newline-separated string.
3138 .n (or .nlstr): value as newline-separated string.
3138 .s (or .spstr): value as whitespace-separated string.
3139 .s (or .spstr): value as whitespace-separated string.
3139
3140
3140 This is very useful when trying to use such lists as arguments to
3141 This is very useful when trying to use such lists as arguments to
3141 system commands."""
3142 system commands."""
3142
3143
3143 if parameter_s:
3144 if parameter_s:
3144 out,err = self.shell.getoutputerror(parameter_s)
3145 out,err = self.shell.getoutputerror(parameter_s)
3145 if err:
3146 if err:
3146 print >> Term.cerr,err
3147 print >> IPython.utils.io.Term.cerr, err
3147 return SList(out.split('\n'))
3148 return SList(out.split('\n'))
3148
3149
3149 def magic_r(self, parameter_s=''):
3150 def magic_r(self, parameter_s=''):
3150 """Repeat previous input.
3151 """Repeat previous input.
3151
3152
3152 Note: Consider using the more powerfull %rep instead!
3153 Note: Consider using the more powerfull %rep instead!
3153
3154
3154 If given an argument, repeats the previous command which starts with
3155 If given an argument, repeats the previous command which starts with
3155 the same string, otherwise it just repeats the previous input.
3156 the same string, otherwise it just repeats the previous input.
3156
3157
3157 Shell escaped commands (with ! as first character) are not recognized
3158 Shell escaped commands (with ! as first character) are not recognized
3158 by this system, only pure python code and magic commands.
3159 by this system, only pure python code and magic commands.
3159 """
3160 """
3160
3161
3161 start = parameter_s.strip()
3162 start = parameter_s.strip()
3162 esc_magic = ESC_MAGIC
3163 esc_magic = ESC_MAGIC
3163 # Identify magic commands even if automagic is on (which means
3164 # Identify magic commands even if automagic is on (which means
3164 # the in-memory version is different from that typed by the user).
3165 # the in-memory version is different from that typed by the user).
3165 if self.shell.automagic:
3166 if self.shell.automagic:
3166 start_magic = esc_magic+start
3167 start_magic = esc_magic+start
3167 else:
3168 else:
3168 start_magic = start
3169 start_magic = start
3169 # Look through the input history in reverse
3170 # Look through the input history in reverse
3170 for n in range(len(self.shell.input_hist)-2,0,-1):
3171 for n in range(len(self.shell.input_hist)-2,0,-1):
3171 input = self.shell.input_hist[n]
3172 input = self.shell.input_hist[n]
3172 # skip plain 'r' lines so we don't recurse to infinity
3173 # skip plain 'r' lines so we don't recurse to infinity
3173 if input != '_ip.magic("r")\n' and \
3174 if input != '_ip.magic("r")\n' and \
3174 (input.startswith(start) or input.startswith(start_magic)):
3175 (input.startswith(start) or input.startswith(start_magic)):
3175 #print 'match',`input` # dbg
3176 #print 'match',`input` # dbg
3176 print 'Executing:',input,
3177 print 'Executing:',input,
3177 self.shell.runlines(input)
3178 self.shell.runlines(input)
3178 return
3179 return
3179 print 'No previous input matching `%s` found.' % start
3180 print 'No previous input matching `%s` found.' % start
3180
3181
3181
3182
3182 def magic_bookmark(self, parameter_s=''):
3183 def magic_bookmark(self, parameter_s=''):
3183 """Manage IPython's bookmark system.
3184 """Manage IPython's bookmark system.
3184
3185
3185 %bookmark <name> - set bookmark to current dir
3186 %bookmark <name> - set bookmark to current dir
3186 %bookmark <name> <dir> - set bookmark to <dir>
3187 %bookmark <name> <dir> - set bookmark to <dir>
3187 %bookmark -l - list all bookmarks
3188 %bookmark -l - list all bookmarks
3188 %bookmark -d <name> - remove bookmark
3189 %bookmark -d <name> - remove bookmark
3189 %bookmark -r - remove all bookmarks
3190 %bookmark -r - remove all bookmarks
3190
3191
3191 You can later on access a bookmarked folder with:
3192 You can later on access a bookmarked folder with:
3192 %cd -b <name>
3193 %cd -b <name>
3193 or simply '%cd <name>' if there is no directory called <name> AND
3194 or simply '%cd <name>' if there is no directory called <name> AND
3194 there is such a bookmark defined.
3195 there is such a bookmark defined.
3195
3196
3196 Your bookmarks persist through IPython sessions, but they are
3197 Your bookmarks persist through IPython sessions, but they are
3197 associated with each profile."""
3198 associated with each profile."""
3198
3199
3199 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3200 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3200 if len(args) > 2:
3201 if len(args) > 2:
3201 raise UsageError("%bookmark: too many arguments")
3202 raise UsageError("%bookmark: too many arguments")
3202
3203
3203 bkms = self.db.get('bookmarks',{})
3204 bkms = self.db.get('bookmarks',{})
3204
3205
3205 if opts.has_key('d'):
3206 if opts.has_key('d'):
3206 try:
3207 try:
3207 todel = args[0]
3208 todel = args[0]
3208 except IndexError:
3209 except IndexError:
3209 raise UsageError(
3210 raise UsageError(
3210 "%bookmark -d: must provide a bookmark to delete")
3211 "%bookmark -d: must provide a bookmark to delete")
3211 else:
3212 else:
3212 try:
3213 try:
3213 del bkms[todel]
3214 del bkms[todel]
3214 except KeyError:
3215 except KeyError:
3215 raise UsageError(
3216 raise UsageError(
3216 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3217 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3217
3218
3218 elif opts.has_key('r'):
3219 elif opts.has_key('r'):
3219 bkms = {}
3220 bkms = {}
3220 elif opts.has_key('l'):
3221 elif opts.has_key('l'):
3221 bks = bkms.keys()
3222 bks = bkms.keys()
3222 bks.sort()
3223 bks.sort()
3223 if bks:
3224 if bks:
3224 size = max(map(len,bks))
3225 size = max(map(len,bks))
3225 else:
3226 else:
3226 size = 0
3227 size = 0
3227 fmt = '%-'+str(size)+'s -> %s'
3228 fmt = '%-'+str(size)+'s -> %s'
3228 print 'Current bookmarks:'
3229 print 'Current bookmarks:'
3229 for bk in bks:
3230 for bk in bks:
3230 print fmt % (bk,bkms[bk])
3231 print fmt % (bk,bkms[bk])
3231 else:
3232 else:
3232 if not args:
3233 if not args:
3233 raise UsageError("%bookmark: You must specify the bookmark name")
3234 raise UsageError("%bookmark: You must specify the bookmark name")
3234 elif len(args)==1:
3235 elif len(args)==1:
3235 bkms[args[0]] = os.getcwd()
3236 bkms[args[0]] = os.getcwd()
3236 elif len(args)==2:
3237 elif len(args)==2:
3237 bkms[args[0]] = args[1]
3238 bkms[args[0]] = args[1]
3238 self.db['bookmarks'] = bkms
3239 self.db['bookmarks'] = bkms
3239
3240
3240 def magic_pycat(self, parameter_s=''):
3241 def magic_pycat(self, parameter_s=''):
3241 """Show a syntax-highlighted file through a pager.
3242 """Show a syntax-highlighted file through a pager.
3242
3243
3243 This magic is similar to the cat utility, but it will assume the file
3244 This magic is similar to the cat utility, but it will assume the file
3244 to be Python source and will show it with syntax highlighting. """
3245 to be Python source and will show it with syntax highlighting. """
3245
3246
3246 try:
3247 try:
3247 filename = get_py_filename(parameter_s)
3248 filename = get_py_filename(parameter_s)
3248 cont = file_read(filename)
3249 cont = file_read(filename)
3249 except IOError:
3250 except IOError:
3250 try:
3251 try:
3251 cont = eval(parameter_s,self.user_ns)
3252 cont = eval(parameter_s,self.user_ns)
3252 except NameError:
3253 except NameError:
3253 cont = None
3254 cont = None
3254 if cont is None:
3255 if cont is None:
3255 print "Error: no such file or variable"
3256 print "Error: no such file or variable"
3256 return
3257 return
3257
3258
3258 page(self.shell.pycolorize(cont),
3259 page(self.shell.pycolorize(cont),
3259 screen_lines=self.shell.usable_screen_length)
3260 screen_lines=self.shell.usable_screen_length)
3260
3261
3261 def _rerun_pasted(self):
3262 def _rerun_pasted(self):
3262 """ Rerun a previously pasted command.
3263 """ Rerun a previously pasted command.
3263 """
3264 """
3264 b = self.user_ns.get('pasted_block', None)
3265 b = self.user_ns.get('pasted_block', None)
3265 if b is None:
3266 if b is None:
3266 raise UsageError('No previous pasted block available')
3267 raise UsageError('No previous pasted block available')
3267 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3268 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3268 exec b in self.user_ns
3269 exec b in self.user_ns
3269
3270
3270 def _get_pasted_lines(self, sentinel):
3271 def _get_pasted_lines(self, sentinel):
3271 """ Yield pasted lines until the user enters the given sentinel value.
3272 """ Yield pasted lines until the user enters the given sentinel value.
3272 """
3273 """
3273 from IPython.core import interactiveshell
3274 from IPython.core import interactiveshell
3274 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3275 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3275 while True:
3276 while True:
3276 l = interactiveshell.raw_input_original(':')
3277 l = interactiveshell.raw_input_original(':')
3277 if l == sentinel:
3278 if l == sentinel:
3278 return
3279 return
3279 else:
3280 else:
3280 yield l
3281 yield l
3281
3282
3282 def _strip_pasted_lines_for_code(self, raw_lines):
3283 def _strip_pasted_lines_for_code(self, raw_lines):
3283 """ Strip non-code parts of a sequence of lines to return a block of
3284 """ Strip non-code parts of a sequence of lines to return a block of
3284 code.
3285 code.
3285 """
3286 """
3286 # Regular expressions that declare text we strip from the input:
3287 # Regular expressions that declare text we strip from the input:
3287 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3288 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3288 r'^\s*(\s?>)+', # Python input prompt
3289 r'^\s*(\s?>)+', # Python input prompt
3289 r'^\s*\.{3,}', # Continuation prompts
3290 r'^\s*\.{3,}', # Continuation prompts
3290 r'^\++',
3291 r'^\++',
3291 ]
3292 ]
3292
3293
3293 strip_from_start = map(re.compile,strip_re)
3294 strip_from_start = map(re.compile,strip_re)
3294
3295
3295 lines = []
3296 lines = []
3296 for l in raw_lines:
3297 for l in raw_lines:
3297 for pat in strip_from_start:
3298 for pat in strip_from_start:
3298 l = pat.sub('',l)
3299 l = pat.sub('',l)
3299 lines.append(l)
3300 lines.append(l)
3300
3301
3301 block = "\n".join(lines) + '\n'
3302 block = "\n".join(lines) + '\n'
3302 #print "block:\n",block
3303 #print "block:\n",block
3303 return block
3304 return block
3304
3305
3305 def _execute_block(self, block, par):
3306 def _execute_block(self, block, par):
3306 """ Execute a block, or store it in a variable, per the user's request.
3307 """ Execute a block, or store it in a variable, per the user's request.
3307 """
3308 """
3308 if not par:
3309 if not par:
3309 b = textwrap.dedent(block)
3310 b = textwrap.dedent(block)
3310 self.user_ns['pasted_block'] = b
3311 self.user_ns['pasted_block'] = b
3311 exec b in self.user_ns
3312 exec b in self.user_ns
3312 else:
3313 else:
3313 self.user_ns[par] = SList(block.splitlines())
3314 self.user_ns[par] = SList(block.splitlines())
3314 print "Block assigned to '%s'" % par
3315 print "Block assigned to '%s'" % par
3315
3316
3316 def magic_cpaste(self, parameter_s=''):
3317 def magic_cpaste(self, parameter_s=''):
3317 """Allows you to paste & execute a pre-formatted code block from clipboard.
3318 """Allows you to paste & execute a pre-formatted code block from clipboard.
3318
3319
3319 You must terminate the block with '--' (two minus-signs) alone on the
3320 You must terminate the block with '--' (two minus-signs) alone on the
3320 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3321 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3321 is the new sentinel for this operation)
3322 is the new sentinel for this operation)
3322
3323
3323 The block is dedented prior to execution to enable execution of method
3324 The block is dedented prior to execution to enable execution of method
3324 definitions. '>' and '+' characters at the beginning of a line are
3325 definitions. '>' and '+' characters at the beginning of a line are
3325 ignored, to allow pasting directly from e-mails, diff files and
3326 ignored, to allow pasting directly from e-mails, diff files and
3326 doctests (the '...' continuation prompt is also stripped). The
3327 doctests (the '...' continuation prompt is also stripped). The
3327 executed block is also assigned to variable named 'pasted_block' for
3328 executed block is also assigned to variable named 'pasted_block' for
3328 later editing with '%edit pasted_block'.
3329 later editing with '%edit pasted_block'.
3329
3330
3330 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3331 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3331 This assigns the pasted block to variable 'foo' as string, without
3332 This assigns the pasted block to variable 'foo' as string, without
3332 dedenting or executing it (preceding >>> and + is still stripped)
3333 dedenting or executing it (preceding >>> and + is still stripped)
3333
3334
3334 '%cpaste -r' re-executes the block previously entered by cpaste.
3335 '%cpaste -r' re-executes the block previously entered by cpaste.
3335
3336
3336 Do not be alarmed by garbled output on Windows (it's a readline bug).
3337 Do not be alarmed by garbled output on Windows (it's a readline bug).
3337 Just press enter and type -- (and press enter again) and the block
3338 Just press enter and type -- (and press enter again) and the block
3338 will be what was just pasted.
3339 will be what was just pasted.
3339
3340
3340 IPython statements (magics, shell escapes) are not supported (yet).
3341 IPython statements (magics, shell escapes) are not supported (yet).
3341
3342
3342 See also
3343 See also
3343 --------
3344 --------
3344 paste: automatically pull code from clipboard.
3345 paste: automatically pull code from clipboard.
3345 """
3346 """
3346
3347
3347 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3348 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3348 par = args.strip()
3349 par = args.strip()
3349 if opts.has_key('r'):
3350 if opts.has_key('r'):
3350 self._rerun_pasted()
3351 self._rerun_pasted()
3351 return
3352 return
3352
3353
3353 sentinel = opts.get('s','--')
3354 sentinel = opts.get('s','--')
3354
3355
3355 block = self._strip_pasted_lines_for_code(
3356 block = self._strip_pasted_lines_for_code(
3356 self._get_pasted_lines(sentinel))
3357 self._get_pasted_lines(sentinel))
3357
3358
3358 self._execute_block(block, par)
3359 self._execute_block(block, par)
3359
3360
3360 def magic_paste(self, parameter_s=''):
3361 def magic_paste(self, parameter_s=''):
3361 """Allows you to paste & execute a pre-formatted code block from clipboard.
3362 """Allows you to paste & execute a pre-formatted code block from clipboard.
3362
3363
3363 The text is pulled directly from the clipboard without user
3364 The text is pulled directly from the clipboard without user
3364 intervention and printed back on the screen before execution (unless
3365 intervention and printed back on the screen before execution (unless
3365 the -q flag is given to force quiet mode).
3366 the -q flag is given to force quiet mode).
3366
3367
3367 The block is dedented prior to execution to enable execution of method
3368 The block is dedented prior to execution to enable execution of method
3368 definitions. '>' and '+' characters at the beginning of a line are
3369 definitions. '>' and '+' characters at the beginning of a line are
3369 ignored, to allow pasting directly from e-mails, diff files and
3370 ignored, to allow pasting directly from e-mails, diff files and
3370 doctests (the '...' continuation prompt is also stripped). The
3371 doctests (the '...' continuation prompt is also stripped). The
3371 executed block is also assigned to variable named 'pasted_block' for
3372 executed block is also assigned to variable named 'pasted_block' for
3372 later editing with '%edit pasted_block'.
3373 later editing with '%edit pasted_block'.
3373
3374
3374 You can also pass a variable name as an argument, e.g. '%paste foo'.
3375 You can also pass a variable name as an argument, e.g. '%paste foo'.
3375 This assigns the pasted block to variable 'foo' as string, without
3376 This assigns the pasted block to variable 'foo' as string, without
3376 dedenting or executing it (preceding >>> and + is still stripped)
3377 dedenting or executing it (preceding >>> and + is still stripped)
3377
3378
3378 Options
3379 Options
3379 -------
3380 -------
3380
3381
3381 -r: re-executes the block previously entered by cpaste.
3382 -r: re-executes the block previously entered by cpaste.
3382
3383
3383 -q: quiet mode: do not echo the pasted text back to the terminal.
3384 -q: quiet mode: do not echo the pasted text back to the terminal.
3384
3385
3385 IPython statements (magics, shell escapes) are not supported (yet).
3386 IPython statements (magics, shell escapes) are not supported (yet).
3386
3387
3387 See also
3388 See also
3388 --------
3389 --------
3389 cpaste: manually paste code into terminal until you mark its end.
3390 cpaste: manually paste code into terminal until you mark its end.
3390 """
3391 """
3391 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3392 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3392 par = args.strip()
3393 par = args.strip()
3393 if opts.has_key('r'):
3394 if opts.has_key('r'):
3394 self._rerun_pasted()
3395 self._rerun_pasted()
3395 return
3396 return
3396
3397
3397 text = self.shell.hooks.clipboard_get()
3398 text = self.shell.hooks.clipboard_get()
3398 block = self._strip_pasted_lines_for_code(text.splitlines())
3399 block = self._strip_pasted_lines_for_code(text.splitlines())
3399
3400
3400 # By default, echo back to terminal unless quiet mode is requested
3401 # By default, echo back to terminal unless quiet mode is requested
3401 if not opts.has_key('q'):
3402 if not opts.has_key('q'):
3402 write = self.shell.write
3403 write = self.shell.write
3403 write(self.shell.pycolorize(block))
3404 write(self.shell.pycolorize(block))
3404 if not block.endswith('\n'):
3405 if not block.endswith('\n'):
3405 write('\n')
3406 write('\n')
3406 write("## -- End pasted text --\n")
3407 write("## -- End pasted text --\n")
3407
3408
3408 self._execute_block(block, par)
3409 self._execute_block(block, par)
3409
3410
3410 def magic_quickref(self,arg):
3411 def magic_quickref(self,arg):
3411 """ Show a quick reference sheet """
3412 """ Show a quick reference sheet """
3412 import IPython.core.usage
3413 import IPython.core.usage
3413 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3414 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3414
3415
3415 page(qr)
3416 page(qr)
3416
3417
3417 def magic_doctest_mode(self,parameter_s=''):
3418 def magic_doctest_mode(self,parameter_s=''):
3418 """Toggle doctest mode on and off.
3419 """Toggle doctest mode on and off.
3419
3420
3420 This mode allows you to toggle the prompt behavior between normal
3421 This mode allows you to toggle the prompt behavior between normal
3421 IPython prompts and ones that are as similar to the default IPython
3422 IPython prompts and ones that are as similar to the default IPython
3422 interpreter as possible.
3423 interpreter as possible.
3423
3424
3424 It also supports the pasting of code snippets that have leading '>>>'
3425 It also supports the pasting of code snippets that have leading '>>>'
3425 and '...' prompts in them. This means that you can paste doctests from
3426 and '...' prompts in them. This means that you can paste doctests from
3426 files or docstrings (even if they have leading whitespace), and the
3427 files or docstrings (even if they have leading whitespace), and the
3427 code will execute correctly. You can then use '%history -tn' to see
3428 code will execute correctly. You can then use '%history -tn' to see
3428 the translated history without line numbers; this will give you the
3429 the translated history without line numbers; this will give you the
3429 input after removal of all the leading prompts and whitespace, which
3430 input after removal of all the leading prompts and whitespace, which
3430 can be pasted back into an editor.
3431 can be pasted back into an editor.
3431
3432
3432 With these features, you can switch into this mode easily whenever you
3433 With these features, you can switch into this mode easily whenever you
3433 need to do testing and changes to doctests, without having to leave
3434 need to do testing and changes to doctests, without having to leave
3434 your existing IPython session.
3435 your existing IPython session.
3435 """
3436 """
3436
3437
3437 from IPython.utils.ipstruct import Struct
3438 from IPython.utils.ipstruct import Struct
3438
3439
3439 # Shorthands
3440 # Shorthands
3440 shell = self.shell
3441 shell = self.shell
3441 oc = shell.outputcache
3442 oc = shell.outputcache
3442 meta = shell.meta
3443 meta = shell.meta
3443 # dstore is a data store kept in the instance metadata bag to track any
3444 # dstore is a data store kept in the instance metadata bag to track any
3444 # changes we make, so we can undo them later.
3445 # changes we make, so we can undo them later.
3445 dstore = meta.setdefault('doctest_mode',Struct())
3446 dstore = meta.setdefault('doctest_mode',Struct())
3446 save_dstore = dstore.setdefault
3447 save_dstore = dstore.setdefault
3447
3448
3448 # save a few values we'll need to recover later
3449 # save a few values we'll need to recover later
3449 mode = save_dstore('mode',False)
3450 mode = save_dstore('mode',False)
3450 save_dstore('rc_pprint',shell.pprint)
3451 save_dstore('rc_pprint',shell.pprint)
3451 save_dstore('xmode',shell.InteractiveTB.mode)
3452 save_dstore('xmode',shell.InteractiveTB.mode)
3452 save_dstore('rc_separate_out',shell.separate_out)
3453 save_dstore('rc_separate_out',shell.separate_out)
3453 save_dstore('rc_separate_out2',shell.separate_out2)
3454 save_dstore('rc_separate_out2',shell.separate_out2)
3454 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3455 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3455 save_dstore('rc_separate_in',shell.separate_in)
3456 save_dstore('rc_separate_in',shell.separate_in)
3456
3457
3457 if mode == False:
3458 if mode == False:
3458 # turn on
3459 # turn on
3459 oc.prompt1.p_template = '>>> '
3460 oc.prompt1.p_template = '>>> '
3460 oc.prompt2.p_template = '... '
3461 oc.prompt2.p_template = '... '
3461 oc.prompt_out.p_template = ''
3462 oc.prompt_out.p_template = ''
3462
3463
3463 # Prompt separators like plain python
3464 # Prompt separators like plain python
3464 oc.input_sep = oc.prompt1.sep = ''
3465 oc.input_sep = oc.prompt1.sep = ''
3465 oc.output_sep = ''
3466 oc.output_sep = ''
3466 oc.output_sep2 = ''
3467 oc.output_sep2 = ''
3467
3468
3468 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3469 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3469 oc.prompt_out.pad_left = False
3470 oc.prompt_out.pad_left = False
3470
3471
3471 shell.pprint = False
3472 shell.pprint = False
3472
3473
3473 shell.magic_xmode('Plain')
3474 shell.magic_xmode('Plain')
3474
3475
3475 else:
3476 else:
3476 # turn off
3477 # turn off
3477 oc.prompt1.p_template = shell.prompt_in1
3478 oc.prompt1.p_template = shell.prompt_in1
3478 oc.prompt2.p_template = shell.prompt_in2
3479 oc.prompt2.p_template = shell.prompt_in2
3479 oc.prompt_out.p_template = shell.prompt_out
3480 oc.prompt_out.p_template = shell.prompt_out
3480
3481
3481 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3482 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3482
3483
3483 oc.output_sep = dstore.rc_separate_out
3484 oc.output_sep = dstore.rc_separate_out
3484 oc.output_sep2 = dstore.rc_separate_out2
3485 oc.output_sep2 = dstore.rc_separate_out2
3485
3486
3486 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3487 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3487 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3488 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3488
3489
3489 shell.pprint = dstore.rc_pprint
3490 shell.pprint = dstore.rc_pprint
3490
3491
3491 shell.magic_xmode(dstore.xmode)
3492 shell.magic_xmode(dstore.xmode)
3492
3493
3493 # Store new mode and inform
3494 # Store new mode and inform
3494 dstore.mode = bool(1-int(mode))
3495 dstore.mode = bool(1-int(mode))
3495 print 'Doctest mode is:',
3496 print 'Doctest mode is:',
3496 print ['OFF','ON'][dstore.mode]
3497 print ['OFF','ON'][dstore.mode]
3497
3498
3498 def magic_gui(self, parameter_s=''):
3499 def magic_gui(self, parameter_s=''):
3499 """Enable or disable IPython GUI event loop integration.
3500 """Enable or disable IPython GUI event loop integration.
3500
3501
3501 %gui [-a] [GUINAME]
3502 %gui [-a] [GUINAME]
3502
3503
3503 This magic replaces IPython's threaded shells that were activated
3504 This magic replaces IPython's threaded shells that were activated
3504 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3505 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3505 can now be enabled, disabled and swtiched at runtime and keyboard
3506 can now be enabled, disabled and swtiched at runtime and keyboard
3506 interrupts should work without any problems. The following toolkits
3507 interrupts should work without any problems. The following toolkits
3507 are supported: wxPython, PyQt4, PyGTK, and Tk::
3508 are supported: wxPython, PyQt4, PyGTK, and Tk::
3508
3509
3509 %gui wx # enable wxPython event loop integration
3510 %gui wx # enable wxPython event loop integration
3510 %gui qt4|qt # enable PyQt4 event loop integration
3511 %gui qt4|qt # enable PyQt4 event loop integration
3511 %gui gtk # enable PyGTK event loop integration
3512 %gui gtk # enable PyGTK event loop integration
3512 %gui tk # enable Tk event loop integration
3513 %gui tk # enable Tk event loop integration
3513 %gui # disable all event loop integration
3514 %gui # disable all event loop integration
3514
3515
3515 WARNING: after any of these has been called you can simply create
3516 WARNING: after any of these has been called you can simply create
3516 an application object, but DO NOT start the event loop yourself, as
3517 an application object, but DO NOT start the event loop yourself, as
3517 we have already handled that.
3518 we have already handled that.
3518
3519
3519 If you want us to create an appropriate application object add the
3520 If you want us to create an appropriate application object add the
3520 "-a" flag to your command::
3521 "-a" flag to your command::
3521
3522
3522 %gui -a wx
3523 %gui -a wx
3523
3524
3524 This is highly recommended for most users.
3525 This is highly recommended for most users.
3525 """
3526 """
3526 opts, arg = self.parse_options(parameter_s,'a')
3527 opts, arg = self.parse_options(parameter_s,'a')
3527 if arg=='': arg = None
3528 if arg=='': arg = None
3528 return enable_gui(arg, 'a' in opts)
3529 return enable_gui(arg, 'a' in opts)
3529
3530
3530 def magic_load_ext(self, module_str):
3531 def magic_load_ext(self, module_str):
3531 """Load an IPython extension by its module name."""
3532 """Load an IPython extension by its module name."""
3532 return self.extension_manager.load_extension(module_str)
3533 return self.extension_manager.load_extension(module_str)
3533
3534
3534 def magic_unload_ext(self, module_str):
3535 def magic_unload_ext(self, module_str):
3535 """Unload an IPython extension by its module name."""
3536 """Unload an IPython extension by its module name."""
3536 self.extension_manager.unload_extension(module_str)
3537 self.extension_manager.unload_extension(module_str)
3537
3538
3538 def magic_reload_ext(self, module_str):
3539 def magic_reload_ext(self, module_str):
3539 """Reload an IPython extension by its module name."""
3540 """Reload an IPython extension by its module name."""
3540 self.extension_manager.reload_extension(module_str)
3541 self.extension_manager.reload_extension(module_str)
3541
3542
3542 @testdec.skip_doctest
3543 @testdec.skip_doctest
3543 def magic_install_profiles(self, s):
3544 def magic_install_profiles(self, s):
3544 """Install the default IPython profiles into the .ipython dir.
3545 """Install the default IPython profiles into the .ipython dir.
3545
3546
3546 If the default profiles have already been installed, they will not
3547 If the default profiles have already been installed, they will not
3547 be overwritten. You can force overwriting them by using the ``-o``
3548 be overwritten. You can force overwriting them by using the ``-o``
3548 option::
3549 option::
3549
3550
3550 In [1]: %install_profiles -o
3551 In [1]: %install_profiles -o
3551 """
3552 """
3552 if '-o' in s:
3553 if '-o' in s:
3553 overwrite = True
3554 overwrite = True
3554 else:
3555 else:
3555 overwrite = False
3556 overwrite = False
3556 from IPython.config import profile
3557 from IPython.config import profile
3557 profile_dir = os.path.split(profile.__file__)[0]
3558 profile_dir = os.path.split(profile.__file__)[0]
3558 ipython_dir = self.ipython_dir
3559 ipython_dir = self.ipython_dir
3559 files = os.listdir(profile_dir)
3560 files = os.listdir(profile_dir)
3560
3561
3561 to_install = []
3562 to_install = []
3562 for f in files:
3563 for f in files:
3563 if f.startswith('ipython_config'):
3564 if f.startswith('ipython_config'):
3564 src = os.path.join(profile_dir, f)
3565 src = os.path.join(profile_dir, f)
3565 dst = os.path.join(ipython_dir, f)
3566 dst = os.path.join(ipython_dir, f)
3566 if (not os.path.isfile(dst)) or overwrite:
3567 if (not os.path.isfile(dst)) or overwrite:
3567 to_install.append((f, src, dst))
3568 to_install.append((f, src, dst))
3568 if len(to_install)>0:
3569 if len(to_install)>0:
3569 print "Installing profiles to: ", ipython_dir
3570 print "Installing profiles to: ", ipython_dir
3570 for (f, src, dst) in to_install:
3571 for (f, src, dst) in to_install:
3571 shutil.copy(src, dst)
3572 shutil.copy(src, dst)
3572 print " %s" % f
3573 print " %s" % f
3573
3574
3574 def magic_install_default_config(self, s):
3575 def magic_install_default_config(self, s):
3575 """Install IPython's default config file into the .ipython dir.
3576 """Install IPython's default config file into the .ipython dir.
3576
3577
3577 If the default config file (:file:`ipython_config.py`) is already
3578 If the default config file (:file:`ipython_config.py`) is already
3578 installed, it will not be overwritten. You can force overwriting
3579 installed, it will not be overwritten. You can force overwriting
3579 by using the ``-o`` option::
3580 by using the ``-o`` option::
3580
3581
3581 In [1]: %install_default_config
3582 In [1]: %install_default_config
3582 """
3583 """
3583 if '-o' in s:
3584 if '-o' in s:
3584 overwrite = True
3585 overwrite = True
3585 else:
3586 else:
3586 overwrite = False
3587 overwrite = False
3587 from IPython.config import default
3588 from IPython.config import default
3588 config_dir = os.path.split(default.__file__)[0]
3589 config_dir = os.path.split(default.__file__)[0]
3589 ipython_dir = self.ipython_dir
3590 ipython_dir = self.ipython_dir
3590 default_config_file_name = 'ipython_config.py'
3591 default_config_file_name = 'ipython_config.py'
3591 src = os.path.join(config_dir, default_config_file_name)
3592 src = os.path.join(config_dir, default_config_file_name)
3592 dst = os.path.join(ipython_dir, default_config_file_name)
3593 dst = os.path.join(ipython_dir, default_config_file_name)
3593 if (not os.path.isfile(dst)) or overwrite:
3594 if (not os.path.isfile(dst)) or overwrite:
3594 shutil.copy(src, dst)
3595 shutil.copy(src, dst)
3595 print "Installing default config file: %s" % dst
3596 print "Installing default config file: %s" % dst
3596
3597
3597 # Pylab support: simple wrappers that activate pylab, load gui input
3598 # Pylab support: simple wrappers that activate pylab, load gui input
3598 # handling and modify slightly %run
3599 # handling and modify slightly %run
3599
3600
3600 @testdec.skip_doctest
3601 @testdec.skip_doctest
3601 def _pylab_magic_run(self, parameter_s=''):
3602 def _pylab_magic_run(self, parameter_s=''):
3602 Magic.magic_run(self, parameter_s,
3603 Magic.magic_run(self, parameter_s,
3603 runner=mpl_runner(self.shell.safe_execfile))
3604 runner=mpl_runner(self.shell.safe_execfile))
3604
3605
3605 _pylab_magic_run.__doc__ = magic_run.__doc__
3606 _pylab_magic_run.__doc__ = magic_run.__doc__
3606
3607
3607 @testdec.skip_doctest
3608 @testdec.skip_doctest
3608 def magic_pylab(self, s):
3609 def magic_pylab(self, s):
3609 """Load numpy and matplotlib to work interactively.
3610 """Load numpy and matplotlib to work interactively.
3610
3611
3611 %pylab [GUINAME]
3612 %pylab [GUINAME]
3612
3613
3613 This function lets you activate pylab (matplotlib, numpy and
3614 This function lets you activate pylab (matplotlib, numpy and
3614 interactive support) at any point during an IPython session.
3615 interactive support) at any point during an IPython session.
3615
3616
3616 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3617 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3617 pylab and mlab, as well as all names from numpy and pylab.
3618 pylab and mlab, as well as all names from numpy and pylab.
3618
3619
3619 Parameters
3620 Parameters
3620 ----------
3621 ----------
3621 guiname : optional
3622 guiname : optional
3622 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3623 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3623 'tk'). If given, the corresponding Matplotlib backend is used,
3624 'tk'). If given, the corresponding Matplotlib backend is used,
3624 otherwise matplotlib's default (which you can override in your
3625 otherwise matplotlib's default (which you can override in your
3625 matplotlib config file) is used.
3626 matplotlib config file) is used.
3626
3627
3627 Examples
3628 Examples
3628 --------
3629 --------
3629 In this case, where the MPL default is TkAgg:
3630 In this case, where the MPL default is TkAgg:
3630 In [2]: %pylab
3631 In [2]: %pylab
3631
3632
3632 Welcome to pylab, a matplotlib-based Python environment.
3633 Welcome to pylab, a matplotlib-based Python environment.
3633 Backend in use: TkAgg
3634 Backend in use: TkAgg
3634 For more information, type 'help(pylab)'.
3635 For more information, type 'help(pylab)'.
3635
3636
3636 But you can explicitly request a different backend:
3637 But you can explicitly request a different backend:
3637 In [3]: %pylab qt
3638 In [3]: %pylab qt
3638
3639
3639 Welcome to pylab, a matplotlib-based Python environment.
3640 Welcome to pylab, a matplotlib-based Python environment.
3640 Backend in use: Qt4Agg
3641 Backend in use: Qt4Agg
3641 For more information, type 'help(pylab)'.
3642 For more information, type 'help(pylab)'.
3642 """
3643 """
3643 self.shell.enable_pylab(s)
3644 self.shell.enable_pylab(s)
3644
3645
3645 def magic_tb(self, s):
3646 def magic_tb(self, s):
3646 """Print the last traceback with the currently active exception mode.
3647 """Print the last traceback with the currently active exception mode.
3647
3648
3648 See %xmode for changing exception reporting modes."""
3649 See %xmode for changing exception reporting modes."""
3649 self.shell.showtraceback()
3650 self.shell.showtraceback()
3650
3651
3651 # end Magic
3652 # end Magic
@@ -1,609 +1,609 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tools for inspecting Python objects.
2 """Tools for inspecting Python objects.
3
3
4 Uses syntax highlighting for presenting the various information elements.
4 Uses syntax highlighting for presenting the various information elements.
5
5
6 Similar in spirit to the inspect module, but all calls take a name argument to
6 Similar in spirit to the inspect module, but all calls take a name argument to
7 reference the name under which an object is being read.
7 reference the name under which an object is being read.
8 """
8 """
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
11 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
15 #*****************************************************************************
16
16
17 __all__ = ['Inspector','InspectColors']
17 __all__ = ['Inspector','InspectColors']
18
18
19 # stdlib modules
19 # stdlib modules
20 import __builtin__
20 import __builtin__
21 import StringIO
21 import StringIO
22 import inspect
22 import inspect
23 import linecache
23 import linecache
24 import os
24 import os
25 import string
25 import string
26 import sys
26 import sys
27 import types
27 import types
28
28
29 # IPython's own
29 # IPython's own
30 from IPython.core.page import page
30 from IPython.core.page import page
31 from IPython.external.Itpl import itpl
31 from IPython.external.Itpl import itpl
32 from IPython.utils import PyColorize
32 from IPython.utils import PyColorize
33 from IPython.utils.io import Term
33 import IPython.utils.io
34 from IPython.utils.text import indent
34 from IPython.utils.text import indent
35 from IPython.utils.wildcard import list_namespace
35 from IPython.utils.wildcard import list_namespace
36 from IPython.utils.coloransi import *
36 from IPython.utils.coloransi import *
37
37
38 #****************************************************************************
38 #****************************************************************************
39 # HACK!!! This is a crude fix for bugs in python 2.3's inspect module. We
39 # HACK!!! This is a crude fix for bugs in python 2.3's inspect module. We
40 # simply monkeypatch inspect with code copied from python 2.4.
40 # simply monkeypatch inspect with code copied from python 2.4.
41 if sys.version_info[:2] == (2,3):
41 if sys.version_info[:2] == (2,3):
42 from inspect import ismodule, getabsfile, modulesbyfile
42 from inspect import ismodule, getabsfile, modulesbyfile
43 def getmodule(object):
43 def getmodule(object):
44 """Return the module an object was defined in, or None if not found."""
44 """Return the module an object was defined in, or None if not found."""
45 if ismodule(object):
45 if ismodule(object):
46 return object
46 return object
47 if hasattr(object, '__module__'):
47 if hasattr(object, '__module__'):
48 return sys.modules.get(object.__module__)
48 return sys.modules.get(object.__module__)
49 try:
49 try:
50 file = getabsfile(object)
50 file = getabsfile(object)
51 except TypeError:
51 except TypeError:
52 return None
52 return None
53 if file in modulesbyfile:
53 if file in modulesbyfile:
54 return sys.modules.get(modulesbyfile[file])
54 return sys.modules.get(modulesbyfile[file])
55 for module in sys.modules.values():
55 for module in sys.modules.values():
56 if hasattr(module, '__file__'):
56 if hasattr(module, '__file__'):
57 modulesbyfile[
57 modulesbyfile[
58 os.path.realpath(
58 os.path.realpath(
59 getabsfile(module))] = module.__name__
59 getabsfile(module))] = module.__name__
60 if file in modulesbyfile:
60 if file in modulesbyfile:
61 return sys.modules.get(modulesbyfile[file])
61 return sys.modules.get(modulesbyfile[file])
62 main = sys.modules['__main__']
62 main = sys.modules['__main__']
63 if not hasattr(object, '__name__'):
63 if not hasattr(object, '__name__'):
64 return None
64 return None
65 if hasattr(main, object.__name__):
65 if hasattr(main, object.__name__):
66 mainobject = getattr(main, object.__name__)
66 mainobject = getattr(main, object.__name__)
67 if mainobject is object:
67 if mainobject is object:
68 return main
68 return main
69 builtin = sys.modules['__builtin__']
69 builtin = sys.modules['__builtin__']
70 if hasattr(builtin, object.__name__):
70 if hasattr(builtin, object.__name__):
71 builtinobject = getattr(builtin, object.__name__)
71 builtinobject = getattr(builtin, object.__name__)
72 if builtinobject is object:
72 if builtinobject is object:
73 return builtin
73 return builtin
74
74
75 inspect.getmodule = getmodule
75 inspect.getmodule = getmodule
76
76
77 #****************************************************************************
77 #****************************************************************************
78 # Builtin color schemes
78 # Builtin color schemes
79
79
80 Colors = TermColors # just a shorthand
80 Colors = TermColors # just a shorthand
81
81
82 # Build a few color schemes
82 # Build a few color schemes
83 NoColor = ColorScheme(
83 NoColor = ColorScheme(
84 'NoColor',{
84 'NoColor',{
85 'header' : Colors.NoColor,
85 'header' : Colors.NoColor,
86 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
86 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
87 } )
87 } )
88
88
89 LinuxColors = ColorScheme(
89 LinuxColors = ColorScheme(
90 'Linux',{
90 'Linux',{
91 'header' : Colors.LightRed,
91 'header' : Colors.LightRed,
92 'normal' : Colors.Normal # color off (usu. Colors.Normal)
92 'normal' : Colors.Normal # color off (usu. Colors.Normal)
93 } )
93 } )
94
94
95 LightBGColors = ColorScheme(
95 LightBGColors = ColorScheme(
96 'LightBG',{
96 'LightBG',{
97 'header' : Colors.Red,
97 'header' : Colors.Red,
98 'normal' : Colors.Normal # color off (usu. Colors.Normal)
98 'normal' : Colors.Normal # color off (usu. Colors.Normal)
99 } )
99 } )
100
100
101 # Build table of color schemes (needed by the parser)
101 # Build table of color schemes (needed by the parser)
102 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
102 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
103 'Linux')
103 'Linux')
104
104
105 #****************************************************************************
105 #****************************************************************************
106 # Auxiliary functions
106 # Auxiliary functions
107 def getdoc(obj):
107 def getdoc(obj):
108 """Stable wrapper around inspect.getdoc.
108 """Stable wrapper around inspect.getdoc.
109
109
110 This can't crash because of attribute problems.
110 This can't crash because of attribute problems.
111
111
112 It also attempts to call a getdoc() method on the given object. This
112 It also attempts to call a getdoc() method on the given object. This
113 allows objects which provide their docstrings via non-standard mechanisms
113 allows objects which provide their docstrings via non-standard mechanisms
114 (like Pyro proxies) to still be inspected by ipython's ? system."""
114 (like Pyro proxies) to still be inspected by ipython's ? system."""
115
115
116 ds = None # default return value
116 ds = None # default return value
117 try:
117 try:
118 ds = inspect.getdoc(obj)
118 ds = inspect.getdoc(obj)
119 except:
119 except:
120 # Harden against an inspect failure, which can occur with
120 # Harden against an inspect failure, which can occur with
121 # SWIG-wrapped extensions.
121 # SWIG-wrapped extensions.
122 pass
122 pass
123 # Allow objects to offer customized documentation via a getdoc method:
123 # Allow objects to offer customized documentation via a getdoc method:
124 try:
124 try:
125 ds2 = obj.getdoc()
125 ds2 = obj.getdoc()
126 except:
126 except:
127 pass
127 pass
128 else:
128 else:
129 # if we get extra info, we add it to the normal docstring.
129 # if we get extra info, we add it to the normal docstring.
130 if ds is None:
130 if ds is None:
131 ds = ds2
131 ds = ds2
132 else:
132 else:
133 ds = '%s\n%s' % (ds,ds2)
133 ds = '%s\n%s' % (ds,ds2)
134 return ds
134 return ds
135
135
136
136
137 def getsource(obj,is_binary=False):
137 def getsource(obj,is_binary=False):
138 """Wrapper around inspect.getsource.
138 """Wrapper around inspect.getsource.
139
139
140 This can be modified by other projects to provide customized source
140 This can be modified by other projects to provide customized source
141 extraction.
141 extraction.
142
142
143 Inputs:
143 Inputs:
144
144
145 - obj: an object whose source code we will attempt to extract.
145 - obj: an object whose source code we will attempt to extract.
146
146
147 Optional inputs:
147 Optional inputs:
148
148
149 - is_binary: whether the object is known to come from a binary source.
149 - is_binary: whether the object is known to come from a binary source.
150 This implementation will skip returning any output for binary objects, but
150 This implementation will skip returning any output for binary objects, but
151 custom extractors may know how to meaningfully process them."""
151 custom extractors may know how to meaningfully process them."""
152
152
153 if is_binary:
153 if is_binary:
154 return None
154 return None
155 else:
155 else:
156 try:
156 try:
157 src = inspect.getsource(obj)
157 src = inspect.getsource(obj)
158 except TypeError:
158 except TypeError:
159 if hasattr(obj,'__class__'):
159 if hasattr(obj,'__class__'):
160 src = inspect.getsource(obj.__class__)
160 src = inspect.getsource(obj.__class__)
161 return src
161 return src
162
162
163 def getargspec(obj):
163 def getargspec(obj):
164 """Get the names and default values of a function's arguments.
164 """Get the names and default values of a function's arguments.
165
165
166 A tuple of four things is returned: (args, varargs, varkw, defaults).
166 A tuple of four things is returned: (args, varargs, varkw, defaults).
167 'args' is a list of the argument names (it may contain nested lists).
167 'args' is a list of the argument names (it may contain nested lists).
168 'varargs' and 'varkw' are the names of the * and ** arguments or None.
168 'varargs' and 'varkw' are the names of the * and ** arguments or None.
169 'defaults' is an n-tuple of the default values of the last n arguments.
169 'defaults' is an n-tuple of the default values of the last n arguments.
170
170
171 Modified version of inspect.getargspec from the Python Standard
171 Modified version of inspect.getargspec from the Python Standard
172 Library."""
172 Library."""
173
173
174 if inspect.isfunction(obj):
174 if inspect.isfunction(obj):
175 func_obj = obj
175 func_obj = obj
176 elif inspect.ismethod(obj):
176 elif inspect.ismethod(obj):
177 func_obj = obj.im_func
177 func_obj = obj.im_func
178 else:
178 else:
179 raise TypeError, 'arg is not a Python function'
179 raise TypeError, 'arg is not a Python function'
180 args, varargs, varkw = inspect.getargs(func_obj.func_code)
180 args, varargs, varkw = inspect.getargs(func_obj.func_code)
181 return args, varargs, varkw, func_obj.func_defaults
181 return args, varargs, varkw, func_obj.func_defaults
182
182
183 #****************************************************************************
183 #****************************************************************************
184 # Class definitions
184 # Class definitions
185
185
186 class myStringIO(StringIO.StringIO):
186 class myStringIO(StringIO.StringIO):
187 """Adds a writeln method to normal StringIO."""
187 """Adds a writeln method to normal StringIO."""
188 def writeln(self,*arg,**kw):
188 def writeln(self,*arg,**kw):
189 """Does a write() and then a write('\n')"""
189 """Does a write() and then a write('\n')"""
190 self.write(*arg,**kw)
190 self.write(*arg,**kw)
191 self.write('\n')
191 self.write('\n')
192
192
193
193
194 class Inspector:
194 class Inspector:
195 def __init__(self,color_table,code_color_table,scheme,
195 def __init__(self,color_table,code_color_table,scheme,
196 str_detail_level=0):
196 str_detail_level=0):
197 self.color_table = color_table
197 self.color_table = color_table
198 self.parser = PyColorize.Parser(code_color_table,out='str')
198 self.parser = PyColorize.Parser(code_color_table,out='str')
199 self.format = self.parser.format
199 self.format = self.parser.format
200 self.str_detail_level = str_detail_level
200 self.str_detail_level = str_detail_level
201 self.set_active_scheme(scheme)
201 self.set_active_scheme(scheme)
202
202
203 def __getdef(self,obj,oname=''):
203 def __getdef(self,obj,oname=''):
204 """Return the definition header for any callable object.
204 """Return the definition header for any callable object.
205
205
206 If any exception is generated, None is returned instead and the
206 If any exception is generated, None is returned instead and the
207 exception is suppressed."""
207 exception is suppressed."""
208
208
209 try:
209 try:
210 return oname + inspect.formatargspec(*getargspec(obj))
210 return oname + inspect.formatargspec(*getargspec(obj))
211 except:
211 except:
212 return None
212 return None
213
213
214 def __head(self,h):
214 def __head(self,h):
215 """Return a header string with proper colors."""
215 """Return a header string with proper colors."""
216 return '%s%s%s' % (self.color_table.active_colors.header,h,
216 return '%s%s%s' % (self.color_table.active_colors.header,h,
217 self.color_table.active_colors.normal)
217 self.color_table.active_colors.normal)
218
218
219 def set_active_scheme(self,scheme):
219 def set_active_scheme(self,scheme):
220 self.color_table.set_active_scheme(scheme)
220 self.color_table.set_active_scheme(scheme)
221 self.parser.color_table.set_active_scheme(scheme)
221 self.parser.color_table.set_active_scheme(scheme)
222
222
223 def noinfo(self,msg,oname):
223 def noinfo(self,msg,oname):
224 """Generic message when no information is found."""
224 """Generic message when no information is found."""
225 print 'No %s found' % msg,
225 print 'No %s found' % msg,
226 if oname:
226 if oname:
227 print 'for %s' % oname
227 print 'for %s' % oname
228 else:
228 else:
229 print
229 print
230
230
231 def pdef(self,obj,oname=''):
231 def pdef(self,obj,oname=''):
232 """Print the definition header for any callable object.
232 """Print the definition header for any callable object.
233
233
234 If the object is a class, print the constructor information."""
234 If the object is a class, print the constructor information."""
235
235
236 if not callable(obj):
236 if not callable(obj):
237 print 'Object is not callable.'
237 print 'Object is not callable.'
238 return
238 return
239
239
240 header = ''
240 header = ''
241
241
242 if inspect.isclass(obj):
242 if inspect.isclass(obj):
243 header = self.__head('Class constructor information:\n')
243 header = self.__head('Class constructor information:\n')
244 obj = obj.__init__
244 obj = obj.__init__
245 elif type(obj) is types.InstanceType:
245 elif type(obj) is types.InstanceType:
246 obj = obj.__call__
246 obj = obj.__call__
247
247
248 output = self.__getdef(obj,oname)
248 output = self.__getdef(obj,oname)
249 if output is None:
249 if output is None:
250 self.noinfo('definition header',oname)
250 self.noinfo('definition header',oname)
251 else:
251 else:
252 print >>Term.cout, header,self.format(output),
252 print >>IPython.utils.io.Term.cout, header,self.format(output),
253
253
254 def pdoc(self,obj,oname='',formatter = None):
254 def pdoc(self,obj,oname='',formatter = None):
255 """Print the docstring for any object.
255 """Print the docstring for any object.
256
256
257 Optional:
257 Optional:
258 -formatter: a function to run the docstring through for specially
258 -formatter: a function to run the docstring through for specially
259 formatted docstrings."""
259 formatted docstrings."""
260
260
261 head = self.__head # so that itpl can find it even if private
261 head = self.__head # so that itpl can find it even if private
262 ds = getdoc(obj)
262 ds = getdoc(obj)
263 if formatter:
263 if formatter:
264 ds = formatter(ds)
264 ds = formatter(ds)
265 if inspect.isclass(obj):
265 if inspect.isclass(obj):
266 init_ds = getdoc(obj.__init__)
266 init_ds = getdoc(obj.__init__)
267 output = itpl('$head("Class Docstring:")\n'
267 output = itpl('$head("Class Docstring:")\n'
268 '$indent(ds)\n'
268 '$indent(ds)\n'
269 '$head("Constructor Docstring"):\n'
269 '$head("Constructor Docstring"):\n'
270 '$indent(init_ds)')
270 '$indent(init_ds)')
271 elif (type(obj) is types.InstanceType or isinstance(obj,object)) \
271 elif (type(obj) is types.InstanceType or isinstance(obj,object)) \
272 and hasattr(obj,'__call__'):
272 and hasattr(obj,'__call__'):
273 call_ds = getdoc(obj.__call__)
273 call_ds = getdoc(obj.__call__)
274 if call_ds:
274 if call_ds:
275 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
275 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
276 '$head("Calling Docstring:")\n$indent(call_ds)')
276 '$head("Calling Docstring:")\n$indent(call_ds)')
277 else:
277 else:
278 output = ds
278 output = ds
279 else:
279 else:
280 output = ds
280 output = ds
281 if output is None:
281 if output is None:
282 self.noinfo('documentation',oname)
282 self.noinfo('documentation',oname)
283 return
283 return
284 page(output)
284 page(output)
285
285
286 def psource(self,obj,oname=''):
286 def psource(self,obj,oname=''):
287 """Print the source code for an object."""
287 """Print the source code for an object."""
288
288
289 # Flush the source cache because inspect can return out-of-date source
289 # Flush the source cache because inspect can return out-of-date source
290 linecache.checkcache()
290 linecache.checkcache()
291 try:
291 try:
292 src = getsource(obj)
292 src = getsource(obj)
293 except:
293 except:
294 self.noinfo('source',oname)
294 self.noinfo('source',oname)
295 else:
295 else:
296 page(self.format(src))
296 page(self.format(src))
297
297
298 def pfile(self,obj,oname=''):
298 def pfile(self,obj,oname=''):
299 """Show the whole file where an object was defined."""
299 """Show the whole file where an object was defined."""
300
300
301 try:
301 try:
302 try:
302 try:
303 lineno = inspect.getsourcelines(obj)[1]
303 lineno = inspect.getsourcelines(obj)[1]
304 except TypeError:
304 except TypeError:
305 # For instances, try the class object like getsource() does
305 # For instances, try the class object like getsource() does
306 if hasattr(obj,'__class__'):
306 if hasattr(obj,'__class__'):
307 lineno = inspect.getsourcelines(obj.__class__)[1]
307 lineno = inspect.getsourcelines(obj.__class__)[1]
308 # Adjust the inspected object so getabsfile() below works
308 # Adjust the inspected object so getabsfile() below works
309 obj = obj.__class__
309 obj = obj.__class__
310 except:
310 except:
311 self.noinfo('file',oname)
311 self.noinfo('file',oname)
312 return
312 return
313
313
314 # We only reach this point if object was successfully queried
314 # We only reach this point if object was successfully queried
315
315
316 # run contents of file through pager starting at line
316 # run contents of file through pager starting at line
317 # where the object is defined
317 # where the object is defined
318 ofile = inspect.getabsfile(obj)
318 ofile = inspect.getabsfile(obj)
319
319
320 if (ofile.endswith('.so') or ofile.endswith('.dll')):
320 if (ofile.endswith('.so') or ofile.endswith('.dll')):
321 print 'File %r is binary, not printing.' % ofile
321 print 'File %r is binary, not printing.' % ofile
322 elif not os.path.isfile(ofile):
322 elif not os.path.isfile(ofile):
323 print 'File %r does not exist, not printing.' % ofile
323 print 'File %r does not exist, not printing.' % ofile
324 else:
324 else:
325 # Print only text files, not extension binaries. Note that
325 # Print only text files, not extension binaries. Note that
326 # getsourcelines returns lineno with 1-offset and page() uses
326 # getsourcelines returns lineno with 1-offset and page() uses
327 # 0-offset, so we must adjust.
327 # 0-offset, so we must adjust.
328 page(self.format(open(ofile).read()),lineno-1)
328 page(self.format(open(ofile).read()),lineno-1)
329
329
330 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
330 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
331 """Show detailed information about an object.
331 """Show detailed information about an object.
332
332
333 Optional arguments:
333 Optional arguments:
334
334
335 - oname: name of the variable pointing to the object.
335 - oname: name of the variable pointing to the object.
336
336
337 - formatter: special formatter for docstrings (see pdoc)
337 - formatter: special formatter for docstrings (see pdoc)
338
338
339 - info: a structure with some information fields which may have been
339 - info: a structure with some information fields which may have been
340 precomputed already.
340 precomputed already.
341
341
342 - detail_level: if set to 1, more information is given.
342 - detail_level: if set to 1, more information is given.
343 """
343 """
344
344
345 obj_type = type(obj)
345 obj_type = type(obj)
346
346
347 header = self.__head
347 header = self.__head
348 if info is None:
348 if info is None:
349 ismagic = 0
349 ismagic = 0
350 isalias = 0
350 isalias = 0
351 ospace = ''
351 ospace = ''
352 else:
352 else:
353 ismagic = info.ismagic
353 ismagic = info.ismagic
354 isalias = info.isalias
354 isalias = info.isalias
355 ospace = info.namespace
355 ospace = info.namespace
356 # Get docstring, special-casing aliases:
356 # Get docstring, special-casing aliases:
357 if isalias:
357 if isalias:
358 if not callable(obj):
358 if not callable(obj):
359 try:
359 try:
360 ds = "Alias to the system command:\n %s" % obj[1]
360 ds = "Alias to the system command:\n %s" % obj[1]
361 except:
361 except:
362 ds = "Alias: " + str(obj)
362 ds = "Alias: " + str(obj)
363 else:
363 else:
364 ds = "Alias to " + str(obj)
364 ds = "Alias to " + str(obj)
365 if obj.__doc__:
365 if obj.__doc__:
366 ds += "\nDocstring:\n" + obj.__doc__
366 ds += "\nDocstring:\n" + obj.__doc__
367 else:
367 else:
368 ds = getdoc(obj)
368 ds = getdoc(obj)
369 if ds is None:
369 if ds is None:
370 ds = '<no docstring>'
370 ds = '<no docstring>'
371 if formatter is not None:
371 if formatter is not None:
372 ds = formatter(ds)
372 ds = formatter(ds)
373
373
374 # store output in a list which gets joined with \n at the end.
374 # store output in a list which gets joined with \n at the end.
375 out = myStringIO()
375 out = myStringIO()
376
376
377 string_max = 200 # max size of strings to show (snipped if longer)
377 string_max = 200 # max size of strings to show (snipped if longer)
378 shalf = int((string_max -5)/2)
378 shalf = int((string_max -5)/2)
379
379
380 if ismagic:
380 if ismagic:
381 obj_type_name = 'Magic function'
381 obj_type_name = 'Magic function'
382 elif isalias:
382 elif isalias:
383 obj_type_name = 'System alias'
383 obj_type_name = 'System alias'
384 else:
384 else:
385 obj_type_name = obj_type.__name__
385 obj_type_name = obj_type.__name__
386 out.writeln(header('Type:\t\t')+obj_type_name)
386 out.writeln(header('Type:\t\t')+obj_type_name)
387
387
388 try:
388 try:
389 bclass = obj.__class__
389 bclass = obj.__class__
390 out.writeln(header('Base Class:\t')+str(bclass))
390 out.writeln(header('Base Class:\t')+str(bclass))
391 except: pass
391 except: pass
392
392
393 # String form, but snip if too long in ? form (full in ??)
393 # String form, but snip if too long in ? form (full in ??)
394 if detail_level >= self.str_detail_level:
394 if detail_level >= self.str_detail_level:
395 try:
395 try:
396 ostr = str(obj)
396 ostr = str(obj)
397 str_head = 'String Form:'
397 str_head = 'String Form:'
398 if not detail_level and len(ostr)>string_max:
398 if not detail_level and len(ostr)>string_max:
399 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
399 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
400 ostr = ("\n" + " " * len(str_head.expandtabs())).\
400 ostr = ("\n" + " " * len(str_head.expandtabs())).\
401 join(map(string.strip,ostr.split("\n")))
401 join(map(string.strip,ostr.split("\n")))
402 if ostr.find('\n') > -1:
402 if ostr.find('\n') > -1:
403 # Print multi-line strings starting at the next line.
403 # Print multi-line strings starting at the next line.
404 str_sep = '\n'
404 str_sep = '\n'
405 else:
405 else:
406 str_sep = '\t'
406 str_sep = '\t'
407 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
407 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
408 except:
408 except:
409 pass
409 pass
410
410
411 if ospace:
411 if ospace:
412 out.writeln(header('Namespace:\t')+ospace)
412 out.writeln(header('Namespace:\t')+ospace)
413
413
414 # Length (for strings and lists)
414 # Length (for strings and lists)
415 try:
415 try:
416 length = str(len(obj))
416 length = str(len(obj))
417 out.writeln(header('Length:\t\t')+length)
417 out.writeln(header('Length:\t\t')+length)
418 except: pass
418 except: pass
419
419
420 # Filename where object was defined
420 # Filename where object was defined
421 binary_file = False
421 binary_file = False
422 try:
422 try:
423 try:
423 try:
424 fname = inspect.getabsfile(obj)
424 fname = inspect.getabsfile(obj)
425 except TypeError:
425 except TypeError:
426 # For an instance, the file that matters is where its class was
426 # For an instance, the file that matters is where its class was
427 # declared.
427 # declared.
428 if hasattr(obj,'__class__'):
428 if hasattr(obj,'__class__'):
429 fname = inspect.getabsfile(obj.__class__)
429 fname = inspect.getabsfile(obj.__class__)
430 if fname.endswith('<string>'):
430 if fname.endswith('<string>'):
431 fname = 'Dynamically generated function. No source code available.'
431 fname = 'Dynamically generated function. No source code available.'
432 if (fname.endswith('.so') or fname.endswith('.dll')):
432 if (fname.endswith('.so') or fname.endswith('.dll')):
433 binary_file = True
433 binary_file = True
434 out.writeln(header('File:\t\t')+fname)
434 out.writeln(header('File:\t\t')+fname)
435 except:
435 except:
436 # if anything goes wrong, we don't want to show source, so it's as
436 # if anything goes wrong, we don't want to show source, so it's as
437 # if the file was binary
437 # if the file was binary
438 binary_file = True
438 binary_file = True
439
439
440 # reconstruct the function definition and print it:
440 # reconstruct the function definition and print it:
441 defln = self.__getdef(obj,oname)
441 defln = self.__getdef(obj,oname)
442 if defln:
442 if defln:
443 out.write(header('Definition:\t')+self.format(defln))
443 out.write(header('Definition:\t')+self.format(defln))
444
444
445 # Docstrings only in detail 0 mode, since source contains them (we
445 # Docstrings only in detail 0 mode, since source contains them (we
446 # avoid repetitions). If source fails, we add them back, see below.
446 # avoid repetitions). If source fails, we add them back, see below.
447 if ds and detail_level == 0:
447 if ds and detail_level == 0:
448 out.writeln(header('Docstring:\n') + indent(ds))
448 out.writeln(header('Docstring:\n') + indent(ds))
449
449
450 # Original source code for any callable
450 # Original source code for any callable
451 if detail_level:
451 if detail_level:
452 # Flush the source cache because inspect can return out-of-date
452 # Flush the source cache because inspect can return out-of-date
453 # source
453 # source
454 linecache.checkcache()
454 linecache.checkcache()
455 source_success = False
455 source_success = False
456 try:
456 try:
457 try:
457 try:
458 src = getsource(obj,binary_file)
458 src = getsource(obj,binary_file)
459 except TypeError:
459 except TypeError:
460 if hasattr(obj,'__class__'):
460 if hasattr(obj,'__class__'):
461 src = getsource(obj.__class__,binary_file)
461 src = getsource(obj.__class__,binary_file)
462 if src is not None:
462 if src is not None:
463 source = self.format(src)
463 source = self.format(src)
464 out.write(header('Source:\n')+source.rstrip())
464 out.write(header('Source:\n')+source.rstrip())
465 source_success = True
465 source_success = True
466 except Exception, msg:
466 except Exception, msg:
467 pass
467 pass
468
468
469 if ds and not source_success:
469 if ds and not source_success:
470 out.writeln(header('Docstring [source file open failed]:\n')
470 out.writeln(header('Docstring [source file open failed]:\n')
471 + indent(ds))
471 + indent(ds))
472
472
473 # Constructor docstring for classes
473 # Constructor docstring for classes
474 if inspect.isclass(obj):
474 if inspect.isclass(obj):
475 # reconstruct the function definition and print it:
475 # reconstruct the function definition and print it:
476 try:
476 try:
477 obj_init = obj.__init__
477 obj_init = obj.__init__
478 except AttributeError:
478 except AttributeError:
479 init_def = init_ds = None
479 init_def = init_ds = None
480 else:
480 else:
481 init_def = self.__getdef(obj_init,oname)
481 init_def = self.__getdef(obj_init,oname)
482 init_ds = getdoc(obj_init)
482 init_ds = getdoc(obj_init)
483 # Skip Python's auto-generated docstrings
483 # Skip Python's auto-generated docstrings
484 if init_ds and \
484 if init_ds and \
485 init_ds.startswith('x.__init__(...) initializes'):
485 init_ds.startswith('x.__init__(...) initializes'):
486 init_ds = None
486 init_ds = None
487
487
488 if init_def or init_ds:
488 if init_def or init_ds:
489 out.writeln(header('\nConstructor information:'))
489 out.writeln(header('\nConstructor information:'))
490 if init_def:
490 if init_def:
491 out.write(header('Definition:\t')+ self.format(init_def))
491 out.write(header('Definition:\t')+ self.format(init_def))
492 if init_ds:
492 if init_ds:
493 out.writeln(header('Docstring:\n') + indent(init_ds))
493 out.writeln(header('Docstring:\n') + indent(init_ds))
494 # and class docstring for instances:
494 # and class docstring for instances:
495 elif obj_type is types.InstanceType or \
495 elif obj_type is types.InstanceType or \
496 isinstance(obj,object):
496 isinstance(obj,object):
497
497
498 # First, check whether the instance docstring is identical to the
498 # First, check whether the instance docstring is identical to the
499 # class one, and print it separately if they don't coincide. In
499 # class one, and print it separately if they don't coincide. In
500 # most cases they will, but it's nice to print all the info for
500 # most cases they will, but it's nice to print all the info for
501 # objects which use instance-customized docstrings.
501 # objects which use instance-customized docstrings.
502 if ds:
502 if ds:
503 try:
503 try:
504 cls = getattr(obj,'__class__')
504 cls = getattr(obj,'__class__')
505 except:
505 except:
506 class_ds = None
506 class_ds = None
507 else:
507 else:
508 class_ds = getdoc(cls)
508 class_ds = getdoc(cls)
509 # Skip Python's auto-generated docstrings
509 # Skip Python's auto-generated docstrings
510 if class_ds and \
510 if class_ds and \
511 (class_ds.startswith('function(code, globals[,') or \
511 (class_ds.startswith('function(code, globals[,') or \
512 class_ds.startswith('instancemethod(function, instance,') or \
512 class_ds.startswith('instancemethod(function, instance,') or \
513 class_ds.startswith('module(name[,') ):
513 class_ds.startswith('module(name[,') ):
514 class_ds = None
514 class_ds = None
515 if class_ds and ds != class_ds:
515 if class_ds and ds != class_ds:
516 out.writeln(header('Class Docstring:\n') +
516 out.writeln(header('Class Docstring:\n') +
517 indent(class_ds))
517 indent(class_ds))
518
518
519 # Next, try to show constructor docstrings
519 # Next, try to show constructor docstrings
520 try:
520 try:
521 init_ds = getdoc(obj.__init__)
521 init_ds = getdoc(obj.__init__)
522 # Skip Python's auto-generated docstrings
522 # Skip Python's auto-generated docstrings
523 if init_ds and \
523 if init_ds and \
524 init_ds.startswith('x.__init__(...) initializes'):
524 init_ds.startswith('x.__init__(...) initializes'):
525 init_ds = None
525 init_ds = None
526 except AttributeError:
526 except AttributeError:
527 init_ds = None
527 init_ds = None
528 if init_ds:
528 if init_ds:
529 out.writeln(header('Constructor Docstring:\n') +
529 out.writeln(header('Constructor Docstring:\n') +
530 indent(init_ds))
530 indent(init_ds))
531
531
532 # Call form docstring for callable instances
532 # Call form docstring for callable instances
533 if hasattr(obj,'__call__'):
533 if hasattr(obj,'__call__'):
534 #out.writeln(header('Callable:\t')+'Yes')
534 #out.writeln(header('Callable:\t')+'Yes')
535 call_def = self.__getdef(obj.__call__,oname)
535 call_def = self.__getdef(obj.__call__,oname)
536 #if call_def is None:
536 #if call_def is None:
537 # out.writeln(header('Call def:\t')+
537 # out.writeln(header('Call def:\t')+
538 # 'Calling definition not available.')
538 # 'Calling definition not available.')
539 if call_def is not None:
539 if call_def is not None:
540 out.writeln(header('Call def:\t')+self.format(call_def))
540 out.writeln(header('Call def:\t')+self.format(call_def))
541 call_ds = getdoc(obj.__call__)
541 call_ds = getdoc(obj.__call__)
542 # Skip Python's auto-generated docstrings
542 # Skip Python's auto-generated docstrings
543 if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'):
543 if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'):
544 call_ds = None
544 call_ds = None
545 if call_ds:
545 if call_ds:
546 out.writeln(header('Call docstring:\n') + indent(call_ds))
546 out.writeln(header('Call docstring:\n') + indent(call_ds))
547
547
548 # Finally send to printer/pager
548 # Finally send to printer/pager
549 output = out.getvalue()
549 output = out.getvalue()
550 if output:
550 if output:
551 page(output)
551 page(output)
552 # end pinfo
552 # end pinfo
553
553
554 def psearch(self,pattern,ns_table,ns_search=[],
554 def psearch(self,pattern,ns_table,ns_search=[],
555 ignore_case=False,show_all=False):
555 ignore_case=False,show_all=False):
556 """Search namespaces with wildcards for objects.
556 """Search namespaces with wildcards for objects.
557
557
558 Arguments:
558 Arguments:
559
559
560 - pattern: string containing shell-like wildcards to use in namespace
560 - pattern: string containing shell-like wildcards to use in namespace
561 searches and optionally a type specification to narrow the search to
561 searches and optionally a type specification to narrow the search to
562 objects of that type.
562 objects of that type.
563
563
564 - ns_table: dict of name->namespaces for search.
564 - ns_table: dict of name->namespaces for search.
565
565
566 Optional arguments:
566 Optional arguments:
567
567
568 - ns_search: list of namespace names to include in search.
568 - ns_search: list of namespace names to include in search.
569
569
570 - ignore_case(False): make the search case-insensitive.
570 - ignore_case(False): make the search case-insensitive.
571
571
572 - show_all(False): show all names, including those starting with
572 - show_all(False): show all names, including those starting with
573 underscores.
573 underscores.
574 """
574 """
575 #print 'ps pattern:<%r>' % pattern # dbg
575 #print 'ps pattern:<%r>' % pattern # dbg
576
576
577 # defaults
577 # defaults
578 type_pattern = 'all'
578 type_pattern = 'all'
579 filter = ''
579 filter = ''
580
580
581 cmds = pattern.split()
581 cmds = pattern.split()
582 len_cmds = len(cmds)
582 len_cmds = len(cmds)
583 if len_cmds == 1:
583 if len_cmds == 1:
584 # Only filter pattern given
584 # Only filter pattern given
585 filter = cmds[0]
585 filter = cmds[0]
586 elif len_cmds == 2:
586 elif len_cmds == 2:
587 # Both filter and type specified
587 # Both filter and type specified
588 filter,type_pattern = cmds
588 filter,type_pattern = cmds
589 else:
589 else:
590 raise ValueError('invalid argument string for psearch: <%s>' %
590 raise ValueError('invalid argument string for psearch: <%s>' %
591 pattern)
591 pattern)
592
592
593 # filter search namespaces
593 # filter search namespaces
594 for name in ns_search:
594 for name in ns_search:
595 if name not in ns_table:
595 if name not in ns_table:
596 raise ValueError('invalid namespace <%s>. Valid names: %s' %
596 raise ValueError('invalid namespace <%s>. Valid names: %s' %
597 (name,ns_table.keys()))
597 (name,ns_table.keys()))
598
598
599 #print 'type_pattern:',type_pattern # dbg
599 #print 'type_pattern:',type_pattern # dbg
600 search_result = []
600 search_result = []
601 for ns_name in ns_search:
601 for ns_name in ns_search:
602 ns = ns_table[ns_name]
602 ns = ns_table[ns_name]
603 tmp_res = list(list_namespace(ns,type_pattern,filter,
603 tmp_res = list(list_namespace(ns,type_pattern,filter,
604 ignore_case=ignore_case,
604 ignore_case=ignore_case,
605 show_all=show_all))
605 show_all=show_all))
606 search_result.extend(tmp_res)
606 search_result.extend(tmp_res)
607 search_result.sort()
607 search_result.sort()
608
608
609 page('\n'.join(search_result))
609 page('\n'.join(search_result))
@@ -1,307 +1,307 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Paging capabilities for IPython.core
4 Paging capabilities for IPython.core
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez
9 * Fernando Perez
10
10
11 Notes
11 Notes
12 -----
12 -----
13
13
14 For now this uses ipapi, so it can't be in IPython.utils. If we can get
14 For now this uses ipapi, so it can't be in IPython.utils. If we can get
15 rid of that dependency, we could move it there.
15 rid of that dependency, we could move it there.
16 -----
16 -----
17 """
17 """
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Copyright (C) 2008-2009 The IPython Development Team
20 # Copyright (C) 2008-2009 The IPython Development Team
21 #
21 #
22 # Distributed under the terms of the BSD License. The full license is in
22 # Distributed under the terms of the BSD License. The full license is in
23 # the file COPYING, distributed as part of this software.
23 # the file COPYING, distributed as part of this software.
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Imports
27 # Imports
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 import os
30 import os
31 import re
31 import re
32 import sys
32 import sys
33 import tempfile
33 import tempfile
34
34
35 from IPython.core import ipapi
35 from IPython.core import ipapi
36 from IPython.core.error import TryNext
36 from IPython.core.error import TryNext
37 from IPython.utils.cursesimport import use_curses
37 from IPython.utils.cursesimport import use_curses
38 from IPython.utils.data import chop
38 from IPython.utils.data import chop
39 from IPython.utils.io import Term
39 import IPython.utils.io
40 from IPython.utils.process import xsys
40 from IPython.utils.process import xsys
41 from IPython.utils.terminal import get_terminal_size
41 from IPython.utils.terminal import get_terminal_size
42
42
43
43
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45 # Classes and functions
45 # Classes and functions
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47
47
48 esc_re = re.compile(r"(\x1b[^m]+m)")
48 esc_re = re.compile(r"(\x1b[^m]+m)")
49
49
50 def page_dumb(strng, start=0, screen_lines=25):
50 def page_dumb(strng, start=0, screen_lines=25):
51 """Very dumb 'pager' in Python, for when nothing else works.
51 """Very dumb 'pager' in Python, for when nothing else works.
52
52
53 Only moves forward, same interface as page(), except for pager_cmd and
53 Only moves forward, same interface as page(), except for pager_cmd and
54 mode."""
54 mode."""
55
55
56 out_ln = strng.splitlines()[start:]
56 out_ln = strng.splitlines()[start:]
57 screens = chop(out_ln,screen_lines-1)
57 screens = chop(out_ln,screen_lines-1)
58 if len(screens) == 1:
58 if len(screens) == 1:
59 print >>Term.cout, os.linesep.join(screens[0])
59 print >>IPython.utils.io.Term.cout, os.linesep.join(screens[0])
60 else:
60 else:
61 last_escape = ""
61 last_escape = ""
62 for scr in screens[0:-1]:
62 for scr in screens[0:-1]:
63 hunk = os.linesep.join(scr)
63 hunk = os.linesep.join(scr)
64 print >>Term.cout, last_escape + hunk
64 print >>IPython.utils.io.Term.cout, last_escape + hunk
65 if not page_more():
65 if not page_more():
66 return
66 return
67 esc_list = esc_re.findall(hunk)
67 esc_list = esc_re.findall(hunk)
68 if len(esc_list) > 0:
68 if len(esc_list) > 0:
69 last_escape = esc_list[-1]
69 last_escape = esc_list[-1]
70 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
70 print >>IPython.utils.io.Term.cout, last_escape + os.linesep.join(screens[-1])
71
71
72
72
73 def page(strng, start=0, screen_lines=0, pager_cmd=None):
73 def page(strng, start=0, screen_lines=0, pager_cmd=None):
74 """Print a string, piping through a pager after a certain length.
74 """Print a string, piping through a pager after a certain length.
75
75
76 The screen_lines parameter specifies the number of *usable* lines of your
76 The screen_lines parameter specifies the number of *usable* lines of your
77 terminal screen (total lines minus lines you need to reserve to show other
77 terminal screen (total lines minus lines you need to reserve to show other
78 information).
78 information).
79
79
80 If you set screen_lines to a number <=0, page() will try to auto-determine
80 If you set screen_lines to a number <=0, page() will try to auto-determine
81 your screen size and will only use up to (screen_size+screen_lines) for
81 your screen size and will only use up to (screen_size+screen_lines) for
82 printing, paging after that. That is, if you want auto-detection but need
82 printing, paging after that. That is, if you want auto-detection but need
83 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
83 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
84 auto-detection without any lines reserved simply use screen_lines = 0.
84 auto-detection without any lines reserved simply use screen_lines = 0.
85
85
86 If a string won't fit in the allowed lines, it is sent through the
86 If a string won't fit in the allowed lines, it is sent through the
87 specified pager command. If none given, look for PAGER in the environment,
87 specified pager command. If none given, look for PAGER in the environment,
88 and ultimately default to less.
88 and ultimately default to less.
89
89
90 If no system pager works, the string is sent through a 'dumb pager'
90 If no system pager works, the string is sent through a 'dumb pager'
91 written in python, very simplistic.
91 written in python, very simplistic.
92 """
92 """
93
93
94 # Some routines may auto-compute start offsets incorrectly and pass a
94 # Some routines may auto-compute start offsets incorrectly and pass a
95 # negative value. Offset to 0 for robustness.
95 # negative value. Offset to 0 for robustness.
96 start = max(0, start)
96 start = max(0, start)
97
97
98 # first, try the hook
98 # first, try the hook
99 ip = ipapi.get()
99 ip = ipapi.get()
100 if ip:
100 if ip:
101 try:
101 try:
102 ip.hooks.show_in_pager(strng)
102 ip.hooks.show_in_pager(strng)
103 return
103 return
104 except TryNext:
104 except TryNext:
105 pass
105 pass
106
106
107 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
107 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
108 TERM = os.environ.get('TERM','dumb')
108 TERM = os.environ.get('TERM','dumb')
109 if TERM in ['dumb','emacs'] and os.name != 'nt':
109 if TERM in ['dumb','emacs'] and os.name != 'nt':
110 print strng
110 print strng
111 return
111 return
112 # chop off the topmost part of the string we don't want to see
112 # chop off the topmost part of the string we don't want to see
113 str_lines = strng.split(os.linesep)[start:]
113 str_lines = strng.split(os.linesep)[start:]
114 str_toprint = os.linesep.join(str_lines)
114 str_toprint = os.linesep.join(str_lines)
115 num_newlines = len(str_lines)
115 num_newlines = len(str_lines)
116 len_str = len(str_toprint)
116 len_str = len(str_toprint)
117
117
118 # Dumb heuristics to guesstimate number of on-screen lines the string
118 # Dumb heuristics to guesstimate number of on-screen lines the string
119 # takes. Very basic, but good enough for docstrings in reasonable
119 # takes. Very basic, but good enough for docstrings in reasonable
120 # terminals. If someone later feels like refining it, it's not hard.
120 # terminals. If someone later feels like refining it, it's not hard.
121 numlines = max(num_newlines,int(len_str/80)+1)
121 numlines = max(num_newlines,int(len_str/80)+1)
122
122
123 screen_lines_def = get_terminal_size()[1]
123 screen_lines_def = get_terminal_size()[1]
124
124
125 # auto-determine screen size
125 # auto-determine screen size
126 if screen_lines <= 0:
126 if screen_lines <= 0:
127 if (TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5':
127 if (TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5':
128 local_use_curses = use_curses
128 local_use_curses = use_curses
129 else:
129 else:
130 # curses causes problems on many terminals other than xterm, and
130 # curses causes problems on many terminals other than xterm, and
131 # some termios calls lock up on Sun OS5.
131 # some termios calls lock up on Sun OS5.
132 local_use_curses = False
132 local_use_curses = False
133 if local_use_curses:
133 if local_use_curses:
134 import termios
134 import termios
135 import curses
135 import curses
136 # There is a bug in curses, where *sometimes* it fails to properly
136 # There is a bug in curses, where *sometimes* it fails to properly
137 # initialize, and then after the endwin() call is made, the
137 # initialize, and then after the endwin() call is made, the
138 # terminal is left in an unusable state. Rather than trying to
138 # terminal is left in an unusable state. Rather than trying to
139 # check everytime for this (by requesting and comparing termios
139 # check everytime for this (by requesting and comparing termios
140 # flags each time), we just save the initial terminal state and
140 # flags each time), we just save the initial terminal state and
141 # unconditionally reset it every time. It's cheaper than making
141 # unconditionally reset it every time. It's cheaper than making
142 # the checks.
142 # the checks.
143 term_flags = termios.tcgetattr(sys.stdout)
143 term_flags = termios.tcgetattr(sys.stdout)
144 scr = curses.initscr()
144 scr = curses.initscr()
145 screen_lines_real,screen_cols = scr.getmaxyx()
145 screen_lines_real,screen_cols = scr.getmaxyx()
146 curses.endwin()
146 curses.endwin()
147 # Restore terminal state in case endwin() didn't.
147 # Restore terminal state in case endwin() didn't.
148 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
148 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
149 # Now we have what we needed: the screen size in rows/columns
149 # Now we have what we needed: the screen size in rows/columns
150 screen_lines += screen_lines_real
150 screen_lines += screen_lines_real
151 #print '***Screen size:',screen_lines_real,'lines x',\
151 #print '***Screen size:',screen_lines_real,'lines x',\
152 #screen_cols,'columns.' # dbg
152 #screen_cols,'columns.' # dbg
153 else:
153 else:
154 screen_lines += screen_lines_def
154 screen_lines += screen_lines_def
155
155
156 #print 'numlines',numlines,'screenlines',screen_lines # dbg
156 #print 'numlines',numlines,'screenlines',screen_lines # dbg
157 if numlines <= screen_lines :
157 if numlines <= screen_lines :
158 #print '*** normal print' # dbg
158 #print '*** normal print' # dbg
159 print >>Term.cout, str_toprint
159 print >>IPython.utils.io.Term.cout, str_toprint
160 else:
160 else:
161 # Try to open pager and default to internal one if that fails.
161 # Try to open pager and default to internal one if that fails.
162 # All failure modes are tagged as 'retval=1', to match the return
162 # All failure modes are tagged as 'retval=1', to match the return
163 # value of a failed system command. If any intermediate attempt
163 # value of a failed system command. If any intermediate attempt
164 # sets retval to 1, at the end we resort to our own page_dumb() pager.
164 # sets retval to 1, at the end we resort to our own page_dumb() pager.
165 pager_cmd = get_pager_cmd(pager_cmd)
165 pager_cmd = get_pager_cmd(pager_cmd)
166 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
166 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
167 if os.name == 'nt':
167 if os.name == 'nt':
168 if pager_cmd.startswith('type'):
168 if pager_cmd.startswith('type'):
169 # The default WinXP 'type' command is failing on complex strings.
169 # The default WinXP 'type' command is failing on complex strings.
170 retval = 1
170 retval = 1
171 else:
171 else:
172 tmpname = tempfile.mktemp('.txt')
172 tmpname = tempfile.mktemp('.txt')
173 tmpfile = file(tmpname,'wt')
173 tmpfile = file(tmpname,'wt')
174 tmpfile.write(strng)
174 tmpfile.write(strng)
175 tmpfile.close()
175 tmpfile.close()
176 cmd = "%s < %s" % (pager_cmd,tmpname)
176 cmd = "%s < %s" % (pager_cmd,tmpname)
177 if os.system(cmd):
177 if os.system(cmd):
178 retval = 1
178 retval = 1
179 else:
179 else:
180 retval = None
180 retval = None
181 os.remove(tmpname)
181 os.remove(tmpname)
182 else:
182 else:
183 try:
183 try:
184 retval = None
184 retval = None
185 # if I use popen4, things hang. No idea why.
185 # if I use popen4, things hang. No idea why.
186 #pager,shell_out = os.popen4(pager_cmd)
186 #pager,shell_out = os.popen4(pager_cmd)
187 pager = os.popen(pager_cmd,'w')
187 pager = os.popen(pager_cmd,'w')
188 pager.write(strng)
188 pager.write(strng)
189 pager.close()
189 pager.close()
190 retval = pager.close() # success returns None
190 retval = pager.close() # success returns None
191 except IOError,msg: # broken pipe when user quits
191 except IOError,msg: # broken pipe when user quits
192 if msg.args == (32,'Broken pipe'):
192 if msg.args == (32,'Broken pipe'):
193 retval = None
193 retval = None
194 else:
194 else:
195 retval = 1
195 retval = 1
196 except OSError:
196 except OSError:
197 # Other strange problems, sometimes seen in Win2k/cygwin
197 # Other strange problems, sometimes seen in Win2k/cygwin
198 retval = 1
198 retval = 1
199 if retval is not None:
199 if retval is not None:
200 page_dumb(strng,screen_lines=screen_lines)
200 page_dumb(strng,screen_lines=screen_lines)
201
201
202
202
203 def page_file(fname, start=0, pager_cmd=None):
203 def page_file(fname, start=0, pager_cmd=None):
204 """Page a file, using an optional pager command and starting line.
204 """Page a file, using an optional pager command and starting line.
205 """
205 """
206
206
207 pager_cmd = get_pager_cmd(pager_cmd)
207 pager_cmd = get_pager_cmd(pager_cmd)
208 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
208 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
209
209
210 try:
210 try:
211 if os.environ['TERM'] in ['emacs','dumb']:
211 if os.environ['TERM'] in ['emacs','dumb']:
212 raise EnvironmentError
212 raise EnvironmentError
213 xsys(pager_cmd + ' ' + fname)
213 xsys(pager_cmd + ' ' + fname)
214 except:
214 except:
215 try:
215 try:
216 if start > 0:
216 if start > 0:
217 start -= 1
217 start -= 1
218 page(open(fname).read(),start)
218 page(open(fname).read(),start)
219 except:
219 except:
220 print 'Unable to show file',`fname`
220 print 'Unable to show file',`fname`
221
221
222
222
223 def get_pager_cmd(pager_cmd=None):
223 def get_pager_cmd(pager_cmd=None):
224 """Return a pager command.
224 """Return a pager command.
225
225
226 Makes some attempts at finding an OS-correct one.
226 Makes some attempts at finding an OS-correct one.
227 """
227 """
228 if os.name == 'posix':
228 if os.name == 'posix':
229 default_pager_cmd = 'less -r' # -r for color control sequences
229 default_pager_cmd = 'less -r' # -r for color control sequences
230 elif os.name in ['nt','dos']:
230 elif os.name in ['nt','dos']:
231 default_pager_cmd = 'type'
231 default_pager_cmd = 'type'
232
232
233 if pager_cmd is None:
233 if pager_cmd is None:
234 try:
234 try:
235 pager_cmd = os.environ['PAGER']
235 pager_cmd = os.environ['PAGER']
236 except:
236 except:
237 pager_cmd = default_pager_cmd
237 pager_cmd = default_pager_cmd
238 return pager_cmd
238 return pager_cmd
239
239
240
240
241 def get_pager_start(pager, start):
241 def get_pager_start(pager, start):
242 """Return the string for paging files with an offset.
242 """Return the string for paging files with an offset.
243
243
244 This is the '+N' argument which less and more (under Unix) accept.
244 This is the '+N' argument which less and more (under Unix) accept.
245 """
245 """
246
246
247 if pager in ['less','more']:
247 if pager in ['less','more']:
248 if start:
248 if start:
249 start_string = '+' + str(start)
249 start_string = '+' + str(start)
250 else:
250 else:
251 start_string = ''
251 start_string = ''
252 else:
252 else:
253 start_string = ''
253 start_string = ''
254 return start_string
254 return start_string
255
255
256
256
257 # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
257 # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
258 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
258 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
259 import msvcrt
259 import msvcrt
260 def page_more():
260 def page_more():
261 """ Smart pausing between pages
261 """ Smart pausing between pages
262
262
263 @return: True if need print more lines, False if quit
263 @return: True if need print more lines, False if quit
264 """
264 """
265 Term.cout.write('---Return to continue, q to quit--- ')
265 IPython.utils.io.Term.cout.write('---Return to continue, q to quit--- ')
266 ans = msvcrt.getch()
266 ans = msvcrt.getch()
267 if ans in ("q", "Q"):
267 if ans in ("q", "Q"):
268 result = False
268 result = False
269 else:
269 else:
270 result = True
270 result = True
271 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
271 IPython.utils.io.Term.cout.write("\b"*37 + " "*37 + "\b"*37)
272 return result
272 return result
273 else:
273 else:
274 def page_more():
274 def page_more():
275 ans = raw_input('---Return to continue, q to quit--- ')
275 ans = raw_input('---Return to continue, q to quit--- ')
276 if ans.lower().startswith('q'):
276 if ans.lower().startswith('q'):
277 return False
277 return False
278 else:
278 else:
279 return True
279 return True
280
280
281
281
282 def snip_print(str,width = 75,print_full = 0,header = ''):
282 def snip_print(str,width = 75,print_full = 0,header = ''):
283 """Print a string snipping the midsection to fit in width.
283 """Print a string snipping the midsection to fit in width.
284
284
285 print_full: mode control:
285 print_full: mode control:
286 - 0: only snip long strings
286 - 0: only snip long strings
287 - 1: send to page() directly.
287 - 1: send to page() directly.
288 - 2: snip long strings and ask for full length viewing with page()
288 - 2: snip long strings and ask for full length viewing with page()
289 Return 1 if snipping was necessary, 0 otherwise."""
289 Return 1 if snipping was necessary, 0 otherwise."""
290
290
291 if print_full == 1:
291 if print_full == 1:
292 page(header+str)
292 page(header+str)
293 return 0
293 return 0
294
294
295 print header,
295 print header,
296 if len(str) < width:
296 if len(str) < width:
297 print str
297 print str
298 snip = 0
298 snip = 0
299 else:
299 else:
300 whalf = int((width -5)/2)
300 whalf = int((width -5)/2)
301 print str[:whalf] + ' <...> ' + str[-whalf:]
301 print str[:whalf] + ' <...> ' + str[-whalf:]
302 snip = 1
302 snip = 1
303 if snip and print_full == 2:
303 if snip and print_full == 2:
304 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
304 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
305 page(str)
305 page(str)
306 return snip
306 return snip
307
307
@@ -1,1022 +1,1022 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Prefiltering components.
4 Prefiltering components.
5
5
6 Prefilters transform user input before it is exec'd by Python. These
6 Prefilters transform user input before it is exec'd by Python. These
7 transforms are used to implement additional syntax such as !ls and %magic.
7 transforms are used to implement additional syntax such as !ls and %magic.
8
8
9 Authors:
9 Authors:
10
10
11 * Brian Granger
11 * Brian Granger
12 * Fernando Perez
12 * Fernando Perez
13 * Dan Milstein
13 * Dan Milstein
14 * Ville Vainio
14 * Ville Vainio
15 """
15 """
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Copyright (C) 2008-2009 The IPython Development Team
18 # Copyright (C) 2008-2009 The IPython Development Team
19 #
19 #
20 # Distributed under the terms of the BSD License. The full license is in
20 # Distributed under the terms of the BSD License. The full license is in
21 # the file COPYING, distributed as part of this software.
21 # the file COPYING, distributed as part of this software.
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Imports
25 # Imports
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 import __builtin__
28 import __builtin__
29 import codeop
29 import codeop
30 import re
30 import re
31
31
32 from IPython.core.alias import AliasManager
32 from IPython.core.alias import AliasManager
33 from IPython.core.autocall import IPyAutocall
33 from IPython.core.autocall import IPyAutocall
34 from IPython.config.configurable import Configurable
34 from IPython.config.configurable import Configurable
35 from IPython.core.splitinput import split_user_input
35 from IPython.core.splitinput import split_user_input
36 from IPython.core.page import page
36 from IPython.core.page import page
37
37
38 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance
38 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance
39 from IPython.utils.io import Term
39 import IPython.utils.io
40 from IPython.utils.text import make_quoted_expr
40 from IPython.utils.text import make_quoted_expr
41 from IPython.utils.autoattr import auto_attr
41 from IPython.utils.autoattr import auto_attr
42
42
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44 # Global utilities, errors and constants
44 # Global utilities, errors and constants
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46
46
47 # Warning, these cannot be changed unless various regular expressions
47 # Warning, these cannot be changed unless various regular expressions
48 # are updated in a number of places. Not great, but at least we told you.
48 # are updated in a number of places. Not great, but at least we told you.
49 ESC_SHELL = '!'
49 ESC_SHELL = '!'
50 ESC_SH_CAP = '!!'
50 ESC_SH_CAP = '!!'
51 ESC_HELP = '?'
51 ESC_HELP = '?'
52 ESC_MAGIC = '%'
52 ESC_MAGIC = '%'
53 ESC_QUOTE = ','
53 ESC_QUOTE = ','
54 ESC_QUOTE2 = ';'
54 ESC_QUOTE2 = ';'
55 ESC_PAREN = '/'
55 ESC_PAREN = '/'
56
56
57
57
58 class PrefilterError(Exception):
58 class PrefilterError(Exception):
59 pass
59 pass
60
60
61
61
62 # RegExp to identify potential function names
62 # RegExp to identify potential function names
63 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
63 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
64
64
65 # RegExp to exclude strings with this start from autocalling. In
65 # RegExp to exclude strings with this start from autocalling. In
66 # particular, all binary operators should be excluded, so that if foo is
66 # particular, all binary operators should be excluded, so that if foo is
67 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
67 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
68 # characters '!=()' don't need to be checked for, as the checkPythonChars
68 # characters '!=()' don't need to be checked for, as the checkPythonChars
69 # routine explicitely does so, to catch direct calls and rebindings of
69 # routine explicitely does so, to catch direct calls and rebindings of
70 # existing names.
70 # existing names.
71
71
72 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
72 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
73 # it affects the rest of the group in square brackets.
73 # it affects the rest of the group in square brackets.
74 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
74 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
75 r'|^is |^not |^in |^and |^or ')
75 r'|^is |^not |^in |^and |^or ')
76
76
77 # try to catch also methods for stuff in lists/tuples/dicts: off
77 # try to catch also methods for stuff in lists/tuples/dicts: off
78 # (experimental). For this to work, the line_split regexp would need
78 # (experimental). For this to work, the line_split regexp would need
79 # to be modified so it wouldn't break things at '['. That line is
79 # to be modified so it wouldn't break things at '['. That line is
80 # nasty enough that I shouldn't change it until I can test it _well_.
80 # nasty enough that I shouldn't change it until I can test it _well_.
81 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
81 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
82
82
83
83
84 # Handler Check Utilities
84 # Handler Check Utilities
85 def is_shadowed(identifier, ip):
85 def is_shadowed(identifier, ip):
86 """Is the given identifier defined in one of the namespaces which shadow
86 """Is the given identifier defined in one of the namespaces which shadow
87 the alias and magic namespaces? Note that an identifier is different
87 the alias and magic namespaces? Note that an identifier is different
88 than ifun, because it can not contain a '.' character."""
88 than ifun, because it can not contain a '.' character."""
89 # This is much safer than calling ofind, which can change state
89 # This is much safer than calling ofind, which can change state
90 return (identifier in ip.user_ns \
90 return (identifier in ip.user_ns \
91 or identifier in ip.internal_ns \
91 or identifier in ip.internal_ns \
92 or identifier in ip.ns_table['builtin'])
92 or identifier in ip.ns_table['builtin'])
93
93
94
94
95 #-----------------------------------------------------------------------------
95 #-----------------------------------------------------------------------------
96 # The LineInfo class used throughout
96 # The LineInfo class used throughout
97 #-----------------------------------------------------------------------------
97 #-----------------------------------------------------------------------------
98
98
99
99
100 class LineInfo(object):
100 class LineInfo(object):
101 """A single line of input and associated info.
101 """A single line of input and associated info.
102
102
103 Includes the following as properties:
103 Includes the following as properties:
104
104
105 line
105 line
106 The original, raw line
106 The original, raw line
107
107
108 continue_prompt
108 continue_prompt
109 Is this line a continuation in a sequence of multiline input?
109 Is this line a continuation in a sequence of multiline input?
110
110
111 pre
111 pre
112 The initial esc character or whitespace.
112 The initial esc character or whitespace.
113
113
114 pre_char
114 pre_char
115 The escape character(s) in pre or the empty string if there isn't one.
115 The escape character(s) in pre or the empty string if there isn't one.
116 Note that '!!' is a possible value for pre_char. Otherwise it will
116 Note that '!!' is a possible value for pre_char. Otherwise it will
117 always be a single character.
117 always be a single character.
118
118
119 pre_whitespace
119 pre_whitespace
120 The leading whitespace from pre if it exists. If there is a pre_char,
120 The leading whitespace from pre if it exists. If there is a pre_char,
121 this is just ''.
121 this is just ''.
122
122
123 ifun
123 ifun
124 The 'function part', which is basically the maximal initial sequence
124 The 'function part', which is basically the maximal initial sequence
125 of valid python identifiers and the '.' character. This is what is
125 of valid python identifiers and the '.' character. This is what is
126 checked for alias and magic transformations, used for auto-calling,
126 checked for alias and magic transformations, used for auto-calling,
127 etc.
127 etc.
128
128
129 the_rest
129 the_rest
130 Everything else on the line.
130 Everything else on the line.
131 """
131 """
132 def __init__(self, line, continue_prompt):
132 def __init__(self, line, continue_prompt):
133 self.line = line
133 self.line = line
134 self.continue_prompt = continue_prompt
134 self.continue_prompt = continue_prompt
135 self.pre, self.ifun, self.the_rest = split_user_input(line)
135 self.pre, self.ifun, self.the_rest = split_user_input(line)
136
136
137 self.pre_char = self.pre.strip()
137 self.pre_char = self.pre.strip()
138 if self.pre_char:
138 if self.pre_char:
139 self.pre_whitespace = '' # No whitespace allowd before esc chars
139 self.pre_whitespace = '' # No whitespace allowd before esc chars
140 else:
140 else:
141 self.pre_whitespace = self.pre
141 self.pre_whitespace = self.pre
142
142
143 self._oinfo = None
143 self._oinfo = None
144
144
145 def ofind(self, ip):
145 def ofind(self, ip):
146 """Do a full, attribute-walking lookup of the ifun in the various
146 """Do a full, attribute-walking lookup of the ifun in the various
147 namespaces for the given IPython InteractiveShell instance.
147 namespaces for the given IPython InteractiveShell instance.
148
148
149 Return a dict with keys: found,obj,ospace,ismagic
149 Return a dict with keys: found,obj,ospace,ismagic
150
150
151 Note: can cause state changes because of calling getattr, but should
151 Note: can cause state changes because of calling getattr, but should
152 only be run if autocall is on and if the line hasn't matched any
152 only be run if autocall is on and if the line hasn't matched any
153 other, less dangerous handlers.
153 other, less dangerous handlers.
154
154
155 Does cache the results of the call, so can be called multiple times
155 Does cache the results of the call, so can be called multiple times
156 without worrying about *further* damaging state.
156 without worrying about *further* damaging state.
157 """
157 """
158 if not self._oinfo:
158 if not self._oinfo:
159 # ip.shell._ofind is actually on the Magic class!
159 # ip.shell._ofind is actually on the Magic class!
160 self._oinfo = ip.shell._ofind(self.ifun)
160 self._oinfo = ip.shell._ofind(self.ifun)
161 return self._oinfo
161 return self._oinfo
162
162
163 def __str__(self):
163 def __str__(self):
164 return "Lineinfo [%s|%s|%s]" %(self.pre, self.ifun, self.the_rest)
164 return "Lineinfo [%s|%s|%s]" %(self.pre, self.ifun, self.the_rest)
165
165
166
166
167 #-----------------------------------------------------------------------------
167 #-----------------------------------------------------------------------------
168 # Main Prefilter manager
168 # Main Prefilter manager
169 #-----------------------------------------------------------------------------
169 #-----------------------------------------------------------------------------
170
170
171
171
172 class PrefilterManager(Configurable):
172 class PrefilterManager(Configurable):
173 """Main prefilter component.
173 """Main prefilter component.
174
174
175 The IPython prefilter is run on all user input before it is run. The
175 The IPython prefilter is run on all user input before it is run. The
176 prefilter consumes lines of input and produces transformed lines of
176 prefilter consumes lines of input and produces transformed lines of
177 input.
177 input.
178
178
179 The iplementation consists of two phases:
179 The iplementation consists of two phases:
180
180
181 1. Transformers
181 1. Transformers
182 2. Checkers and handlers
182 2. Checkers and handlers
183
183
184 Over time, we plan on deprecating the checkers and handlers and doing
184 Over time, we plan on deprecating the checkers and handlers and doing
185 everything in the transformers.
185 everything in the transformers.
186
186
187 The transformers are instances of :class:`PrefilterTransformer` and have
187 The transformers are instances of :class:`PrefilterTransformer` and have
188 a single method :meth:`transform` that takes a line and returns a
188 a single method :meth:`transform` that takes a line and returns a
189 transformed line. The transformation can be accomplished using any
189 transformed line. The transformation can be accomplished using any
190 tool, but our current ones use regular expressions for speed. We also
190 tool, but our current ones use regular expressions for speed. We also
191 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
191 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
192
192
193 After all the transformers have been run, the line is fed to the checkers,
193 After all the transformers have been run, the line is fed to the checkers,
194 which are instances of :class:`PrefilterChecker`. The line is passed to
194 which are instances of :class:`PrefilterChecker`. The line is passed to
195 the :meth:`check` method, which either returns `None` or a
195 the :meth:`check` method, which either returns `None` or a
196 :class:`PrefilterHandler` instance. If `None` is returned, the other
196 :class:`PrefilterHandler` instance. If `None` is returned, the other
197 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
197 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
198 the line is passed to the :meth:`handle` method of the returned
198 the line is passed to the :meth:`handle` method of the returned
199 handler and no further checkers are tried.
199 handler and no further checkers are tried.
200
200
201 Both transformers and checkers have a `priority` attribute, that determines
201 Both transformers and checkers have a `priority` attribute, that determines
202 the order in which they are called. Smaller priorities are tried first.
202 the order in which they are called. Smaller priorities are tried first.
203
203
204 Both transformers and checkers also have `enabled` attribute, which is
204 Both transformers and checkers also have `enabled` attribute, which is
205 a boolean that determines if the instance is used.
205 a boolean that determines if the instance is used.
206
206
207 Users or developers can change the priority or enabled attribute of
207 Users or developers can change the priority or enabled attribute of
208 transformers or checkers, but they must call the :meth:`sort_checkers`
208 transformers or checkers, but they must call the :meth:`sort_checkers`
209 or :meth:`sort_transformers` method after changing the priority.
209 or :meth:`sort_transformers` method after changing the priority.
210 """
210 """
211
211
212 multi_line_specials = CBool(True, config=True)
212 multi_line_specials = CBool(True, config=True)
213 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
213 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
214
214
215 def __init__(self, shell=None, config=None):
215 def __init__(self, shell=None, config=None):
216 super(PrefilterManager, self).__init__(shell=shell, config=config)
216 super(PrefilterManager, self).__init__(shell=shell, config=config)
217 self.shell = shell
217 self.shell = shell
218 self.init_transformers()
218 self.init_transformers()
219 self.init_handlers()
219 self.init_handlers()
220 self.init_checkers()
220 self.init_checkers()
221
221
222 #-------------------------------------------------------------------------
222 #-------------------------------------------------------------------------
223 # API for managing transformers
223 # API for managing transformers
224 #-------------------------------------------------------------------------
224 #-------------------------------------------------------------------------
225
225
226 def init_transformers(self):
226 def init_transformers(self):
227 """Create the default transformers."""
227 """Create the default transformers."""
228 self._transformers = []
228 self._transformers = []
229 for transformer_cls in _default_transformers:
229 for transformer_cls in _default_transformers:
230 transformer_cls(
230 transformer_cls(
231 shell=self.shell, prefilter_manager=self, config=self.config
231 shell=self.shell, prefilter_manager=self, config=self.config
232 )
232 )
233
233
234 def sort_transformers(self):
234 def sort_transformers(self):
235 """Sort the transformers by priority.
235 """Sort the transformers by priority.
236
236
237 This must be called after the priority of a transformer is changed.
237 This must be called after the priority of a transformer is changed.
238 The :meth:`register_transformer` method calls this automatically.
238 The :meth:`register_transformer` method calls this automatically.
239 """
239 """
240 self._transformers.sort(cmp=lambda x,y: x.priority-y.priority)
240 self._transformers.sort(cmp=lambda x,y: x.priority-y.priority)
241
241
242 @property
242 @property
243 def transformers(self):
243 def transformers(self):
244 """Return a list of checkers, sorted by priority."""
244 """Return a list of checkers, sorted by priority."""
245 return self._transformers
245 return self._transformers
246
246
247 def register_transformer(self, transformer):
247 def register_transformer(self, transformer):
248 """Register a transformer instance."""
248 """Register a transformer instance."""
249 if transformer not in self._transformers:
249 if transformer not in self._transformers:
250 self._transformers.append(transformer)
250 self._transformers.append(transformer)
251 self.sort_transformers()
251 self.sort_transformers()
252
252
253 def unregister_transformer(self, transformer):
253 def unregister_transformer(self, transformer):
254 """Unregister a transformer instance."""
254 """Unregister a transformer instance."""
255 if transformer in self._transformers:
255 if transformer in self._transformers:
256 self._transformers.remove(transformer)
256 self._transformers.remove(transformer)
257
257
258 #-------------------------------------------------------------------------
258 #-------------------------------------------------------------------------
259 # API for managing checkers
259 # API for managing checkers
260 #-------------------------------------------------------------------------
260 #-------------------------------------------------------------------------
261
261
262 def init_checkers(self):
262 def init_checkers(self):
263 """Create the default checkers."""
263 """Create the default checkers."""
264 self._checkers = []
264 self._checkers = []
265 for checker in _default_checkers:
265 for checker in _default_checkers:
266 checker(
266 checker(
267 shell=self.shell, prefilter_manager=self, config=self.config
267 shell=self.shell, prefilter_manager=self, config=self.config
268 )
268 )
269
269
270 def sort_checkers(self):
270 def sort_checkers(self):
271 """Sort the checkers by priority.
271 """Sort the checkers by priority.
272
272
273 This must be called after the priority of a checker is changed.
273 This must be called after the priority of a checker is changed.
274 The :meth:`register_checker` method calls this automatically.
274 The :meth:`register_checker` method calls this automatically.
275 """
275 """
276 self._checkers.sort(cmp=lambda x,y: x.priority-y.priority)
276 self._checkers.sort(cmp=lambda x,y: x.priority-y.priority)
277
277
278 @property
278 @property
279 def checkers(self):
279 def checkers(self):
280 """Return a list of checkers, sorted by priority."""
280 """Return a list of checkers, sorted by priority."""
281 return self._checkers
281 return self._checkers
282
282
283 def register_checker(self, checker):
283 def register_checker(self, checker):
284 """Register a checker instance."""
284 """Register a checker instance."""
285 if checker not in self._checkers:
285 if checker not in self._checkers:
286 self._checkers.append(checker)
286 self._checkers.append(checker)
287 self.sort_checkers()
287 self.sort_checkers()
288
288
289 def unregister_checker(self, checker):
289 def unregister_checker(self, checker):
290 """Unregister a checker instance."""
290 """Unregister a checker instance."""
291 if checker in self._checkers:
291 if checker in self._checkers:
292 self._checkers.remove(checker)
292 self._checkers.remove(checker)
293
293
294 #-------------------------------------------------------------------------
294 #-------------------------------------------------------------------------
295 # API for managing checkers
295 # API for managing checkers
296 #-------------------------------------------------------------------------
296 #-------------------------------------------------------------------------
297
297
298 def init_handlers(self):
298 def init_handlers(self):
299 """Create the default handlers."""
299 """Create the default handlers."""
300 self._handlers = {}
300 self._handlers = {}
301 self._esc_handlers = {}
301 self._esc_handlers = {}
302 for handler in _default_handlers:
302 for handler in _default_handlers:
303 handler(
303 handler(
304 shell=self.shell, prefilter_manager=self, config=self.config
304 shell=self.shell, prefilter_manager=self, config=self.config
305 )
305 )
306
306
307 @property
307 @property
308 def handlers(self):
308 def handlers(self):
309 """Return a dict of all the handlers."""
309 """Return a dict of all the handlers."""
310 return self._handlers
310 return self._handlers
311
311
312 def register_handler(self, name, handler, esc_strings):
312 def register_handler(self, name, handler, esc_strings):
313 """Register a handler instance by name with esc_strings."""
313 """Register a handler instance by name with esc_strings."""
314 self._handlers[name] = handler
314 self._handlers[name] = handler
315 for esc_str in esc_strings:
315 for esc_str in esc_strings:
316 self._esc_handlers[esc_str] = handler
316 self._esc_handlers[esc_str] = handler
317
317
318 def unregister_handler(self, name, handler, esc_strings):
318 def unregister_handler(self, name, handler, esc_strings):
319 """Unregister a handler instance by name with esc_strings."""
319 """Unregister a handler instance by name with esc_strings."""
320 try:
320 try:
321 del self._handlers[name]
321 del self._handlers[name]
322 except KeyError:
322 except KeyError:
323 pass
323 pass
324 for esc_str in esc_strings:
324 for esc_str in esc_strings:
325 h = self._esc_handlers.get(esc_str)
325 h = self._esc_handlers.get(esc_str)
326 if h is handler:
326 if h is handler:
327 del self._esc_handlers[esc_str]
327 del self._esc_handlers[esc_str]
328
328
329 def get_handler_by_name(self, name):
329 def get_handler_by_name(self, name):
330 """Get a handler by its name."""
330 """Get a handler by its name."""
331 return self._handlers.get(name)
331 return self._handlers.get(name)
332
332
333 def get_handler_by_esc(self, esc_str):
333 def get_handler_by_esc(self, esc_str):
334 """Get a handler by its escape string."""
334 """Get a handler by its escape string."""
335 return self._esc_handlers.get(esc_str)
335 return self._esc_handlers.get(esc_str)
336
336
337 #-------------------------------------------------------------------------
337 #-------------------------------------------------------------------------
338 # Main prefiltering API
338 # Main prefiltering API
339 #-------------------------------------------------------------------------
339 #-------------------------------------------------------------------------
340
340
341 def prefilter_line_info(self, line_info):
341 def prefilter_line_info(self, line_info):
342 """Prefilter a line that has been converted to a LineInfo object.
342 """Prefilter a line that has been converted to a LineInfo object.
343
343
344 This implements the checker/handler part of the prefilter pipe.
344 This implements the checker/handler part of the prefilter pipe.
345 """
345 """
346 # print "prefilter_line_info: ", line_info
346 # print "prefilter_line_info: ", line_info
347 handler = self.find_handler(line_info)
347 handler = self.find_handler(line_info)
348 return handler.handle(line_info)
348 return handler.handle(line_info)
349
349
350 def find_handler(self, line_info):
350 def find_handler(self, line_info):
351 """Find a handler for the line_info by trying checkers."""
351 """Find a handler for the line_info by trying checkers."""
352 for checker in self.checkers:
352 for checker in self.checkers:
353 if checker.enabled:
353 if checker.enabled:
354 handler = checker.check(line_info)
354 handler = checker.check(line_info)
355 if handler:
355 if handler:
356 return handler
356 return handler
357 return self.get_handler_by_name('normal')
357 return self.get_handler_by_name('normal')
358
358
359 def transform_line(self, line, continue_prompt):
359 def transform_line(self, line, continue_prompt):
360 """Calls the enabled transformers in order of increasing priority."""
360 """Calls the enabled transformers in order of increasing priority."""
361 for transformer in self.transformers:
361 for transformer in self.transformers:
362 if transformer.enabled:
362 if transformer.enabled:
363 line = transformer.transform(line, continue_prompt)
363 line = transformer.transform(line, continue_prompt)
364 return line
364 return line
365
365
366 def prefilter_line(self, line, continue_prompt=False):
366 def prefilter_line(self, line, continue_prompt=False):
367 """Prefilter a single input line as text.
367 """Prefilter a single input line as text.
368
368
369 This method prefilters a single line of text by calling the
369 This method prefilters a single line of text by calling the
370 transformers and then the checkers/handlers.
370 transformers and then the checkers/handlers.
371 """
371 """
372
372
373 # print "prefilter_line: ", line, continue_prompt
373 # print "prefilter_line: ", line, continue_prompt
374 # All handlers *must* return a value, even if it's blank ('').
374 # All handlers *must* return a value, even if it's blank ('').
375
375
376 # Lines are NOT logged here. Handlers should process the line as
376 # Lines are NOT logged here. Handlers should process the line as
377 # needed, update the cache AND log it (so that the input cache array
377 # needed, update the cache AND log it (so that the input cache array
378 # stays synced).
378 # stays synced).
379
379
380 # save the line away in case we crash, so the post-mortem handler can
380 # save the line away in case we crash, so the post-mortem handler can
381 # record it
381 # record it
382 self.shell._last_input_line = line
382 self.shell._last_input_line = line
383
383
384 if not line:
384 if not line:
385 # Return immediately on purely empty lines, so that if the user
385 # Return immediately on purely empty lines, so that if the user
386 # previously typed some whitespace that started a continuation
386 # previously typed some whitespace that started a continuation
387 # prompt, he can break out of that loop with just an empty line.
387 # prompt, he can break out of that loop with just an empty line.
388 # This is how the default python prompt works.
388 # This is how the default python prompt works.
389
389
390 # Only return if the accumulated input buffer was just whitespace!
390 # Only return if the accumulated input buffer was just whitespace!
391 if ''.join(self.shell.buffer).isspace():
391 if ''.join(self.shell.buffer).isspace():
392 self.shell.buffer[:] = []
392 self.shell.buffer[:] = []
393 return ''
393 return ''
394
394
395 # At this point, we invoke our transformers.
395 # At this point, we invoke our transformers.
396 if not continue_prompt or (continue_prompt and self.multi_line_specials):
396 if not continue_prompt or (continue_prompt and self.multi_line_specials):
397 line = self.transform_line(line, continue_prompt)
397 line = self.transform_line(line, continue_prompt)
398
398
399 # Now we compute line_info for the checkers and handlers
399 # Now we compute line_info for the checkers and handlers
400 line_info = LineInfo(line, continue_prompt)
400 line_info = LineInfo(line, continue_prompt)
401
401
402 # the input history needs to track even empty lines
402 # the input history needs to track even empty lines
403 stripped = line.strip()
403 stripped = line.strip()
404
404
405 normal_handler = self.get_handler_by_name('normal')
405 normal_handler = self.get_handler_by_name('normal')
406 if not stripped:
406 if not stripped:
407 if not continue_prompt:
407 if not continue_prompt:
408 self.shell.outputcache.prompt_count -= 1
408 self.shell.outputcache.prompt_count -= 1
409
409
410 return normal_handler.handle(line_info)
410 return normal_handler.handle(line_info)
411
411
412 # special handlers are only allowed for single line statements
412 # special handlers are only allowed for single line statements
413 if continue_prompt and not self.multi_line_specials:
413 if continue_prompt and not self.multi_line_specials:
414 return normal_handler.handle(line_info)
414 return normal_handler.handle(line_info)
415
415
416 prefiltered = self.prefilter_line_info(line_info)
416 prefiltered = self.prefilter_line_info(line_info)
417 # print "prefiltered line: %r" % prefiltered
417 # print "prefiltered line: %r" % prefiltered
418 return prefiltered
418 return prefiltered
419
419
420 def prefilter_lines(self, lines, continue_prompt=False):
420 def prefilter_lines(self, lines, continue_prompt=False):
421 """Prefilter multiple input lines of text.
421 """Prefilter multiple input lines of text.
422
422
423 This is the main entry point for prefiltering multiple lines of
423 This is the main entry point for prefiltering multiple lines of
424 input. This simply calls :meth:`prefilter_line` for each line of
424 input. This simply calls :meth:`prefilter_line` for each line of
425 input.
425 input.
426
426
427 This covers cases where there are multiple lines in the user entry,
427 This covers cases where there are multiple lines in the user entry,
428 which is the case when the user goes back to a multiline history
428 which is the case when the user goes back to a multiline history
429 entry and presses enter.
429 entry and presses enter.
430 """
430 """
431 llines = lines.rstrip('\n').split('\n')
431 llines = lines.rstrip('\n').split('\n')
432 # We can get multiple lines in one shot, where multiline input 'blends'
432 # We can get multiple lines in one shot, where multiline input 'blends'
433 # into one line, in cases like recalling from the readline history
433 # into one line, in cases like recalling from the readline history
434 # buffer. We need to make sure that in such cases, we correctly
434 # buffer. We need to make sure that in such cases, we correctly
435 # communicate downstream which line is first and which are continuation
435 # communicate downstream which line is first and which are continuation
436 # ones.
436 # ones.
437 if len(llines) > 1:
437 if len(llines) > 1:
438 out = '\n'.join([self.prefilter_line(line, lnum>0)
438 out = '\n'.join([self.prefilter_line(line, lnum>0)
439 for lnum, line in enumerate(llines) ])
439 for lnum, line in enumerate(llines) ])
440 else:
440 else:
441 out = self.prefilter_line(llines[0], continue_prompt)
441 out = self.prefilter_line(llines[0], continue_prompt)
442
442
443 return out
443 return out
444
444
445 #-----------------------------------------------------------------------------
445 #-----------------------------------------------------------------------------
446 # Prefilter transformers
446 # Prefilter transformers
447 #-----------------------------------------------------------------------------
447 #-----------------------------------------------------------------------------
448
448
449
449
450 class PrefilterTransformer(Configurable):
450 class PrefilterTransformer(Configurable):
451 """Transform a line of user input."""
451 """Transform a line of user input."""
452
452
453 priority = Int(100, config=True)
453 priority = Int(100, config=True)
454 # Transformers don't currently use shell or prefilter_manager, but as we
454 # Transformers don't currently use shell or prefilter_manager, but as we
455 # move away from checkers and handlers, they will need them.
455 # move away from checkers and handlers, they will need them.
456 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
456 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
457 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
457 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
458 enabled = Bool(True, config=True)
458 enabled = Bool(True, config=True)
459
459
460 def __init__(self, shell=None, prefilter_manager=None, config=None):
460 def __init__(self, shell=None, prefilter_manager=None, config=None):
461 super(PrefilterTransformer, self).__init__(
461 super(PrefilterTransformer, self).__init__(
462 shell=shell, prefilter_manager=prefilter_manager, config=config
462 shell=shell, prefilter_manager=prefilter_manager, config=config
463 )
463 )
464 self.prefilter_manager.register_transformer(self)
464 self.prefilter_manager.register_transformer(self)
465
465
466 def transform(self, line, continue_prompt):
466 def transform(self, line, continue_prompt):
467 """Transform a line, returning the new one."""
467 """Transform a line, returning the new one."""
468 return None
468 return None
469
469
470 def __repr__(self):
470 def __repr__(self):
471 return "<%s(priority=%r, enabled=%r)>" % (
471 return "<%s(priority=%r, enabled=%r)>" % (
472 self.__class__.__name__, self.priority, self.enabled)
472 self.__class__.__name__, self.priority, self.enabled)
473
473
474
474
475 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
475 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
476 r'\s*=\s*!(?P<cmd>.*)')
476 r'\s*=\s*!(?P<cmd>.*)')
477
477
478
478
479 class AssignSystemTransformer(PrefilterTransformer):
479 class AssignSystemTransformer(PrefilterTransformer):
480 """Handle the `files = !ls` syntax."""
480 """Handle the `files = !ls` syntax."""
481
481
482 priority = Int(100, config=True)
482 priority = Int(100, config=True)
483
483
484 def transform(self, line, continue_prompt):
484 def transform(self, line, continue_prompt):
485 m = _assign_system_re.match(line)
485 m = _assign_system_re.match(line)
486 if m is not None:
486 if m is not None:
487 cmd = m.group('cmd')
487 cmd = m.group('cmd')
488 lhs = m.group('lhs')
488 lhs = m.group('lhs')
489 expr = make_quoted_expr("sc -l =%s" % cmd)
489 expr = make_quoted_expr("sc -l =%s" % cmd)
490 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
490 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
491 return new_line
491 return new_line
492 return line
492 return line
493
493
494
494
495 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
495 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
496 r'\s*=\s*%(?P<cmd>.*)')
496 r'\s*=\s*%(?P<cmd>.*)')
497
497
498 class AssignMagicTransformer(PrefilterTransformer):
498 class AssignMagicTransformer(PrefilterTransformer):
499 """Handle the `a = %who` syntax."""
499 """Handle the `a = %who` syntax."""
500
500
501 priority = Int(200, config=True)
501 priority = Int(200, config=True)
502
502
503 def transform(self, line, continue_prompt):
503 def transform(self, line, continue_prompt):
504 m = _assign_magic_re.match(line)
504 m = _assign_magic_re.match(line)
505 if m is not None:
505 if m is not None:
506 cmd = m.group('cmd')
506 cmd = m.group('cmd')
507 lhs = m.group('lhs')
507 lhs = m.group('lhs')
508 expr = make_quoted_expr(cmd)
508 expr = make_quoted_expr(cmd)
509 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
509 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
510 return new_line
510 return new_line
511 return line
511 return line
512
512
513
513
514 _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )')
514 _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )')
515
515
516 class PyPromptTransformer(PrefilterTransformer):
516 class PyPromptTransformer(PrefilterTransformer):
517 """Handle inputs that start with '>>> ' syntax."""
517 """Handle inputs that start with '>>> ' syntax."""
518
518
519 priority = Int(50, config=True)
519 priority = Int(50, config=True)
520
520
521 def transform(self, line, continue_prompt):
521 def transform(self, line, continue_prompt):
522
522
523 if not line or line.isspace() or line.strip() == '...':
523 if not line or line.isspace() or line.strip() == '...':
524 # This allows us to recognize multiple input prompts separated by
524 # This allows us to recognize multiple input prompts separated by
525 # blank lines and pasted in a single chunk, very common when
525 # blank lines and pasted in a single chunk, very common when
526 # pasting doctests or long tutorial passages.
526 # pasting doctests or long tutorial passages.
527 return ''
527 return ''
528 m = _classic_prompt_re.match(line)
528 m = _classic_prompt_re.match(line)
529 if m:
529 if m:
530 return line[len(m.group(0)):]
530 return line[len(m.group(0)):]
531 else:
531 else:
532 return line
532 return line
533
533
534
534
535 _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
535 _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
536
536
537 class IPyPromptTransformer(PrefilterTransformer):
537 class IPyPromptTransformer(PrefilterTransformer):
538 """Handle inputs that start classic IPython prompt syntax."""
538 """Handle inputs that start classic IPython prompt syntax."""
539
539
540 priority = Int(50, config=True)
540 priority = Int(50, config=True)
541
541
542 def transform(self, line, continue_prompt):
542 def transform(self, line, continue_prompt):
543
543
544 if not line or line.isspace() or line.strip() == '...':
544 if not line or line.isspace() or line.strip() == '...':
545 # This allows us to recognize multiple input prompts separated by
545 # This allows us to recognize multiple input prompts separated by
546 # blank lines and pasted in a single chunk, very common when
546 # blank lines and pasted in a single chunk, very common when
547 # pasting doctests or long tutorial passages.
547 # pasting doctests or long tutorial passages.
548 return ''
548 return ''
549 m = _ipy_prompt_re.match(line)
549 m = _ipy_prompt_re.match(line)
550 if m:
550 if m:
551 return line[len(m.group(0)):]
551 return line[len(m.group(0)):]
552 else:
552 else:
553 return line
553 return line
554
554
555 #-----------------------------------------------------------------------------
555 #-----------------------------------------------------------------------------
556 # Prefilter checkers
556 # Prefilter checkers
557 #-----------------------------------------------------------------------------
557 #-----------------------------------------------------------------------------
558
558
559
559
560 class PrefilterChecker(Configurable):
560 class PrefilterChecker(Configurable):
561 """Inspect an input line and return a handler for that line."""
561 """Inspect an input line and return a handler for that line."""
562
562
563 priority = Int(100, config=True)
563 priority = Int(100, config=True)
564 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
564 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
565 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
565 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
566 enabled = Bool(True, config=True)
566 enabled = Bool(True, config=True)
567
567
568 def __init__(self, shell=None, prefilter_manager=None, config=None):
568 def __init__(self, shell=None, prefilter_manager=None, config=None):
569 super(PrefilterChecker, self).__init__(
569 super(PrefilterChecker, self).__init__(
570 shell=shell, prefilter_manager=prefilter_manager, config=config
570 shell=shell, prefilter_manager=prefilter_manager, config=config
571 )
571 )
572 self.prefilter_manager.register_checker(self)
572 self.prefilter_manager.register_checker(self)
573
573
574 def check(self, line_info):
574 def check(self, line_info):
575 """Inspect line_info and return a handler instance or None."""
575 """Inspect line_info and return a handler instance or None."""
576 return None
576 return None
577
577
578 def __repr__(self):
578 def __repr__(self):
579 return "<%s(priority=%r, enabled=%r)>" % (
579 return "<%s(priority=%r, enabled=%r)>" % (
580 self.__class__.__name__, self.priority, self.enabled)
580 self.__class__.__name__, self.priority, self.enabled)
581
581
582
582
583 class EmacsChecker(PrefilterChecker):
583 class EmacsChecker(PrefilterChecker):
584
584
585 priority = Int(100, config=True)
585 priority = Int(100, config=True)
586 enabled = Bool(False, config=True)
586 enabled = Bool(False, config=True)
587
587
588 def check(self, line_info):
588 def check(self, line_info):
589 "Emacs ipython-mode tags certain input lines."
589 "Emacs ipython-mode tags certain input lines."
590 if line_info.line.endswith('# PYTHON-MODE'):
590 if line_info.line.endswith('# PYTHON-MODE'):
591 return self.prefilter_manager.get_handler_by_name('emacs')
591 return self.prefilter_manager.get_handler_by_name('emacs')
592 else:
592 else:
593 return None
593 return None
594
594
595
595
596 class ShellEscapeChecker(PrefilterChecker):
596 class ShellEscapeChecker(PrefilterChecker):
597
597
598 priority = Int(200, config=True)
598 priority = Int(200, config=True)
599
599
600 def check(self, line_info):
600 def check(self, line_info):
601 if line_info.line.lstrip().startswith(ESC_SHELL):
601 if line_info.line.lstrip().startswith(ESC_SHELL):
602 return self.prefilter_manager.get_handler_by_name('shell')
602 return self.prefilter_manager.get_handler_by_name('shell')
603
603
604
604
605 class IPyAutocallChecker(PrefilterChecker):
605 class IPyAutocallChecker(PrefilterChecker):
606
606
607 priority = Int(300, config=True)
607 priority = Int(300, config=True)
608
608
609 def check(self, line_info):
609 def check(self, line_info):
610 "Instances of IPyAutocall in user_ns get autocalled immediately"
610 "Instances of IPyAutocall in user_ns get autocalled immediately"
611 obj = self.shell.user_ns.get(line_info.ifun, None)
611 obj = self.shell.user_ns.get(line_info.ifun, None)
612 if isinstance(obj, IPyAutocall):
612 if isinstance(obj, IPyAutocall):
613 obj.set_ip(self.shell)
613 obj.set_ip(self.shell)
614 return self.prefilter_manager.get_handler_by_name('auto')
614 return self.prefilter_manager.get_handler_by_name('auto')
615 else:
615 else:
616 return None
616 return None
617
617
618
618
619 class MultiLineMagicChecker(PrefilterChecker):
619 class MultiLineMagicChecker(PrefilterChecker):
620
620
621 priority = Int(400, config=True)
621 priority = Int(400, config=True)
622
622
623 def check(self, line_info):
623 def check(self, line_info):
624 "Allow ! and !! in multi-line statements if multi_line_specials is on"
624 "Allow ! and !! in multi-line statements if multi_line_specials is on"
625 # Note that this one of the only places we check the first character of
625 # Note that this one of the only places we check the first character of
626 # ifun and *not* the pre_char. Also note that the below test matches
626 # ifun and *not* the pre_char. Also note that the below test matches
627 # both ! and !!.
627 # both ! and !!.
628 if line_info.continue_prompt \
628 if line_info.continue_prompt \
629 and self.prefilter_manager.multi_line_specials:
629 and self.prefilter_manager.multi_line_specials:
630 if line_info.ifun.startswith(ESC_MAGIC):
630 if line_info.ifun.startswith(ESC_MAGIC):
631 return self.prefilter_manager.get_handler_by_name('magic')
631 return self.prefilter_manager.get_handler_by_name('magic')
632 else:
632 else:
633 return None
633 return None
634
634
635
635
636 class EscCharsChecker(PrefilterChecker):
636 class EscCharsChecker(PrefilterChecker):
637
637
638 priority = Int(500, config=True)
638 priority = Int(500, config=True)
639
639
640 def check(self, line_info):
640 def check(self, line_info):
641 """Check for escape character and return either a handler to handle it,
641 """Check for escape character and return either a handler to handle it,
642 or None if there is no escape char."""
642 or None if there is no escape char."""
643 if line_info.line[-1] == ESC_HELP \
643 if line_info.line[-1] == ESC_HELP \
644 and line_info.pre_char != ESC_SHELL \
644 and line_info.pre_char != ESC_SHELL \
645 and line_info.pre_char != ESC_SH_CAP:
645 and line_info.pre_char != ESC_SH_CAP:
646 # the ? can be at the end, but *not* for either kind of shell escape,
646 # the ? can be at the end, but *not* for either kind of shell escape,
647 # because a ? can be a vaild final char in a shell cmd
647 # because a ? can be a vaild final char in a shell cmd
648 return self.prefilter_manager.get_handler_by_name('help')
648 return self.prefilter_manager.get_handler_by_name('help')
649 else:
649 else:
650 # This returns None like it should if no handler exists
650 # This returns None like it should if no handler exists
651 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
651 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
652
652
653
653
654 class AssignmentChecker(PrefilterChecker):
654 class AssignmentChecker(PrefilterChecker):
655
655
656 priority = Int(600, config=True)
656 priority = Int(600, config=True)
657
657
658 def check(self, line_info):
658 def check(self, line_info):
659 """Check to see if user is assigning to a var for the first time, in
659 """Check to see if user is assigning to a var for the first time, in
660 which case we want to avoid any sort of automagic / autocall games.
660 which case we want to avoid any sort of automagic / autocall games.
661
661
662 This allows users to assign to either alias or magic names true python
662 This allows users to assign to either alias or magic names true python
663 variables (the magic/alias systems always take second seat to true
663 variables (the magic/alias systems always take second seat to true
664 python code). E.g. ls='hi', or ls,that=1,2"""
664 python code). E.g. ls='hi', or ls,that=1,2"""
665 if line_info.the_rest:
665 if line_info.the_rest:
666 if line_info.the_rest[0] in '=,':
666 if line_info.the_rest[0] in '=,':
667 return self.prefilter_manager.get_handler_by_name('normal')
667 return self.prefilter_manager.get_handler_by_name('normal')
668 else:
668 else:
669 return None
669 return None
670
670
671
671
672 class AutoMagicChecker(PrefilterChecker):
672 class AutoMagicChecker(PrefilterChecker):
673
673
674 priority = Int(700, config=True)
674 priority = Int(700, config=True)
675
675
676 def check(self, line_info):
676 def check(self, line_info):
677 """If the ifun is magic, and automagic is on, run it. Note: normal,
677 """If the ifun is magic, and automagic is on, run it. Note: normal,
678 non-auto magic would already have been triggered via '%' in
678 non-auto magic would already have been triggered via '%' in
679 check_esc_chars. This just checks for automagic. Also, before
679 check_esc_chars. This just checks for automagic. Also, before
680 triggering the magic handler, make sure that there is nothing in the
680 triggering the magic handler, make sure that there is nothing in the
681 user namespace which could shadow it."""
681 user namespace which could shadow it."""
682 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
682 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
683 return None
683 return None
684
684
685 # We have a likely magic method. Make sure we should actually call it.
685 # We have a likely magic method. Make sure we should actually call it.
686 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
686 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
687 return None
687 return None
688
688
689 head = line_info.ifun.split('.',1)[0]
689 head = line_info.ifun.split('.',1)[0]
690 if is_shadowed(head, self.shell):
690 if is_shadowed(head, self.shell):
691 return None
691 return None
692
692
693 return self.prefilter_manager.get_handler_by_name('magic')
693 return self.prefilter_manager.get_handler_by_name('magic')
694
694
695
695
696 class AliasChecker(PrefilterChecker):
696 class AliasChecker(PrefilterChecker):
697
697
698 priority = Int(800, config=True)
698 priority = Int(800, config=True)
699
699
700 def check(self, line_info):
700 def check(self, line_info):
701 "Check if the initital identifier on the line is an alias."
701 "Check if the initital identifier on the line is an alias."
702 # Note: aliases can not contain '.'
702 # Note: aliases can not contain '.'
703 head = line_info.ifun.split('.',1)[0]
703 head = line_info.ifun.split('.',1)[0]
704 if line_info.ifun not in self.shell.alias_manager \
704 if line_info.ifun not in self.shell.alias_manager \
705 or head not in self.shell.alias_manager \
705 or head not in self.shell.alias_manager \
706 or is_shadowed(head, self.shell):
706 or is_shadowed(head, self.shell):
707 return None
707 return None
708
708
709 return self.prefilter_manager.get_handler_by_name('alias')
709 return self.prefilter_manager.get_handler_by_name('alias')
710
710
711
711
712 class PythonOpsChecker(PrefilterChecker):
712 class PythonOpsChecker(PrefilterChecker):
713
713
714 priority = Int(900, config=True)
714 priority = Int(900, config=True)
715
715
716 def check(self, line_info):
716 def check(self, line_info):
717 """If the 'rest' of the line begins with a function call or pretty much
717 """If the 'rest' of the line begins with a function call or pretty much
718 any python operator, we should simply execute the line (regardless of
718 any python operator, we should simply execute the line (regardless of
719 whether or not there's a possible autocall expansion). This avoids
719 whether or not there's a possible autocall expansion). This avoids
720 spurious (and very confusing) geattr() accesses."""
720 spurious (and very confusing) geattr() accesses."""
721 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
721 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
722 return self.prefilter_manager.get_handler_by_name('normal')
722 return self.prefilter_manager.get_handler_by_name('normal')
723 else:
723 else:
724 return None
724 return None
725
725
726
726
727 class AutocallChecker(PrefilterChecker):
727 class AutocallChecker(PrefilterChecker):
728
728
729 priority = Int(1000, config=True)
729 priority = Int(1000, config=True)
730
730
731 def check(self, line_info):
731 def check(self, line_info):
732 "Check if the initial word/function is callable and autocall is on."
732 "Check if the initial word/function is callable and autocall is on."
733 if not self.shell.autocall:
733 if not self.shell.autocall:
734 return None
734 return None
735
735
736 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
736 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
737 if not oinfo['found']:
737 if not oinfo['found']:
738 return None
738 return None
739
739
740 if callable(oinfo['obj']) \
740 if callable(oinfo['obj']) \
741 and (not re_exclude_auto.match(line_info.the_rest)) \
741 and (not re_exclude_auto.match(line_info.the_rest)) \
742 and re_fun_name.match(line_info.ifun):
742 and re_fun_name.match(line_info.ifun):
743 return self.prefilter_manager.get_handler_by_name('auto')
743 return self.prefilter_manager.get_handler_by_name('auto')
744 else:
744 else:
745 return None
745 return None
746
746
747
747
748 #-----------------------------------------------------------------------------
748 #-----------------------------------------------------------------------------
749 # Prefilter handlers
749 # Prefilter handlers
750 #-----------------------------------------------------------------------------
750 #-----------------------------------------------------------------------------
751
751
752
752
753 class PrefilterHandler(Configurable):
753 class PrefilterHandler(Configurable):
754
754
755 handler_name = Str('normal')
755 handler_name = Str('normal')
756 esc_strings = List([])
756 esc_strings = List([])
757 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
757 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
758 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
758 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
759
759
760 def __init__(self, shell=None, prefilter_manager=None, config=None):
760 def __init__(self, shell=None, prefilter_manager=None, config=None):
761 super(PrefilterHandler, self).__init__(
761 super(PrefilterHandler, self).__init__(
762 shell=shell, prefilter_manager=prefilter_manager, config=config
762 shell=shell, prefilter_manager=prefilter_manager, config=config
763 )
763 )
764 self.prefilter_manager.register_handler(
764 self.prefilter_manager.register_handler(
765 self.handler_name,
765 self.handler_name,
766 self,
766 self,
767 self.esc_strings
767 self.esc_strings
768 )
768 )
769
769
770 def handle(self, line_info):
770 def handle(self, line_info):
771 # print "normal: ", line_info
771 # print "normal: ", line_info
772 """Handle normal input lines. Use as a template for handlers."""
772 """Handle normal input lines. Use as a template for handlers."""
773
773
774 # With autoindent on, we need some way to exit the input loop, and I
774 # With autoindent on, we need some way to exit the input loop, and I
775 # don't want to force the user to have to backspace all the way to
775 # don't want to force the user to have to backspace all the way to
776 # clear the line. The rule will be in this case, that either two
776 # clear the line. The rule will be in this case, that either two
777 # lines of pure whitespace in a row, or a line of pure whitespace but
777 # lines of pure whitespace in a row, or a line of pure whitespace but
778 # of a size different to the indent level, will exit the input loop.
778 # of a size different to the indent level, will exit the input loop.
779 line = line_info.line
779 line = line_info.line
780 continue_prompt = line_info.continue_prompt
780 continue_prompt = line_info.continue_prompt
781
781
782 if (continue_prompt and
782 if (continue_prompt and
783 self.shell.autoindent and
783 self.shell.autoindent and
784 line.isspace() and
784 line.isspace() and
785
785
786 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2
786 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2
787 or
787 or
788 not self.shell.buffer
788 not self.shell.buffer
789 or
789 or
790 (self.shell.buffer[-1]).isspace()
790 (self.shell.buffer[-1]).isspace()
791 )
791 )
792 ):
792 ):
793 line = ''
793 line = ''
794
794
795 self.shell.log(line, line, continue_prompt)
795 self.shell.log(line, line, continue_prompt)
796 return line
796 return line
797
797
798 def __str__(self):
798 def __str__(self):
799 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
799 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
800
800
801
801
802 class AliasHandler(PrefilterHandler):
802 class AliasHandler(PrefilterHandler):
803
803
804 handler_name = Str('alias')
804 handler_name = Str('alias')
805
805
806 def handle(self, line_info):
806 def handle(self, line_info):
807 """Handle alias input lines. """
807 """Handle alias input lines. """
808 transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
808 transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
809 # pre is needed, because it carries the leading whitespace. Otherwise
809 # pre is needed, because it carries the leading whitespace. Otherwise
810 # aliases won't work in indented sections.
810 # aliases won't work in indented sections.
811 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
811 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
812 make_quoted_expr(transformed))
812 make_quoted_expr(transformed))
813
813
814 self.shell.log(line_info.line, line_out, line_info.continue_prompt)
814 self.shell.log(line_info.line, line_out, line_info.continue_prompt)
815 return line_out
815 return line_out
816
816
817
817
818 class ShellEscapeHandler(PrefilterHandler):
818 class ShellEscapeHandler(PrefilterHandler):
819
819
820 handler_name = Str('shell')
820 handler_name = Str('shell')
821 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
821 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
822
822
823 def handle(self, line_info):
823 def handle(self, line_info):
824 """Execute the line in a shell, empty return value"""
824 """Execute the line in a shell, empty return value"""
825 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
825 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
826
826
827 line = line_info.line
827 line = line_info.line
828 if line.lstrip().startswith(ESC_SH_CAP):
828 if line.lstrip().startswith(ESC_SH_CAP):
829 # rewrite LineInfo's line, ifun and the_rest to properly hold the
829 # rewrite LineInfo's line, ifun and the_rest to properly hold the
830 # call to %sx and the actual command to be executed, so
830 # call to %sx and the actual command to be executed, so
831 # handle_magic can work correctly. Note that this works even if
831 # handle_magic can work correctly. Note that this works even if
832 # the line is indented, so it handles multi_line_specials
832 # the line is indented, so it handles multi_line_specials
833 # properly.
833 # properly.
834 new_rest = line.lstrip()[2:]
834 new_rest = line.lstrip()[2:]
835 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
835 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
836 line_info.ifun = 'sx'
836 line_info.ifun = 'sx'
837 line_info.the_rest = new_rest
837 line_info.the_rest = new_rest
838 return magic_handler.handle(line_info)
838 return magic_handler.handle(line_info)
839 else:
839 else:
840 cmd = line.lstrip().lstrip(ESC_SHELL)
840 cmd = line.lstrip().lstrip(ESC_SHELL)
841 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
841 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
842 make_quoted_expr(cmd))
842 make_quoted_expr(cmd))
843 # update cache/log and return
843 # update cache/log and return
844 self.shell.log(line, line_out, line_info.continue_prompt)
844 self.shell.log(line, line_out, line_info.continue_prompt)
845 return line_out
845 return line_out
846
846
847
847
848 class MagicHandler(PrefilterHandler):
848 class MagicHandler(PrefilterHandler):
849
849
850 handler_name = Str('magic')
850 handler_name = Str('magic')
851 esc_strings = List([ESC_MAGIC])
851 esc_strings = List([ESC_MAGIC])
852
852
853 def handle(self, line_info):
853 def handle(self, line_info):
854 """Execute magic functions."""
854 """Execute magic functions."""
855 ifun = line_info.ifun
855 ifun = line_info.ifun
856 the_rest = line_info.the_rest
856 the_rest = line_info.the_rest
857 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
857 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
858 make_quoted_expr(ifun + " " + the_rest))
858 make_quoted_expr(ifun + " " + the_rest))
859 self.shell.log(line_info.line, cmd, line_info.continue_prompt)
859 self.shell.log(line_info.line, cmd, line_info.continue_prompt)
860 return cmd
860 return cmd
861
861
862
862
863 class AutoHandler(PrefilterHandler):
863 class AutoHandler(PrefilterHandler):
864
864
865 handler_name = Str('auto')
865 handler_name = Str('auto')
866 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
866 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
867
867
868 def handle(self, line_info):
868 def handle(self, line_info):
869 """Handle lines which can be auto-executed, quoting if requested."""
869 """Handle lines which can be auto-executed, quoting if requested."""
870 line = line_info.line
870 line = line_info.line
871 ifun = line_info.ifun
871 ifun = line_info.ifun
872 the_rest = line_info.the_rest
872 the_rest = line_info.the_rest
873 pre = line_info.pre
873 pre = line_info.pre
874 continue_prompt = line_info.continue_prompt
874 continue_prompt = line_info.continue_prompt
875 obj = line_info.ofind(self)['obj']
875 obj = line_info.ofind(self)['obj']
876 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
876 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
877
877
878 # This should only be active for single-line input!
878 # This should only be active for single-line input!
879 if continue_prompt:
879 if continue_prompt:
880 self.shell.log(line,line,continue_prompt)
880 self.shell.log(line,line,continue_prompt)
881 return line
881 return line
882
882
883 force_auto = isinstance(obj, IPyAutocall)
883 force_auto = isinstance(obj, IPyAutocall)
884 auto_rewrite = True
884 auto_rewrite = True
885
885
886 if pre == ESC_QUOTE:
886 if pre == ESC_QUOTE:
887 # Auto-quote splitting on whitespace
887 # Auto-quote splitting on whitespace
888 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
888 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
889 elif pre == ESC_QUOTE2:
889 elif pre == ESC_QUOTE2:
890 # Auto-quote whole string
890 # Auto-quote whole string
891 newcmd = '%s("%s")' % (ifun,the_rest)
891 newcmd = '%s("%s")' % (ifun,the_rest)
892 elif pre == ESC_PAREN:
892 elif pre == ESC_PAREN:
893 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
893 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
894 else:
894 else:
895 # Auto-paren.
895 # Auto-paren.
896 # We only apply it to argument-less calls if the autocall
896 # We only apply it to argument-less calls if the autocall
897 # parameter is set to 2. We only need to check that autocall is <
897 # parameter is set to 2. We only need to check that autocall is <
898 # 2, since this function isn't called unless it's at least 1.
898 # 2, since this function isn't called unless it's at least 1.
899 if not the_rest and (self.shell.autocall < 2) and not force_auto:
899 if not the_rest and (self.shell.autocall < 2) and not force_auto:
900 newcmd = '%s %s' % (ifun,the_rest)
900 newcmd = '%s %s' % (ifun,the_rest)
901 auto_rewrite = False
901 auto_rewrite = False
902 else:
902 else:
903 if not force_auto and the_rest.startswith('['):
903 if not force_auto and the_rest.startswith('['):
904 if hasattr(obj,'__getitem__'):
904 if hasattr(obj,'__getitem__'):
905 # Don't autocall in this case: item access for an object
905 # Don't autocall in this case: item access for an object
906 # which is BOTH callable and implements __getitem__.
906 # which is BOTH callable and implements __getitem__.
907 newcmd = '%s %s' % (ifun,the_rest)
907 newcmd = '%s %s' % (ifun,the_rest)
908 auto_rewrite = False
908 auto_rewrite = False
909 else:
909 else:
910 # if the object doesn't support [] access, go ahead and
910 # if the object doesn't support [] access, go ahead and
911 # autocall
911 # autocall
912 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
912 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
913 elif the_rest.endswith(';'):
913 elif the_rest.endswith(';'):
914 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
914 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
915 else:
915 else:
916 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
916 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
917
917
918 if auto_rewrite:
918 if auto_rewrite:
919 rw = self.shell.outputcache.prompt1.auto_rewrite() + newcmd
919 rw = self.shell.outputcache.prompt1.auto_rewrite() + newcmd
920
920
921 try:
921 try:
922 # plain ascii works better w/ pyreadline, on some machines, so
922 # plain ascii works better w/ pyreadline, on some machines, so
923 # we use it and only print uncolored rewrite if we have unicode
923 # we use it and only print uncolored rewrite if we have unicode
924 rw = str(rw)
924 rw = str(rw)
925 print >>Term.cout, rw
925 print >>IPython.utils.io.Term.cout, rw
926 except UnicodeEncodeError:
926 except UnicodeEncodeError:
927 print "-------------->" + newcmd
927 print "-------------->" + newcmd
928
928
929 # log what is now valid Python, not the actual user input (without the
929 # log what is now valid Python, not the actual user input (without the
930 # final newline)
930 # final newline)
931 self.shell.log(line,newcmd,continue_prompt)
931 self.shell.log(line,newcmd,continue_prompt)
932 return newcmd
932 return newcmd
933
933
934
934
935 class HelpHandler(PrefilterHandler):
935 class HelpHandler(PrefilterHandler):
936
936
937 handler_name = Str('help')
937 handler_name = Str('help')
938 esc_strings = List([ESC_HELP])
938 esc_strings = List([ESC_HELP])
939
939
940 def handle(self, line_info):
940 def handle(self, line_info):
941 """Try to get some help for the object.
941 """Try to get some help for the object.
942
942
943 obj? or ?obj -> basic information.
943 obj? or ?obj -> basic information.
944 obj?? or ??obj -> more details.
944 obj?? or ??obj -> more details.
945 """
945 """
946 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
946 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
947 line = line_info.line
947 line = line_info.line
948 # We need to make sure that we don't process lines which would be
948 # We need to make sure that we don't process lines which would be
949 # otherwise valid python, such as "x=1 # what?"
949 # otherwise valid python, such as "x=1 # what?"
950 try:
950 try:
951 codeop.compile_command(line)
951 codeop.compile_command(line)
952 except SyntaxError:
952 except SyntaxError:
953 # We should only handle as help stuff which is NOT valid syntax
953 # We should only handle as help stuff which is NOT valid syntax
954 if line[0]==ESC_HELP:
954 if line[0]==ESC_HELP:
955 line = line[1:]
955 line = line[1:]
956 elif line[-1]==ESC_HELP:
956 elif line[-1]==ESC_HELP:
957 line = line[:-1]
957 line = line[:-1]
958 self.shell.log(line, '#?'+line, line_info.continue_prompt)
958 self.shell.log(line, '#?'+line, line_info.continue_prompt)
959 if line:
959 if line:
960 #print 'line:<%r>' % line # dbg
960 #print 'line:<%r>' % line # dbg
961 self.shell.magic_pinfo(line)
961 self.shell.magic_pinfo(line)
962 else:
962 else:
963 page(self.shell.usage, screen_lines=self.shell.usable_screen_length)
963 page(self.shell.usage, screen_lines=self.shell.usable_screen_length)
964 return '' # Empty string is needed here!
964 return '' # Empty string is needed here!
965 except:
965 except:
966 raise
966 raise
967 # Pass any other exceptions through to the normal handler
967 # Pass any other exceptions through to the normal handler
968 return normal_handler.handle(line_info)
968 return normal_handler.handle(line_info)
969 else:
969 else:
970 # If the code compiles ok, we should handle it normally
970 # If the code compiles ok, we should handle it normally
971 return normal_handler.handle(line_info)
971 return normal_handler.handle(line_info)
972
972
973
973
974 class EmacsHandler(PrefilterHandler):
974 class EmacsHandler(PrefilterHandler):
975
975
976 handler_name = Str('emacs')
976 handler_name = Str('emacs')
977 esc_strings = List([])
977 esc_strings = List([])
978
978
979 def handle(self, line_info):
979 def handle(self, line_info):
980 """Handle input lines marked by python-mode."""
980 """Handle input lines marked by python-mode."""
981
981
982 # Currently, nothing is done. Later more functionality can be added
982 # Currently, nothing is done. Later more functionality can be added
983 # here if needed.
983 # here if needed.
984
984
985 # The input cache shouldn't be updated
985 # The input cache shouldn't be updated
986 return line_info.line
986 return line_info.line
987
987
988
988
989 #-----------------------------------------------------------------------------
989 #-----------------------------------------------------------------------------
990 # Defaults
990 # Defaults
991 #-----------------------------------------------------------------------------
991 #-----------------------------------------------------------------------------
992
992
993
993
994 _default_transformers = [
994 _default_transformers = [
995 AssignSystemTransformer,
995 AssignSystemTransformer,
996 AssignMagicTransformer,
996 AssignMagicTransformer,
997 PyPromptTransformer,
997 PyPromptTransformer,
998 IPyPromptTransformer,
998 IPyPromptTransformer,
999 ]
999 ]
1000
1000
1001 _default_checkers = [
1001 _default_checkers = [
1002 EmacsChecker,
1002 EmacsChecker,
1003 ShellEscapeChecker,
1003 ShellEscapeChecker,
1004 IPyAutocallChecker,
1004 IPyAutocallChecker,
1005 MultiLineMagicChecker,
1005 MultiLineMagicChecker,
1006 EscCharsChecker,
1006 EscCharsChecker,
1007 AssignmentChecker,
1007 AssignmentChecker,
1008 AutoMagicChecker,
1008 AutoMagicChecker,
1009 AliasChecker,
1009 AliasChecker,
1010 PythonOpsChecker,
1010 PythonOpsChecker,
1011 AutocallChecker
1011 AutocallChecker
1012 ]
1012 ]
1013
1013
1014 _default_handlers = [
1014 _default_handlers = [
1015 PrefilterHandler,
1015 PrefilterHandler,
1016 AliasHandler,
1016 AliasHandler,
1017 ShellEscapeHandler,
1017 ShellEscapeHandler,
1018 MagicHandler,
1018 MagicHandler,
1019 AutoHandler,
1019 AutoHandler,
1020 HelpHandler,
1020 HelpHandler,
1021 EmacsHandler
1021 EmacsHandler
1022 ]
1022 ]
@@ -1,639 +1,639 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Classes for handling input/output prompts.
3 Classes for handling input/output prompts.
4 """
4 """
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2008-2009 The IPython Development Team
7 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
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
15
16 import __builtin__
16 import __builtin__
17 import os
17 import os
18 import re
18 import re
19 import socket
19 import socket
20 import sys
20 import sys
21
21
22 from IPython.core import release
22 from IPython.core import release
23 from IPython.external.Itpl import ItplNS
23 from IPython.external.Itpl import ItplNS
24 from IPython.core.error import TryNext
24 from IPython.core.error import TryNext
25 from IPython.utils import coloransi
25 from IPython.utils import coloransi
26 import IPython.utils.generics
26 import IPython.utils.generics
27 from IPython.utils.warn import warn
27 from IPython.utils.warn import warn
28 from IPython.utils.io import Term
28 import IPython.utils.io
29
29
30 #****************************************************************************
30 #****************************************************************************
31 #Color schemes for Prompts.
31 #Color schemes for Prompts.
32
32
33 PromptColors = coloransi.ColorSchemeTable()
33 PromptColors = coloransi.ColorSchemeTable()
34 InputColors = coloransi.InputTermColors # just a shorthand
34 InputColors = coloransi.InputTermColors # just a shorthand
35 Colors = coloransi.TermColors # just a shorthand
35 Colors = coloransi.TermColors # just a shorthand
36
36
37 PromptColors.add_scheme(coloransi.ColorScheme(
37 PromptColors.add_scheme(coloransi.ColorScheme(
38 'NoColor',
38 'NoColor',
39 in_prompt = InputColors.NoColor, # Input prompt
39 in_prompt = InputColors.NoColor, # Input prompt
40 in_number = InputColors.NoColor, # Input prompt number
40 in_number = InputColors.NoColor, # Input prompt number
41 in_prompt2 = InputColors.NoColor, # Continuation prompt
41 in_prompt2 = InputColors.NoColor, # Continuation prompt
42 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
42 in_normal = InputColors.NoColor, # color off (usu. Colors.Normal)
43
43
44 out_prompt = Colors.NoColor, # Output prompt
44 out_prompt = Colors.NoColor, # Output prompt
45 out_number = Colors.NoColor, # Output prompt number
45 out_number = Colors.NoColor, # Output prompt number
46
46
47 normal = Colors.NoColor # color off (usu. Colors.Normal)
47 normal = Colors.NoColor # color off (usu. Colors.Normal)
48 ))
48 ))
49
49
50 # make some schemes as instances so we can copy them for modification easily:
50 # make some schemes as instances so we can copy them for modification easily:
51 __PColLinux = coloransi.ColorScheme(
51 __PColLinux = coloransi.ColorScheme(
52 'Linux',
52 'Linux',
53 in_prompt = InputColors.Green,
53 in_prompt = InputColors.Green,
54 in_number = InputColors.LightGreen,
54 in_number = InputColors.LightGreen,
55 in_prompt2 = InputColors.Green,
55 in_prompt2 = InputColors.Green,
56 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
56 in_normal = InputColors.Normal, # color off (usu. Colors.Normal)
57
57
58 out_prompt = Colors.Red,
58 out_prompt = Colors.Red,
59 out_number = Colors.LightRed,
59 out_number = Colors.LightRed,
60
60
61 normal = Colors.Normal
61 normal = Colors.Normal
62 )
62 )
63 # Don't forget to enter it into the table!
63 # Don't forget to enter it into the table!
64 PromptColors.add_scheme(__PColLinux)
64 PromptColors.add_scheme(__PColLinux)
65
65
66 # Slightly modified Linux for light backgrounds
66 # Slightly modified Linux for light backgrounds
67 __PColLightBG = __PColLinux.copy('LightBG')
67 __PColLightBG = __PColLinux.copy('LightBG')
68
68
69 __PColLightBG.colors.update(
69 __PColLightBG.colors.update(
70 in_prompt = InputColors.Blue,
70 in_prompt = InputColors.Blue,
71 in_number = InputColors.LightBlue,
71 in_number = InputColors.LightBlue,
72 in_prompt2 = InputColors.Blue
72 in_prompt2 = InputColors.Blue
73 )
73 )
74 PromptColors.add_scheme(__PColLightBG)
74 PromptColors.add_scheme(__PColLightBG)
75
75
76 del Colors,InputColors
76 del Colors,InputColors
77
77
78 #-----------------------------------------------------------------------------
78 #-----------------------------------------------------------------------------
79 def multiple_replace(dict, text):
79 def multiple_replace(dict, text):
80 """ Replace in 'text' all occurences of any key in the given
80 """ Replace in 'text' all occurences of any key in the given
81 dictionary by its corresponding value. Returns the new string."""
81 dictionary by its corresponding value. Returns the new string."""
82
82
83 # Function by Xavier Defrang, originally found at:
83 # Function by Xavier Defrang, originally found at:
84 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
84 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330
85
85
86 # Create a regular expression from the dictionary keys
86 # Create a regular expression from the dictionary keys
87 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
87 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
88 # For each match, look-up corresponding value in dictionary
88 # For each match, look-up corresponding value in dictionary
89 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
89 return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
90
90
91 #-----------------------------------------------------------------------------
91 #-----------------------------------------------------------------------------
92 # Special characters that can be used in prompt templates, mainly bash-like
92 # Special characters that can be used in prompt templates, mainly bash-like
93
93
94 # If $HOME isn't defined (Windows), make it an absurd string so that it can
94 # If $HOME isn't defined (Windows), make it an absurd string so that it can
95 # never be expanded out into '~'. Basically anything which can never be a
95 # never be expanded out into '~'. Basically anything which can never be a
96 # reasonable directory name will do, we just want the $HOME -> '~' operation
96 # reasonable directory name will do, we just want the $HOME -> '~' operation
97 # to become a no-op. We pre-compute $HOME here so it's not done on every
97 # to become a no-op. We pre-compute $HOME here so it's not done on every
98 # prompt call.
98 # prompt call.
99
99
100 # FIXME:
100 # FIXME:
101
101
102 # - This should be turned into a class which does proper namespace management,
102 # - This should be turned into a class which does proper namespace management,
103 # since the prompt specials need to be evaluated in a certain namespace.
103 # since the prompt specials need to be evaluated in a certain namespace.
104 # Currently it's just globals, which need to be managed manually by code
104 # Currently it's just globals, which need to be managed manually by code
105 # below.
105 # below.
106
106
107 # - I also need to split up the color schemes from the prompt specials
107 # - I also need to split up the color schemes from the prompt specials
108 # somehow. I don't have a clean design for that quite yet.
108 # somehow. I don't have a clean design for that quite yet.
109
109
110 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
110 HOME = os.environ.get("HOME","//////:::::ZZZZZ,,,~~~")
111
111
112 # We precompute a few more strings here for the prompt_specials, which are
112 # We precompute a few more strings here for the prompt_specials, which are
113 # fixed once ipython starts. This reduces the runtime overhead of computing
113 # fixed once ipython starts. This reduces the runtime overhead of computing
114 # prompt strings.
114 # prompt strings.
115 USER = os.environ.get("USER")
115 USER = os.environ.get("USER")
116 HOSTNAME = socket.gethostname()
116 HOSTNAME = socket.gethostname()
117 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
117 HOSTNAME_SHORT = HOSTNAME.split(".")[0]
118 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
118 ROOT_SYMBOL = "$#"[os.name=='nt' or os.getuid()==0]
119
119
120 prompt_specials_color = {
120 prompt_specials_color = {
121 # Prompt/history count
121 # Prompt/history count
122 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
122 '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
123 r'\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
123 r'\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
124 # Just the prompt counter number, WITHOUT any coloring wrappers, so users
124 # Just the prompt counter number, WITHOUT any coloring wrappers, so users
125 # can get numbers displayed in whatever color they want.
125 # can get numbers displayed in whatever color they want.
126 r'\N': '${self.cache.prompt_count}',
126 r'\N': '${self.cache.prompt_count}',
127
127
128 # Prompt/history count, with the actual digits replaced by dots. Used
128 # Prompt/history count, with the actual digits replaced by dots. Used
129 # mainly in continuation prompts (prompt_in2)
129 # mainly in continuation prompts (prompt_in2)
130 #r'\D': '${"."*len(str(self.cache.prompt_count))}',
130 #r'\D': '${"."*len(str(self.cache.prompt_count))}',
131
131
132 # More robust form of the above expression, that uses the __builtin__
132 # More robust form of the above expression, that uses the __builtin__
133 # module. Note that we can NOT use __builtins__ (note the 's'), because
133 # module. Note that we can NOT use __builtins__ (note the 's'), because
134 # that can either be a dict or a module, and can even mutate at runtime,
134 # that can either be a dict or a module, and can even mutate at runtime,
135 # depending on the context (Python makes no guarantees on it). In
135 # depending on the context (Python makes no guarantees on it). In
136 # contrast, __builtin__ is always a module object, though it must be
136 # contrast, __builtin__ is always a module object, though it must be
137 # explicitly imported.
137 # explicitly imported.
138 r'\D': '${"."*__builtin__.len(__builtin__.str(self.cache.prompt_count))}',
138 r'\D': '${"."*__builtin__.len(__builtin__.str(self.cache.prompt_count))}',
139
139
140 # Current working directory
140 # Current working directory
141 r'\w': '${os.getcwd()}',
141 r'\w': '${os.getcwd()}',
142 # Current time
142 # Current time
143 r'\t' : '${time.strftime("%H:%M:%S")}',
143 r'\t' : '${time.strftime("%H:%M:%S")}',
144 # Basename of current working directory.
144 # Basename of current working directory.
145 # (use os.sep to make this portable across OSes)
145 # (use os.sep to make this portable across OSes)
146 r'\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
146 r'\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
147 # These X<N> are an extension to the normal bash prompts. They return
147 # These X<N> are an extension to the normal bash prompts. They return
148 # N terms of the path, after replacing $HOME with '~'
148 # N terms of the path, after replacing $HOME with '~'
149 r'\X0': '${os.getcwd().replace("%s","~")}' % HOME,
149 r'\X0': '${os.getcwd().replace("%s","~")}' % HOME,
150 r'\X1': '${self.cwd_filt(1)}',
150 r'\X1': '${self.cwd_filt(1)}',
151 r'\X2': '${self.cwd_filt(2)}',
151 r'\X2': '${self.cwd_filt(2)}',
152 r'\X3': '${self.cwd_filt(3)}',
152 r'\X3': '${self.cwd_filt(3)}',
153 r'\X4': '${self.cwd_filt(4)}',
153 r'\X4': '${self.cwd_filt(4)}',
154 r'\X5': '${self.cwd_filt(5)}',
154 r'\X5': '${self.cwd_filt(5)}',
155 # Y<N> are similar to X<N>, but they show '~' if it's the directory
155 # Y<N> are similar to X<N>, but they show '~' if it's the directory
156 # N+1 in the list. Somewhat like %cN in tcsh.
156 # N+1 in the list. Somewhat like %cN in tcsh.
157 r'\Y0': '${self.cwd_filt2(0)}',
157 r'\Y0': '${self.cwd_filt2(0)}',
158 r'\Y1': '${self.cwd_filt2(1)}',
158 r'\Y1': '${self.cwd_filt2(1)}',
159 r'\Y2': '${self.cwd_filt2(2)}',
159 r'\Y2': '${self.cwd_filt2(2)}',
160 r'\Y3': '${self.cwd_filt2(3)}',
160 r'\Y3': '${self.cwd_filt2(3)}',
161 r'\Y4': '${self.cwd_filt2(4)}',
161 r'\Y4': '${self.cwd_filt2(4)}',
162 r'\Y5': '${self.cwd_filt2(5)}',
162 r'\Y5': '${self.cwd_filt2(5)}',
163 # Hostname up to first .
163 # Hostname up to first .
164 r'\h': HOSTNAME_SHORT,
164 r'\h': HOSTNAME_SHORT,
165 # Full hostname
165 # Full hostname
166 r'\H': HOSTNAME,
166 r'\H': HOSTNAME,
167 # Username of current user
167 # Username of current user
168 r'\u': USER,
168 r'\u': USER,
169 # Escaped '\'
169 # Escaped '\'
170 '\\\\': '\\',
170 '\\\\': '\\',
171 # Newline
171 # Newline
172 r'\n': '\n',
172 r'\n': '\n',
173 # Carriage return
173 # Carriage return
174 r'\r': '\r',
174 r'\r': '\r',
175 # Release version
175 # Release version
176 r'\v': release.version,
176 r'\v': release.version,
177 # Root symbol ($ or #)
177 # Root symbol ($ or #)
178 r'\$': ROOT_SYMBOL,
178 r'\$': ROOT_SYMBOL,
179 }
179 }
180
180
181 # A copy of the prompt_specials dictionary but with all color escapes removed,
181 # A copy of the prompt_specials dictionary but with all color escapes removed,
182 # so we can correctly compute the prompt length for the auto_rewrite method.
182 # so we can correctly compute the prompt length for the auto_rewrite method.
183 prompt_specials_nocolor = prompt_specials_color.copy()
183 prompt_specials_nocolor = prompt_specials_color.copy()
184 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
184 prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
185 prompt_specials_nocolor[r'\#'] = '${self.cache.prompt_count}'
185 prompt_specials_nocolor[r'\#'] = '${self.cache.prompt_count}'
186
186
187 # Add in all the InputTermColors color escapes as valid prompt characters.
187 # Add in all the InputTermColors color escapes as valid prompt characters.
188 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
188 # They all get added as \\C_COLORNAME, so that we don't have any conflicts
189 # with a color name which may begin with a letter used by any other of the
189 # with a color name which may begin with a letter used by any other of the
190 # allowed specials. This of course means that \\C will never be allowed for
190 # allowed specials. This of course means that \\C will never be allowed for
191 # anything else.
191 # anything else.
192 input_colors = coloransi.InputTermColors
192 input_colors = coloransi.InputTermColors
193 for _color in dir(input_colors):
193 for _color in dir(input_colors):
194 if _color[0] != '_':
194 if _color[0] != '_':
195 c_name = r'\C_'+_color
195 c_name = r'\C_'+_color
196 prompt_specials_color[c_name] = getattr(input_colors,_color)
196 prompt_specials_color[c_name] = getattr(input_colors,_color)
197 prompt_specials_nocolor[c_name] = ''
197 prompt_specials_nocolor[c_name] = ''
198
198
199 # we default to no color for safety. Note that prompt_specials is a global
199 # we default to no color for safety. Note that prompt_specials is a global
200 # variable used by all prompt objects.
200 # variable used by all prompt objects.
201 prompt_specials = prompt_specials_nocolor
201 prompt_specials = prompt_specials_nocolor
202
202
203 #-----------------------------------------------------------------------------
203 #-----------------------------------------------------------------------------
204 def str_safe(arg):
204 def str_safe(arg):
205 """Convert to a string, without ever raising an exception.
205 """Convert to a string, without ever raising an exception.
206
206
207 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
207 If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
208 error message."""
208 error message."""
209
209
210 try:
210 try:
211 out = str(arg)
211 out = str(arg)
212 except UnicodeError:
212 except UnicodeError:
213 try:
213 try:
214 out = arg.encode('utf_8','replace')
214 out = arg.encode('utf_8','replace')
215 except Exception,msg:
215 except Exception,msg:
216 # let's keep this little duplication here, so that the most common
216 # let's keep this little duplication here, so that the most common
217 # case doesn't suffer from a double try wrapping.
217 # case doesn't suffer from a double try wrapping.
218 out = '<ERROR: %s>' % msg
218 out = '<ERROR: %s>' % msg
219 except Exception,msg:
219 except Exception,msg:
220 out = '<ERROR: %s>' % msg
220 out = '<ERROR: %s>' % msg
221 #raise # dbg
221 #raise # dbg
222 return out
222 return out
223
223
224 class BasePrompt(object):
224 class BasePrompt(object):
225 """Interactive prompt similar to Mathematica's."""
225 """Interactive prompt similar to Mathematica's."""
226
226
227 def _get_p_template(self):
227 def _get_p_template(self):
228 return self._p_template
228 return self._p_template
229
229
230 def _set_p_template(self,val):
230 def _set_p_template(self,val):
231 self._p_template = val
231 self._p_template = val
232 self.set_p_str()
232 self.set_p_str()
233
233
234 p_template = property(_get_p_template,_set_p_template,
234 p_template = property(_get_p_template,_set_p_template,
235 doc='Template for prompt string creation')
235 doc='Template for prompt string creation')
236
236
237 def __init__(self,cache,sep,prompt,pad_left=False):
237 def __init__(self,cache,sep,prompt,pad_left=False):
238
238
239 # Hack: we access information about the primary prompt through the
239 # Hack: we access information about the primary prompt through the
240 # cache argument. We need this, because we want the secondary prompt
240 # cache argument. We need this, because we want the secondary prompt
241 # to be aligned with the primary one. Color table info is also shared
241 # to be aligned with the primary one. Color table info is also shared
242 # by all prompt classes through the cache. Nice OO spaghetti code!
242 # by all prompt classes through the cache. Nice OO spaghetti code!
243 self.cache = cache
243 self.cache = cache
244 self.sep = sep
244 self.sep = sep
245
245
246 # regexp to count the number of spaces at the end of a prompt
246 # regexp to count the number of spaces at the end of a prompt
247 # expression, useful for prompt auto-rewriting
247 # expression, useful for prompt auto-rewriting
248 self.rspace = re.compile(r'(\s*)$')
248 self.rspace = re.compile(r'(\s*)$')
249 # Flag to left-pad prompt strings to match the length of the primary
249 # Flag to left-pad prompt strings to match the length of the primary
250 # prompt
250 # prompt
251 self.pad_left = pad_left
251 self.pad_left = pad_left
252
252
253 # Set template to create each actual prompt (where numbers change).
253 # Set template to create each actual prompt (where numbers change).
254 # Use a property
254 # Use a property
255 self.p_template = prompt
255 self.p_template = prompt
256 self.set_p_str()
256 self.set_p_str()
257
257
258 def set_p_str(self):
258 def set_p_str(self):
259 """ Set the interpolating prompt strings.
259 """ Set the interpolating prompt strings.
260
260
261 This must be called every time the color settings change, because the
261 This must be called every time the color settings change, because the
262 prompt_specials global may have changed."""
262 prompt_specials global may have changed."""
263
263
264 import os,time # needed in locals for prompt string handling
264 import os,time # needed in locals for prompt string handling
265 loc = locals()
265 loc = locals()
266 try:
266 try:
267 self.p_str = ItplNS('%s%s%s' %
267 self.p_str = ItplNS('%s%s%s' %
268 ('${self.sep}${self.col_p}',
268 ('${self.sep}${self.col_p}',
269 multiple_replace(prompt_specials, self.p_template),
269 multiple_replace(prompt_specials, self.p_template),
270 '${self.col_norm}'),self.cache.user_ns,loc)
270 '${self.col_norm}'),self.cache.user_ns,loc)
271
271
272 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
272 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
273 self.p_template),
273 self.p_template),
274 self.cache.user_ns,loc)
274 self.cache.user_ns,loc)
275 except:
275 except:
276 print "Illegal prompt template (check $ usage!):",self.p_template
276 print "Illegal prompt template (check $ usage!):",self.p_template
277 self.p_str = self.p_template
277 self.p_str = self.p_template
278 self.p_str_nocolor = self.p_template
278 self.p_str_nocolor = self.p_template
279
279
280 def write(self,msg): # dbg
280 def write(self,msg): # dbg
281 sys.stdout.write(msg)
281 sys.stdout.write(msg)
282 return ''
282 return ''
283
283
284 def __str__(self):
284 def __str__(self):
285 """Return a string form of the prompt.
285 """Return a string form of the prompt.
286
286
287 This for is useful for continuation and output prompts, since it is
287 This for is useful for continuation and output prompts, since it is
288 left-padded to match lengths with the primary one (if the
288 left-padded to match lengths with the primary one (if the
289 self.pad_left attribute is set)."""
289 self.pad_left attribute is set)."""
290
290
291 out_str = str_safe(self.p_str)
291 out_str = str_safe(self.p_str)
292 if self.pad_left:
292 if self.pad_left:
293 # We must find the amount of padding required to match lengths,
293 # We must find the amount of padding required to match lengths,
294 # taking the color escapes (which are invisible on-screen) into
294 # taking the color escapes (which are invisible on-screen) into
295 # account.
295 # account.
296 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
296 esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
297 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
297 format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
298 return format % out_str
298 return format % out_str
299 else:
299 else:
300 return out_str
300 return out_str
301
301
302 # these path filters are put in as methods so that we can control the
302 # these path filters are put in as methods so that we can control the
303 # namespace where the prompt strings get evaluated
303 # namespace where the prompt strings get evaluated
304 def cwd_filt(self,depth):
304 def cwd_filt(self,depth):
305 """Return the last depth elements of the current working directory.
305 """Return the last depth elements of the current working directory.
306
306
307 $HOME is always replaced with '~'.
307 $HOME is always replaced with '~'.
308 If depth==0, the full path is returned."""
308 If depth==0, the full path is returned."""
309
309
310 cwd = os.getcwd().replace(HOME,"~")
310 cwd = os.getcwd().replace(HOME,"~")
311 out = os.sep.join(cwd.split(os.sep)[-depth:])
311 out = os.sep.join(cwd.split(os.sep)[-depth:])
312 if out:
312 if out:
313 return out
313 return out
314 else:
314 else:
315 return os.sep
315 return os.sep
316
316
317 def cwd_filt2(self,depth):
317 def cwd_filt2(self,depth):
318 """Return the last depth elements of the current working directory.
318 """Return the last depth elements of the current working directory.
319
319
320 $HOME is always replaced with '~'.
320 $HOME is always replaced with '~'.
321 If depth==0, the full path is returned."""
321 If depth==0, the full path is returned."""
322
322
323 full_cwd = os.getcwd()
323 full_cwd = os.getcwd()
324 cwd = full_cwd.replace(HOME,"~").split(os.sep)
324 cwd = full_cwd.replace(HOME,"~").split(os.sep)
325 if '~' in cwd and len(cwd) == depth+1:
325 if '~' in cwd and len(cwd) == depth+1:
326 depth += 1
326 depth += 1
327 drivepart = ''
327 drivepart = ''
328 if sys.platform == 'win32' and len(cwd) > depth:
328 if sys.platform == 'win32' and len(cwd) > depth:
329 drivepart = os.path.splitdrive(full_cwd)[0]
329 drivepart = os.path.splitdrive(full_cwd)[0]
330 out = drivepart + '/'.join(cwd[-depth:])
330 out = drivepart + '/'.join(cwd[-depth:])
331
331
332 if out:
332 if out:
333 return out
333 return out
334 else:
334 else:
335 return os.sep
335 return os.sep
336
336
337 def __nonzero__(self):
337 def __nonzero__(self):
338 """Implement boolean behavior.
338 """Implement boolean behavior.
339
339
340 Checks whether the p_str attribute is non-empty"""
340 Checks whether the p_str attribute is non-empty"""
341
341
342 return bool(self.p_template)
342 return bool(self.p_template)
343
343
344 class Prompt1(BasePrompt):
344 class Prompt1(BasePrompt):
345 """Input interactive prompt similar to Mathematica's."""
345 """Input interactive prompt similar to Mathematica's."""
346
346
347 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
347 def __init__(self,cache,sep='\n',prompt='In [\\#]: ',pad_left=True):
348 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
348 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
349
349
350 def set_colors(self):
350 def set_colors(self):
351 self.set_p_str()
351 self.set_p_str()
352 Colors = self.cache.color_table.active_colors # shorthand
352 Colors = self.cache.color_table.active_colors # shorthand
353 self.col_p = Colors.in_prompt
353 self.col_p = Colors.in_prompt
354 self.col_num = Colors.in_number
354 self.col_num = Colors.in_number
355 self.col_norm = Colors.in_normal
355 self.col_norm = Colors.in_normal
356 # We need a non-input version of these escapes for the '--->'
356 # We need a non-input version of these escapes for the '--->'
357 # auto-call prompts used in the auto_rewrite() method.
357 # auto-call prompts used in the auto_rewrite() method.
358 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
358 self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
359 self.col_norm_ni = Colors.normal
359 self.col_norm_ni = Colors.normal
360
360
361 def __str__(self):
361 def __str__(self):
362 self.cache.prompt_count += 1
362 self.cache.prompt_count += 1
363 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
363 self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
364 return str_safe(self.p_str)
364 return str_safe(self.p_str)
365
365
366 def auto_rewrite(self):
366 def auto_rewrite(self):
367 """Print a string of the form '--->' which lines up with the previous
367 """Print a string of the form '--->' which lines up with the previous
368 input string. Useful for systems which re-write the user input when
368 input string. Useful for systems which re-write the user input when
369 handling automatically special syntaxes."""
369 handling automatically special syntaxes."""
370
370
371 curr = str(self.cache.last_prompt)
371 curr = str(self.cache.last_prompt)
372 nrspaces = len(self.rspace.search(curr).group())
372 nrspaces = len(self.rspace.search(curr).group())
373 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
373 return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
374 ' '*nrspaces,self.col_norm_ni)
374 ' '*nrspaces,self.col_norm_ni)
375
375
376 class PromptOut(BasePrompt):
376 class PromptOut(BasePrompt):
377 """Output interactive prompt similar to Mathematica's."""
377 """Output interactive prompt similar to Mathematica's."""
378
378
379 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
379 def __init__(self,cache,sep='',prompt='Out[\\#]: ',pad_left=True):
380 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
380 BasePrompt.__init__(self,cache,sep,prompt,pad_left)
381 if not self.p_template:
381 if not self.p_template:
382 self.__str__ = lambda: ''
382 self.__str__ = lambda: ''
383
383
384 def set_colors(self):
384 def set_colors(self):
385 self.set_p_str()
385 self.set_p_str()
386 Colors = self.cache.color_table.active_colors # shorthand
386 Colors = self.cache.color_table.active_colors # shorthand
387 self.col_p = Colors.out_prompt
387 self.col_p = Colors.out_prompt
388 self.col_num = Colors.out_number
388 self.col_num = Colors.out_number
389 self.col_norm = Colors.normal
389 self.col_norm = Colors.normal
390
390
391 class Prompt2(BasePrompt):
391 class Prompt2(BasePrompt):
392 """Interactive continuation prompt."""
392 """Interactive continuation prompt."""
393
393
394 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
394 def __init__(self,cache,prompt=' .\\D.: ',pad_left=True):
395 self.cache = cache
395 self.cache = cache
396 self.p_template = prompt
396 self.p_template = prompt
397 self.pad_left = pad_left
397 self.pad_left = pad_left
398 self.set_p_str()
398 self.set_p_str()
399
399
400 def set_p_str(self):
400 def set_p_str(self):
401 import os,time # needed in locals for prompt string handling
401 import os,time # needed in locals for prompt string handling
402 loc = locals()
402 loc = locals()
403 self.p_str = ItplNS('%s%s%s' %
403 self.p_str = ItplNS('%s%s%s' %
404 ('${self.col_p2}',
404 ('${self.col_p2}',
405 multiple_replace(prompt_specials, self.p_template),
405 multiple_replace(prompt_specials, self.p_template),
406 '$self.col_norm'),
406 '$self.col_norm'),
407 self.cache.user_ns,loc)
407 self.cache.user_ns,loc)
408 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
408 self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
409 self.p_template),
409 self.p_template),
410 self.cache.user_ns,loc)
410 self.cache.user_ns,loc)
411
411
412 def set_colors(self):
412 def set_colors(self):
413 self.set_p_str()
413 self.set_p_str()
414 Colors = self.cache.color_table.active_colors
414 Colors = self.cache.color_table.active_colors
415 self.col_p2 = Colors.in_prompt2
415 self.col_p2 = Colors.in_prompt2
416 self.col_norm = Colors.in_normal
416 self.col_norm = Colors.in_normal
417 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
417 # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
418 # updated their prompt_in2 definitions. Remove eventually.
418 # updated their prompt_in2 definitions. Remove eventually.
419 self.col_p = Colors.out_prompt
419 self.col_p = Colors.out_prompt
420 self.col_num = Colors.out_number
420 self.col_num = Colors.out_number
421
421
422
422
423 #-----------------------------------------------------------------------------
423 #-----------------------------------------------------------------------------
424 class CachedOutput:
424 class CachedOutput:
425 """Class for printing output from calculations while keeping a cache of
425 """Class for printing output from calculations while keeping a cache of
426 reults. It dynamically creates global variables prefixed with _ which
426 reults. It dynamically creates global variables prefixed with _ which
427 contain these results.
427 contain these results.
428
428
429 Meant to be used as a sys.displayhook replacement, providing numbered
429 Meant to be used as a sys.displayhook replacement, providing numbered
430 prompts and cache services.
430 prompts and cache services.
431
431
432 Initialize with initial and final values for cache counter (this defines
432 Initialize with initial and final values for cache counter (this defines
433 the maximum size of the cache."""
433 the maximum size of the cache."""
434
434
435 def __init__(self,shell,cache_size,Pprint,
435 def __init__(self,shell,cache_size,Pprint,
436 colors='NoColor',input_sep='\n',
436 colors='NoColor',input_sep='\n',
437 output_sep='\n',output_sep2='',
437 output_sep='\n',output_sep2='',
438 ps1 = None, ps2 = None,ps_out = None,pad_left=True):
438 ps1 = None, ps2 = None,ps_out = None,pad_left=True):
439
439
440 cache_size_min = 3
440 cache_size_min = 3
441 if cache_size <= 0:
441 if cache_size <= 0:
442 self.do_full_cache = 0
442 self.do_full_cache = 0
443 cache_size = 0
443 cache_size = 0
444 elif cache_size < cache_size_min:
444 elif cache_size < cache_size_min:
445 self.do_full_cache = 0
445 self.do_full_cache = 0
446 cache_size = 0
446 cache_size = 0
447 warn('caching was disabled (min value for cache size is %s).' %
447 warn('caching was disabled (min value for cache size is %s).' %
448 cache_size_min,level=3)
448 cache_size_min,level=3)
449 else:
449 else:
450 self.do_full_cache = 1
450 self.do_full_cache = 1
451
451
452 self.cache_size = cache_size
452 self.cache_size = cache_size
453 self.input_sep = input_sep
453 self.input_sep = input_sep
454
454
455 # we need a reference to the user-level namespace
455 # we need a reference to the user-level namespace
456 self.shell = shell
456 self.shell = shell
457 self.user_ns = shell.user_ns
457 self.user_ns = shell.user_ns
458 # and to the user's input
458 # and to the user's input
459 self.input_hist = shell.input_hist
459 self.input_hist = shell.input_hist
460 # and to the user's logger, for logging output
460 # and to the user's logger, for logging output
461 self.logger = shell.logger
461 self.logger = shell.logger
462
462
463 # Set input prompt strings and colors
463 # Set input prompt strings and colors
464 if cache_size == 0:
464 if cache_size == 0:
465 if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
465 if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
466 or ps1.find(r'\N') > -1:
466 or ps1.find(r'\N') > -1:
467 ps1 = '>>> '
467 ps1 = '>>> '
468 if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
468 if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
469 or ps2.find(r'\N') > -1:
469 or ps2.find(r'\N') > -1:
470 ps2 = '... '
470 ps2 = '... '
471 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
471 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
472 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
472 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
473 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
473 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
474
474
475 self.color_table = PromptColors
475 self.color_table = PromptColors
476 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
476 self.prompt1 = Prompt1(self,sep=input_sep,prompt=self.ps1_str,
477 pad_left=pad_left)
477 pad_left=pad_left)
478 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
478 self.prompt2 = Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
479 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
479 self.prompt_out = PromptOut(self,sep='',prompt=self.ps_out_str,
480 pad_left=pad_left)
480 pad_left=pad_left)
481 self.set_colors(colors)
481 self.set_colors(colors)
482
482
483 # other more normal stuff
483 # other more normal stuff
484 # b/c each call to the In[] prompt raises it by 1, even the first.
484 # b/c each call to the In[] prompt raises it by 1, even the first.
485 self.prompt_count = 0
485 self.prompt_count = 0
486 # Store the last prompt string each time, we need it for aligning
486 # Store the last prompt string each time, we need it for aligning
487 # continuation and auto-rewrite prompts
487 # continuation and auto-rewrite prompts
488 self.last_prompt = ''
488 self.last_prompt = ''
489 self.Pprint = Pprint
489 self.Pprint = Pprint
490 self.output_sep = output_sep
490 self.output_sep = output_sep
491 self.output_sep2 = output_sep2
491 self.output_sep2 = output_sep2
492 self._,self.__,self.___ = '','',''
492 self._,self.__,self.___ = '','',''
493 self.pprint_types = map(type,[(),[],{}])
493 self.pprint_types = map(type,[(),[],{}])
494
494
495 # these are deliberately global:
495 # these are deliberately global:
496 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
496 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
497 self.user_ns.update(to_user_ns)
497 self.user_ns.update(to_user_ns)
498
498
499 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
499 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
500 if p_str is None:
500 if p_str is None:
501 if self.do_full_cache:
501 if self.do_full_cache:
502 return cache_def
502 return cache_def
503 else:
503 else:
504 return no_cache_def
504 return no_cache_def
505 else:
505 else:
506 return p_str
506 return p_str
507
507
508 def set_colors(self,colors):
508 def set_colors(self,colors):
509 """Set the active color scheme and configure colors for the three
509 """Set the active color scheme and configure colors for the three
510 prompt subsystems."""
510 prompt subsystems."""
511
511
512 # FIXME: the prompt_specials global should be gobbled inside this
512 # FIXME: the prompt_specials global should be gobbled inside this
513 # class instead. Do it when cleaning up the whole 3-prompt system.
513 # class instead. Do it when cleaning up the whole 3-prompt system.
514 global prompt_specials
514 global prompt_specials
515 if colors.lower()=='nocolor':
515 if colors.lower()=='nocolor':
516 prompt_specials = prompt_specials_nocolor
516 prompt_specials = prompt_specials_nocolor
517 else:
517 else:
518 prompt_specials = prompt_specials_color
518 prompt_specials = prompt_specials_color
519
519
520 self.color_table.set_active_scheme(colors)
520 self.color_table.set_active_scheme(colors)
521 self.prompt1.set_colors()
521 self.prompt1.set_colors()
522 self.prompt2.set_colors()
522 self.prompt2.set_colors()
523 self.prompt_out.set_colors()
523 self.prompt_out.set_colors()
524
524
525 def __call__(self,arg=None):
525 def __call__(self,arg=None):
526 """Printing with history cache management.
526 """Printing with history cache management.
527
527
528 This is invoked everytime the interpreter needs to print, and is
528 This is invoked everytime the interpreter needs to print, and is
529 activated by setting the variable sys.displayhook to it."""
529 activated by setting the variable sys.displayhook to it."""
530
530
531 # If something injected a '_' variable in __builtin__, delete
531 # If something injected a '_' variable in __builtin__, delete
532 # ipython's automatic one so we don't clobber that. gettext() in
532 # ipython's automatic one so we don't clobber that. gettext() in
533 # particular uses _, so we need to stay away from it.
533 # particular uses _, so we need to stay away from it.
534 if '_' in __builtin__.__dict__:
534 if '_' in __builtin__.__dict__:
535 try:
535 try:
536 del self.user_ns['_']
536 del self.user_ns['_']
537 except KeyError:
537 except KeyError:
538 pass
538 pass
539 if arg is not None:
539 if arg is not None:
540 cout_write = Term.cout.write # fast lookup
540 cout_write = IPython.utils.io.Term.cout.write # fast lookup
541 # first handle the cache and counters
541 # first handle the cache and counters
542
542
543 # do not print output if input ends in ';'
543 # do not print output if input ends in ';'
544 try:
544 try:
545 if self.input_hist[self.prompt_count].endswith(';\n'):
545 if self.input_hist[self.prompt_count].endswith(';\n'):
546 return
546 return
547 except IndexError:
547 except IndexError:
548 # some uses of ipshellembed may fail here
548 # some uses of ipshellembed may fail here
549 pass
549 pass
550 # don't use print, puts an extra space
550 # don't use print, puts an extra space
551 cout_write(self.output_sep)
551 cout_write(self.output_sep)
552 outprompt = self.shell.hooks.generate_output_prompt()
552 outprompt = self.shell.hooks.generate_output_prompt()
553 # print "Got prompt: ", outprompt
553 # print "Got prompt: ", outprompt
554 if self.do_full_cache:
554 if self.do_full_cache:
555 cout_write(outprompt)
555 cout_write(outprompt)
556
556
557 # and now call a possibly user-defined print mechanism. Note that
557 # and now call a possibly user-defined print mechanism. Note that
558 # self.display typically prints as a side-effect, we don't do any
558 # self.display typically prints as a side-effect, we don't do any
559 # printing to stdout here.
559 # printing to stdout here.
560 try:
560 try:
561 manipulated_val = self.display(arg)
561 manipulated_val = self.display(arg)
562 except TypeError:
562 except TypeError:
563 # If the user's display hook didn't return a string we can
563 # If the user's display hook didn't return a string we can
564 # print, we're done. Happens commonly if they return None
564 # print, we're done. Happens commonly if they return None
565 cout_write('\n')
565 cout_write('\n')
566 return
566 return
567
567
568 # user display hooks can change the variable to be stored in
568 # user display hooks can change the variable to be stored in
569 # output history
569 # output history
570 if manipulated_val is not None:
570 if manipulated_val is not None:
571 arg = manipulated_val
571 arg = manipulated_val
572
572
573 # avoid recursive reference when displaying _oh/Out
573 # avoid recursive reference when displaying _oh/Out
574 if arg is not self.user_ns['_oh']:
574 if arg is not self.user_ns['_oh']:
575 self.update(arg)
575 self.update(arg)
576
576
577 if self.logger.log_output:
577 if self.logger.log_output:
578 self.logger.log_write(repr(arg),'output')
578 self.logger.log_write(repr(arg),'output')
579 cout_write(self.output_sep2)
579 cout_write(self.output_sep2)
580 Term.cout.flush()
580 IPython.utils.io.Term.cout.flush()
581
581
582 def _display(self,arg):
582 def _display(self,arg):
583 """Default printer method, uses pprint.
583 """Default printer method, uses pprint.
584
584
585 Do ip.set_hook("result_display", my_displayhook) for custom result
585 Do ip.set_hook("result_display", my_displayhook) for custom result
586 display, e.g. when your own objects need special formatting.
586 display, e.g. when your own objects need special formatting.
587 """
587 """
588 try:
588 try:
589 return IPython.utils.generics.result_display(arg)
589 return IPython.utils.generics.result_display(arg)
590 except TryNext:
590 except TryNext:
591 return self.shell.hooks.result_display(arg)
591 return self.shell.hooks.result_display(arg)
592
592
593 # Assign the default display method:
593 # Assign the default display method:
594 display = _display
594 display = _display
595
595
596 def update(self,arg):
596 def update(self,arg):
597 #print '***cache_count', self.cache_count # dbg
597 #print '***cache_count', self.cache_count # dbg
598 if len(self.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
598 if len(self.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
599 warn('Output cache limit (currently '+
599 warn('Output cache limit (currently '+
600 `self.cache_size`+' entries) hit.\n'
600 `self.cache_size`+' entries) hit.\n'
601 'Flushing cache and resetting history counter...\n'
601 'Flushing cache and resetting history counter...\n'
602 'The only history variables available will be _,__,___ and _1\n'
602 'The only history variables available will be _,__,___ and _1\n'
603 'with the current result.')
603 'with the current result.')
604
604
605 self.flush()
605 self.flush()
606 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
606 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
607 # we cause buggy behavior for things like gettext).
607 # we cause buggy behavior for things like gettext).
608 if '_' not in __builtin__.__dict__:
608 if '_' not in __builtin__.__dict__:
609 self.___ = self.__
609 self.___ = self.__
610 self.__ = self._
610 self.__ = self._
611 self._ = arg
611 self._ = arg
612 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
612 self.user_ns.update({'_':self._,'__':self.__,'___':self.___})
613
613
614 # hackish access to top-level namespace to create _1,_2... dynamically
614 # hackish access to top-level namespace to create _1,_2... dynamically
615 to_main = {}
615 to_main = {}
616 if self.do_full_cache:
616 if self.do_full_cache:
617 new_result = '_'+`self.prompt_count`
617 new_result = '_'+`self.prompt_count`
618 to_main[new_result] = arg
618 to_main[new_result] = arg
619 self.user_ns.update(to_main)
619 self.user_ns.update(to_main)
620 self.user_ns['_oh'][self.prompt_count] = arg
620 self.user_ns['_oh'][self.prompt_count] = arg
621
621
622 def flush(self):
622 def flush(self):
623 if not self.do_full_cache:
623 if not self.do_full_cache:
624 raise ValueError,"You shouldn't have reached the cache flush "\
624 raise ValueError,"You shouldn't have reached the cache flush "\
625 "if full caching is not enabled!"
625 "if full caching is not enabled!"
626 # delete auto-generated vars from global namespace
626 # delete auto-generated vars from global namespace
627
627
628 for n in range(1,self.prompt_count + 1):
628 for n in range(1,self.prompt_count + 1):
629 key = '_'+`n`
629 key = '_'+`n`
630 try:
630 try:
631 del self.user_ns[key]
631 del self.user_ns[key]
632 except: pass
632 except: pass
633 self.user_ns['_oh'].clear()
633 self.user_ns['_oh'].clear()
634
634
635 if '_' not in __builtin__.__dict__:
635 if '_' not in __builtin__.__dict__:
636 self.user_ns.update({'_':None,'__':None, '___':None})
636 self.user_ns.update({'_':None,'__':None, '___':None})
637 import gc
637 import gc
638 gc.collect() # xxx needed?
638 gc.collect() # xxx needed?
639
639
@@ -1,1104 +1,1107 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 ultratb.py -- Spice up your tracebacks!
3 ultratb.py -- Spice up your tracebacks!
4
4
5 * ColorTB
5 * ColorTB
6 I've always found it a bit hard to visually parse tracebacks in Python. The
6 I've always found it a bit hard to visually parse tracebacks in Python. The
7 ColorTB class is a solution to that problem. It colors the different parts of a
7 ColorTB class is a solution to that problem. It colors the different parts of a
8 traceback in a manner similar to what you would expect from a syntax-highlighting
8 traceback in a manner similar to what you would expect from a syntax-highlighting
9 text editor.
9 text editor.
10
10
11 Installation instructions for ColorTB:
11 Installation instructions for ColorTB:
12 import sys,ultratb
12 import sys,ultratb
13 sys.excepthook = ultratb.ColorTB()
13 sys.excepthook = ultratb.ColorTB()
14
14
15 * VerboseTB
15 * VerboseTB
16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
17 of useful info when a traceback occurs. Ping originally had it spit out HTML
17 of useful info when a traceback occurs. Ping originally had it spit out HTML
18 and intended it for CGI programmers, but why should they have all the fun? I
18 and intended it for CGI programmers, but why should they have all the fun? I
19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
20 but kind of neat, and maybe useful for long-running programs that you believe
20 but kind of neat, and maybe useful for long-running programs that you believe
21 are bug-free. If a crash *does* occur in that type of program you want details.
21 are bug-free. If a crash *does* occur in that type of program you want details.
22 Give it a shot--you'll love it or you'll hate it.
22 Give it a shot--you'll love it or you'll hate it.
23
23
24 Note:
24 Note:
25
25
26 The Verbose mode prints the variables currently visible where the exception
26 The Verbose mode prints the variables currently visible where the exception
27 happened (shortening their strings if too long). This can potentially be
27 happened (shortening their strings if too long). This can potentially be
28 very slow, if you happen to have a huge data structure whose string
28 very slow, if you happen to have a huge data structure whose string
29 representation is complex to compute. Your computer may appear to freeze for
29 representation is complex to compute. Your computer may appear to freeze for
30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
31 with Ctrl-C (maybe hitting it more than once).
31 with Ctrl-C (maybe hitting it more than once).
32
32
33 If you encounter this kind of situation often, you may want to use the
33 If you encounter this kind of situation often, you may want to use the
34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
35 variables (but otherwise includes the information and context given by
35 variables (but otherwise includes the information and context given by
36 Verbose).
36 Verbose).
37
37
38
38
39 Installation instructions for ColorTB:
39 Installation instructions for ColorTB:
40 import sys,ultratb
40 import sys,ultratb
41 sys.excepthook = ultratb.VerboseTB()
41 sys.excepthook = ultratb.VerboseTB()
42
42
43 Note: Much of the code in this module was lifted verbatim from the standard
43 Note: Much of the code in this module was lifted verbatim from the standard
44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
45
45
46 * Color schemes
46 * Color schemes
47 The colors are defined in the class TBTools through the use of the
47 The colors are defined in the class TBTools through the use of the
48 ColorSchemeTable class. Currently the following exist:
48 ColorSchemeTable class. Currently the following exist:
49
49
50 - NoColor: allows all of this module to be used in any terminal (the color
50 - NoColor: allows all of this module to be used in any terminal (the color
51 escapes are just dummy blank strings).
51 escapes are just dummy blank strings).
52
52
53 - Linux: is meant to look good in a terminal like the Linux console (black
53 - Linux: is meant to look good in a terminal like the Linux console (black
54 or very dark background).
54 or very dark background).
55
55
56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
57 in light background terminals.
57 in light background terminals.
58
58
59 You can implement other color schemes easily, the syntax is fairly
59 You can implement other color schemes easily, the syntax is fairly
60 self-explanatory. Please send back new schemes you develop to the author for
60 self-explanatory. Please send back new schemes you develop to the author for
61 possible inclusion in future releases.
61 possible inclusion in future releases.
62 """
62 """
63
63
64 #*****************************************************************************
64 #*****************************************************************************
65 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
65 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
66 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
66 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
67 #
67 #
68 # Distributed under the terms of the BSD License. The full license is in
68 # Distributed under the terms of the BSD License. The full license is in
69 # the file COPYING, distributed as part of this software.
69 # the file COPYING, distributed as part of this software.
70 #*****************************************************************************
70 #*****************************************************************************
71
71
72 from __future__ import with_statement
72 from __future__ import with_statement
73
73
74 import inspect
74 import inspect
75 import keyword
75 import keyword
76 import linecache
76 import linecache
77 import os
77 import os
78 import pydoc
78 import pydoc
79 import re
79 import re
80 import string
80 import string
81 import sys
81 import sys
82 import time
82 import time
83 import tokenize
83 import tokenize
84 import traceback
84 import traceback
85 import types
85 import types
86
86
87 # For purposes of monkeypatching inspect to fix a bug in it.
87 # For purposes of monkeypatching inspect to fix a bug in it.
88 from inspect import getsourcefile, getfile, getmodule,\
88 from inspect import getsourcefile, getfile, getmodule,\
89 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
89 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
90
90
91 # IPython's own modules
91 # IPython's own modules
92 # Modified pdb which doesn't damage IPython's readline handling
92 # Modified pdb which doesn't damage IPython's readline handling
93 from IPython.utils import PyColorize
93 from IPython.utils import PyColorize
94 from IPython.core import debugger, ipapi
94 from IPython.core import debugger, ipapi
95 from IPython.core.display_trap import DisplayTrap
95 from IPython.core.display_trap import DisplayTrap
96 from IPython.core.excolors import exception_colors
96 from IPython.core.excolors import exception_colors
97 from IPython.utils.data import uniq_stable
97 from IPython.utils.data import uniq_stable
98 from IPython.utils.io import Term
98 import IPython.utils.io
99 from IPython.utils.warn import info, error
99 from IPython.utils.warn import info, error
100
100
101 # Globals
101 # Globals
102 # amount of space to put line numbers before verbose tracebacks
102 # amount of space to put line numbers before verbose tracebacks
103 INDENT_SIZE = 8
103 INDENT_SIZE = 8
104
104
105 # Default color scheme. This is used, for example, by the traceback
105 # Default color scheme. This is used, for example, by the traceback
106 # formatter. When running in an actual IPython instance, the user's rc.colors
106 # formatter. When running in an actual IPython instance, the user's rc.colors
107 # value is used, but havinga module global makes this functionality available
107 # value is used, but havinga module global makes this functionality available
108 # to users of ultratb who are NOT running inside ipython.
108 # to users of ultratb who are NOT running inside ipython.
109 DEFAULT_SCHEME = 'NoColor'
109 DEFAULT_SCHEME = 'NoColor'
110
110
111 #---------------------------------------------------------------------------
111 #---------------------------------------------------------------------------
112 # Code begins
112 # Code begins
113
113
114 # Utility functions
114 # Utility functions
115 def inspect_error():
115 def inspect_error():
116 """Print a message about internal inspect errors.
116 """Print a message about internal inspect errors.
117
117
118 These are unfortunately quite common."""
118 These are unfortunately quite common."""
119
119
120 error('Internal Python error in the inspect module.\n'
120 error('Internal Python error in the inspect module.\n'
121 'Below is the traceback from this internal error.\n')
121 'Below is the traceback from this internal error.\n')
122
122
123
123
124 def findsource(object):
124 def findsource(object):
125 """Return the entire source file and starting line number for an object.
125 """Return the entire source file and starting line number for an object.
126
126
127 The argument may be a module, class, method, function, traceback, frame,
127 The argument may be a module, class, method, function, traceback, frame,
128 or code object. The source code is returned as a list of all the lines
128 or code object. The source code is returned as a list of all the lines
129 in the file and the line number indexes a line in that list. An IOError
129 in the file and the line number indexes a line in that list. An IOError
130 is raised if the source code cannot be retrieved.
130 is raised if the source code cannot be retrieved.
131
131
132 FIXED version with which we monkeypatch the stdlib to work around a bug."""
132 FIXED version with which we monkeypatch the stdlib to work around a bug."""
133
133
134 file = getsourcefile(object) or getfile(object)
134 file = getsourcefile(object) or getfile(object)
135 # If the object is a frame, then trying to get the globals dict from its
135 # If the object is a frame, then trying to get the globals dict from its
136 # module won't work. Instead, the frame object itself has the globals
136 # module won't work. Instead, the frame object itself has the globals
137 # dictionary.
137 # dictionary.
138 globals_dict = None
138 globals_dict = None
139 if inspect.isframe(object):
139 if inspect.isframe(object):
140 # XXX: can this ever be false?
140 # XXX: can this ever be false?
141 globals_dict = object.f_globals
141 globals_dict = object.f_globals
142 else:
142 else:
143 module = getmodule(object, file)
143 module = getmodule(object, file)
144 if module:
144 if module:
145 globals_dict = module.__dict__
145 globals_dict = module.__dict__
146 lines = linecache.getlines(file, globals_dict)
146 lines = linecache.getlines(file, globals_dict)
147 if not lines:
147 if not lines:
148 raise IOError('could not get source code')
148 raise IOError('could not get source code')
149
149
150 if ismodule(object):
150 if ismodule(object):
151 return lines, 0
151 return lines, 0
152
152
153 if isclass(object):
153 if isclass(object):
154 name = object.__name__
154 name = object.__name__
155 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
155 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
156 # make some effort to find the best matching class definition:
156 # make some effort to find the best matching class definition:
157 # use the one with the least indentation, which is the one
157 # use the one with the least indentation, which is the one
158 # that's most probably not inside a function definition.
158 # that's most probably not inside a function definition.
159 candidates = []
159 candidates = []
160 for i in range(len(lines)):
160 for i in range(len(lines)):
161 match = pat.match(lines[i])
161 match = pat.match(lines[i])
162 if match:
162 if match:
163 # if it's at toplevel, it's already the best one
163 # if it's at toplevel, it's already the best one
164 if lines[i][0] == 'c':
164 if lines[i][0] == 'c':
165 return lines, i
165 return lines, i
166 # else add whitespace to candidate list
166 # else add whitespace to candidate list
167 candidates.append((match.group(1), i))
167 candidates.append((match.group(1), i))
168 if candidates:
168 if candidates:
169 # this will sort by whitespace, and by line number,
169 # this will sort by whitespace, and by line number,
170 # less whitespace first
170 # less whitespace first
171 candidates.sort()
171 candidates.sort()
172 return lines, candidates[0][1]
172 return lines, candidates[0][1]
173 else:
173 else:
174 raise IOError('could not find class definition')
174 raise IOError('could not find class definition')
175
175
176 if ismethod(object):
176 if ismethod(object):
177 object = object.im_func
177 object = object.im_func
178 if isfunction(object):
178 if isfunction(object):
179 object = object.func_code
179 object = object.func_code
180 if istraceback(object):
180 if istraceback(object):
181 object = object.tb_frame
181 object = object.tb_frame
182 if isframe(object):
182 if isframe(object):
183 object = object.f_code
183 object = object.f_code
184 if iscode(object):
184 if iscode(object):
185 if not hasattr(object, 'co_firstlineno'):
185 if not hasattr(object, 'co_firstlineno'):
186 raise IOError('could not find function definition')
186 raise IOError('could not find function definition')
187 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
187 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
188 pmatch = pat.match
188 pmatch = pat.match
189 # fperez - fix: sometimes, co_firstlineno can give a number larger than
189 # fperez - fix: sometimes, co_firstlineno can give a number larger than
190 # the length of lines, which causes an error. Safeguard against that.
190 # the length of lines, which causes an error. Safeguard against that.
191 lnum = min(object.co_firstlineno,len(lines))-1
191 lnum = min(object.co_firstlineno,len(lines))-1
192 while lnum > 0:
192 while lnum > 0:
193 if pmatch(lines[lnum]): break
193 if pmatch(lines[lnum]): break
194 lnum -= 1
194 lnum -= 1
195
195
196 return lines, lnum
196 return lines, lnum
197 raise IOError('could not find code object')
197 raise IOError('could not find code object')
198
198
199 # Monkeypatch inspect to apply our bugfix. This code only works with py25
199 # Monkeypatch inspect to apply our bugfix. This code only works with py25
200 if sys.version_info[:2] >= (2,5):
200 if sys.version_info[:2] >= (2,5):
201 inspect.findsource = findsource
201 inspect.findsource = findsource
202
202
203 def fix_frame_records_filenames(records):
203 def fix_frame_records_filenames(records):
204 """Try to fix the filenames in each record from inspect.getinnerframes().
204 """Try to fix the filenames in each record from inspect.getinnerframes().
205
205
206 Particularly, modules loaded from within zip files have useless filenames
206 Particularly, modules loaded from within zip files have useless filenames
207 attached to their code object, and inspect.getinnerframes() just uses it.
207 attached to their code object, and inspect.getinnerframes() just uses it.
208 """
208 """
209 fixed_records = []
209 fixed_records = []
210 for frame, filename, line_no, func_name, lines, index in records:
210 for frame, filename, line_no, func_name, lines, index in records:
211 # Look inside the frame's globals dictionary for __file__, which should
211 # Look inside the frame's globals dictionary for __file__, which should
212 # be better.
212 # be better.
213 better_fn = frame.f_globals.get('__file__', None)
213 better_fn = frame.f_globals.get('__file__', None)
214 if isinstance(better_fn, str):
214 if isinstance(better_fn, str):
215 # Check the type just in case someone did something weird with
215 # Check the type just in case someone did something weird with
216 # __file__. It might also be None if the error occurred during
216 # __file__. It might also be None if the error occurred during
217 # import.
217 # import.
218 filename = better_fn
218 filename = better_fn
219 fixed_records.append((frame, filename, line_no, func_name, lines, index))
219 fixed_records.append((frame, filename, line_no, func_name, lines, index))
220 return fixed_records
220 return fixed_records
221
221
222
222
223 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
223 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
224 import linecache
224 import linecache
225 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
225 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
226
226
227 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
227 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
228
228
229 # If the error is at the console, don't build any context, since it would
229 # If the error is at the console, don't build any context, since it would
230 # otherwise produce 5 blank lines printed out (there is no file at the
230 # otherwise produce 5 blank lines printed out (there is no file at the
231 # console)
231 # console)
232 rec_check = records[tb_offset:]
232 rec_check = records[tb_offset:]
233 try:
233 try:
234 rname = rec_check[0][1]
234 rname = rec_check[0][1]
235 if rname == '<ipython console>' or rname.endswith('<string>'):
235 if rname == '<ipython console>' or rname.endswith('<string>'):
236 return rec_check
236 return rec_check
237 except IndexError:
237 except IndexError:
238 pass
238 pass
239
239
240 aux = traceback.extract_tb(etb)
240 aux = traceback.extract_tb(etb)
241 assert len(records) == len(aux)
241 assert len(records) == len(aux)
242 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
242 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
243 maybeStart = lnum-1 - context//2
243 maybeStart = lnum-1 - context//2
244 start = max(maybeStart, 0)
244 start = max(maybeStart, 0)
245 end = start + context
245 end = start + context
246 lines = linecache.getlines(file)[start:end]
246 lines = linecache.getlines(file)[start:end]
247 # pad with empty lines if necessary
247 # pad with empty lines if necessary
248 if maybeStart < 0:
248 if maybeStart < 0:
249 lines = (['\n'] * -maybeStart) + lines
249 lines = (['\n'] * -maybeStart) + lines
250 if len(lines) < context:
250 if len(lines) < context:
251 lines += ['\n'] * (context - len(lines))
251 lines += ['\n'] * (context - len(lines))
252 buf = list(records[i])
252 buf = list(records[i])
253 buf[LNUM_POS] = lnum
253 buf[LNUM_POS] = lnum
254 buf[INDEX_POS] = lnum - 1 - start
254 buf[INDEX_POS] = lnum - 1 - start
255 buf[LINES_POS] = lines
255 buf[LINES_POS] = lines
256 records[i] = tuple(buf)
256 records[i] = tuple(buf)
257 return records[tb_offset:]
257 return records[tb_offset:]
258
258
259 # Helper function -- largely belongs to VerboseTB, but we need the same
259 # Helper function -- largely belongs to VerboseTB, but we need the same
260 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
260 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
261 # can be recognized properly by ipython.el's py-traceback-line-re
261 # can be recognized properly by ipython.el's py-traceback-line-re
262 # (SyntaxErrors have to be treated specially because they have no traceback)
262 # (SyntaxErrors have to be treated specially because they have no traceback)
263
263
264 _parser = PyColorize.Parser()
264 _parser = PyColorize.Parser()
265
265
266 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
266 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
267 numbers_width = INDENT_SIZE - 1
267 numbers_width = INDENT_SIZE - 1
268 res = []
268 res = []
269 i = lnum - index
269 i = lnum - index
270
270
271 # This lets us get fully syntax-highlighted tracebacks.
271 # This lets us get fully syntax-highlighted tracebacks.
272 if scheme is None:
272 if scheme is None:
273 ipinst = ipapi.get()
273 ipinst = ipapi.get()
274 if ipinst is not None:
274 if ipinst is not None:
275 scheme = ipinst.colors
275 scheme = ipinst.colors
276 else:
276 else:
277 scheme = DEFAULT_SCHEME
277 scheme = DEFAULT_SCHEME
278
278
279 _line_format = _parser.format2
279 _line_format = _parser.format2
280
280
281 for line in lines:
281 for line in lines:
282 new_line, err = _line_format(line,'str',scheme)
282 new_line, err = _line_format(line,'str',scheme)
283 if not err: line = new_line
283 if not err: line = new_line
284
284
285 if i == lnum:
285 if i == lnum:
286 # This is the line with the error
286 # This is the line with the error
287 pad = numbers_width - len(str(i))
287 pad = numbers_width - len(str(i))
288 if pad >= 3:
288 if pad >= 3:
289 marker = '-'*(pad-3) + '-> '
289 marker = '-'*(pad-3) + '-> '
290 elif pad == 2:
290 elif pad == 2:
291 marker = '> '
291 marker = '> '
292 elif pad == 1:
292 elif pad == 1:
293 marker = '>'
293 marker = '>'
294 else:
294 else:
295 marker = ''
295 marker = ''
296 num = marker + str(i)
296 num = marker + str(i)
297 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
297 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
298 Colors.line, line, Colors.Normal)
298 Colors.line, line, Colors.Normal)
299 else:
299 else:
300 num = '%*s' % (numbers_width,i)
300 num = '%*s' % (numbers_width,i)
301 line = '%s%s%s %s' %(Colors.lineno, num,
301 line = '%s%s%s %s' %(Colors.lineno, num,
302 Colors.Normal, line)
302 Colors.Normal, line)
303
303
304 res.append(line)
304 res.append(line)
305 if lvals and i == lnum:
305 if lvals and i == lnum:
306 res.append(lvals + '\n')
306 res.append(lvals + '\n')
307 i = i + 1
307 i = i + 1
308 return res
308 return res
309
309
310
310
311 #---------------------------------------------------------------------------
311 #---------------------------------------------------------------------------
312 # Module classes
312 # Module classes
313 class TBTools:
313 class TBTools:
314 """Basic tools used by all traceback printer classes."""
314 """Basic tools used by all traceback printer classes."""
315
315
316 #: Default output stream, can be overridden at call time. A special value
316 # This attribute us used in globalipapp.py to have stdout used for
317 #: of 'stdout' *as a string* can be given to force extraction of sys.stdout
317 # writting exceptions. This is needed so nose can trap them. This attribute
318 #: at runtime. This allows testing exception printing with doctests, that
318 # should be None (the default, which will use IPython.utils.io.Term) or
319 #: swap sys.stdout just at execution time.
319 # the string 'stdout' which will cause the override to sys.stdout.
320 #: Warning: be VERY careful to set this to one of the Term streams, NEVER
320 out_stream = None
321 #: directly to sys.stdout/err, because under win32 the Term streams come from
322 #: pyreadline and know how to handle color correctly, whie stdout/err don't.
323 out_stream = Term.cerr
324
321
325 def __init__(self,color_scheme = 'NoColor',call_pdb=False):
322 def __init__(self,color_scheme = 'NoColor',call_pdb=False):
326 # Whether to call the interactive pdb debugger after printing
323 # Whether to call the interactive pdb debugger after printing
327 # tracebacks or not
324 # tracebacks or not
328 self.call_pdb = call_pdb
325 self.call_pdb = call_pdb
329
326
330 # Create color table
327 # Create color table
331 self.color_scheme_table = exception_colors()
328 self.color_scheme_table = exception_colors()
332
329
333 self.set_colors(color_scheme)
330 self.set_colors(color_scheme)
334 self.old_scheme = color_scheme # save initial value for toggles
331 self.old_scheme = color_scheme # save initial value for toggles
335
332
336 if call_pdb:
333 if call_pdb:
337 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
334 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
338 else:
335 else:
339 self.pdb = None
336 self.pdb = None
340
337
341 def set_colors(self,*args,**kw):
338 def set_colors(self,*args,**kw):
342 """Shorthand access to the color table scheme selector method."""
339 """Shorthand access to the color table scheme selector method."""
343
340
344 # Set own color table
341 # Set own color table
345 self.color_scheme_table.set_active_scheme(*args,**kw)
342 self.color_scheme_table.set_active_scheme(*args,**kw)
346 # for convenience, set Colors to the active scheme
343 # for convenience, set Colors to the active scheme
347 self.Colors = self.color_scheme_table.active_colors
344 self.Colors = self.color_scheme_table.active_colors
348 # Also set colors of debugger
345 # Also set colors of debugger
349 if hasattr(self,'pdb') and self.pdb is not None:
346 if hasattr(self,'pdb') and self.pdb is not None:
350 self.pdb.set_colors(*args,**kw)
347 self.pdb.set_colors(*args,**kw)
351
348
352 def color_toggle(self):
349 def color_toggle(self):
353 """Toggle between the currently active color scheme and NoColor."""
350 """Toggle between the currently active color scheme and NoColor."""
354
351
355 if self.color_scheme_table.active_scheme_name == 'NoColor':
352 if self.color_scheme_table.active_scheme_name == 'NoColor':
356 self.color_scheme_table.set_active_scheme(self.old_scheme)
353 self.color_scheme_table.set_active_scheme(self.old_scheme)
357 self.Colors = self.color_scheme_table.active_colors
354 self.Colors = self.color_scheme_table.active_colors
358 else:
355 else:
359 self.old_scheme = self.color_scheme_table.active_scheme_name
356 self.old_scheme = self.color_scheme_table.active_scheme_name
360 self.color_scheme_table.set_active_scheme('NoColor')
357 self.color_scheme_table.set_active_scheme('NoColor')
361 self.Colors = self.color_scheme_table.active_colors
358 self.Colors = self.color_scheme_table.active_colors
362
359
363 #---------------------------------------------------------------------------
360 #---------------------------------------------------------------------------
364 class ListTB(TBTools):
361 class ListTB(TBTools):
365 """Print traceback information from a traceback list, with optional color.
362 """Print traceback information from a traceback list, with optional color.
366
363
367 Calling: requires 3 arguments:
364 Calling: requires 3 arguments:
368 (etype, evalue, elist)
365 (etype, evalue, elist)
369 as would be obtained by:
366 as would be obtained by:
370 etype, evalue, tb = sys.exc_info()
367 etype, evalue, tb = sys.exc_info()
371 if tb:
368 if tb:
372 elist = traceback.extract_tb(tb)
369 elist = traceback.extract_tb(tb)
373 else:
370 else:
374 elist = None
371 elist = None
375
372
376 It can thus be used by programs which need to process the traceback before
373 It can thus be used by programs which need to process the traceback before
377 printing (such as console replacements based on the code module from the
374 printing (such as console replacements based on the code module from the
378 standard library).
375 standard library).
379
376
380 Because they are meant to be called without a full traceback (only a
377 Because they are meant to be called without a full traceback (only a
381 list), instances of this class can't call the interactive pdb debugger."""
378 list), instances of this class can't call the interactive pdb debugger."""
382
379
383 def __init__(self,color_scheme = 'NoColor'):
380 def __init__(self,color_scheme = 'NoColor'):
384 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
381 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
385
382
386 def __call__(self, etype, value, elist):
383 def __call__(self, etype, value, elist):
387 Term.cout.flush()
384 IPython.utils.io.Term.cout.flush()
388 Term.cerr.write(self.text(etype,value,elist))
385 IPython.utils.io.Term.cerr.write(self.text(etype,value,elist))
389 Term.cerr.write('\n')
386 IPython.utils.io.Term.cerr.write('\n')
390
387
391 def text(self, etype, value, elist, context=5):
388 def text(self, etype, value, elist, context=5):
392 """Return a color formatted string with the traceback info.
389 """Return a color formatted string with the traceback info.
393
390
394 Parameters
391 Parameters
395 ----------
392 ----------
396 etype : exception type
393 etype : exception type
397 Type of the exception raised.
394 Type of the exception raised.
398
395
399 value : object
396 value : object
400 Data stored in the exception
397 Data stored in the exception
401
398
402 elist : list
399 elist : list
403 List of frames, see class docstring for details.
400 List of frames, see class docstring for details.
404
401
405 Returns
402 Returns
406 -------
403 -------
407 String with formatted exception.
404 String with formatted exception.
408 """
405 """
409
406
410 Colors = self.Colors
407 Colors = self.Colors
411 out_string = []
408 out_string = []
412 if elist:
409 if elist:
413 out_string.append('Traceback %s(most recent call last)%s:' %
410 out_string.append('Traceback %s(most recent call last)%s:' %
414 (Colors.normalEm, Colors.Normal) + '\n')
411 (Colors.normalEm, Colors.Normal) + '\n')
415 out_string.extend(self._format_list(elist))
412 out_string.extend(self._format_list(elist))
416 lines = self._format_exception_only(etype, value)
413 lines = self._format_exception_only(etype, value)
417 for line in lines[:-1]:
414 for line in lines[:-1]:
418 out_string.append(" "+line)
415 out_string.append(" "+line)
419 out_string.append(lines[-1])
416 out_string.append(lines[-1])
420 return ''.join(out_string)
417 return ''.join(out_string)
421
418
422 def _format_list(self, extracted_list):
419 def _format_list(self, extracted_list):
423 """Format a list of traceback entry tuples for printing.
420 """Format a list of traceback entry tuples for printing.
424
421
425 Given a list of tuples as returned by extract_tb() or
422 Given a list of tuples as returned by extract_tb() or
426 extract_stack(), return a list of strings ready for printing.
423 extract_stack(), return a list of strings ready for printing.
427 Each string in the resulting list corresponds to the item with the
424 Each string in the resulting list corresponds to the item with the
428 same index in the argument list. Each string ends in a newline;
425 same index in the argument list. Each string ends in a newline;
429 the strings may contain internal newlines as well, for those items
426 the strings may contain internal newlines as well, for those items
430 whose source text line is not None.
427 whose source text line is not None.
431
428
432 Lifted almost verbatim from traceback.py
429 Lifted almost verbatim from traceback.py
433 """
430 """
434
431
435 Colors = self.Colors
432 Colors = self.Colors
436 list = []
433 list = []
437 for filename, lineno, name, line in extracted_list[:-1]:
434 for filename, lineno, name, line in extracted_list[:-1]:
438 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
435 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
439 (Colors.filename, filename, Colors.Normal,
436 (Colors.filename, filename, Colors.Normal,
440 Colors.lineno, lineno, Colors.Normal,
437 Colors.lineno, lineno, Colors.Normal,
441 Colors.name, name, Colors.Normal)
438 Colors.name, name, Colors.Normal)
442 if line:
439 if line:
443 item = item + ' %s\n' % line.strip()
440 item = item + ' %s\n' % line.strip()
444 list.append(item)
441 list.append(item)
445 # Emphasize the last entry
442 # Emphasize the last entry
446 filename, lineno, name, line = extracted_list[-1]
443 filename, lineno, name, line = extracted_list[-1]
447 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
444 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
448 (Colors.normalEm,
445 (Colors.normalEm,
449 Colors.filenameEm, filename, Colors.normalEm,
446 Colors.filenameEm, filename, Colors.normalEm,
450 Colors.linenoEm, lineno, Colors.normalEm,
447 Colors.linenoEm, lineno, Colors.normalEm,
451 Colors.nameEm, name, Colors.normalEm,
448 Colors.nameEm, name, Colors.normalEm,
452 Colors.Normal)
449 Colors.Normal)
453 if line:
450 if line:
454 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
451 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
455 Colors.Normal)
452 Colors.Normal)
456 list.append(item)
453 list.append(item)
457 return list
454 return list
458
455
459 def _format_exception_only(self, etype, value):
456 def _format_exception_only(self, etype, value):
460 """Format the exception part of a traceback.
457 """Format the exception part of a traceback.
461
458
462 The arguments are the exception type and value such as given by
459 The arguments are the exception type and value such as given by
463 sys.exc_info()[:2]. The return value is a list of strings, each ending
460 sys.exc_info()[:2]. The return value is a list of strings, each ending
464 in a newline. Normally, the list contains a single string; however,
461 in a newline. Normally, the list contains a single string; however,
465 for SyntaxError exceptions, it contains several lines that (when
462 for SyntaxError exceptions, it contains several lines that (when
466 printed) display detailed information about where the syntax error
463 printed) display detailed information about where the syntax error
467 occurred. The message indicating which exception occurred is the
464 occurred. The message indicating which exception occurred is the
468 always last string in the list.
465 always last string in the list.
469
466
470 Also lifted nearly verbatim from traceback.py
467 Also lifted nearly verbatim from traceback.py
471 """
468 """
472
469
473 have_filedata = False
470 have_filedata = False
474 Colors = self.Colors
471 Colors = self.Colors
475 list = []
472 list = []
476 try:
473 try:
477 stype = Colors.excName + etype.__name__ + Colors.Normal
474 stype = Colors.excName + etype.__name__ + Colors.Normal
478 except AttributeError:
475 except AttributeError:
479 stype = etype # String exceptions don't get special coloring
476 stype = etype # String exceptions don't get special coloring
480 if value is None:
477 if value is None:
481 list.append( str(stype) + '\n')
478 list.append( str(stype) + '\n')
482 else:
479 else:
483 if etype is SyntaxError:
480 if etype is SyntaxError:
484 try:
481 try:
485 msg, (filename, lineno, offset, line) = value
482 msg, (filename, lineno, offset, line) = value
486 except:
483 except:
487 have_filedata = False
484 have_filedata = False
488 else:
485 else:
489 have_filedata = True
486 have_filedata = True
490 #print 'filename is',filename # dbg
487 #print 'filename is',filename # dbg
491 if not filename: filename = "<string>"
488 if not filename: filename = "<string>"
492 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
489 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
493 (Colors.normalEm,
490 (Colors.normalEm,
494 Colors.filenameEm, filename, Colors.normalEm,
491 Colors.filenameEm, filename, Colors.normalEm,
495 Colors.linenoEm, lineno, Colors.Normal ))
492 Colors.linenoEm, lineno, Colors.Normal ))
496 if line is not None:
493 if line is not None:
497 i = 0
494 i = 0
498 while i < len(line) and line[i].isspace():
495 while i < len(line) and line[i].isspace():
499 i = i+1
496 i = i+1
500 list.append('%s %s%s\n' % (Colors.line,
497 list.append('%s %s%s\n' % (Colors.line,
501 line.strip(),
498 line.strip(),
502 Colors.Normal))
499 Colors.Normal))
503 if offset is not None:
500 if offset is not None:
504 s = ' '
501 s = ' '
505 for c in line[i:offset-1]:
502 for c in line[i:offset-1]:
506 if c.isspace():
503 if c.isspace():
507 s = s + c
504 s = s + c
508 else:
505 else:
509 s = s + ' '
506 s = s + ' '
510 list.append('%s%s^%s\n' % (Colors.caret, s,
507 list.append('%s%s^%s\n' % (Colors.caret, s,
511 Colors.Normal) )
508 Colors.Normal) )
512 value = msg
509 value = msg
513 s = self._some_str(value)
510 s = self._some_str(value)
514 if s:
511 if s:
515 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
512 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
516 Colors.Normal, s))
513 Colors.Normal, s))
517 else:
514 else:
518 list.append('%s\n' % str(stype))
515 list.append('%s\n' % str(stype))
519
516
520 # sync with user hooks
517 # sync with user hooks
521 if have_filedata:
518 if have_filedata:
522 ipinst = ipapi.get()
519 ipinst = ipapi.get()
523 if ipinst is not None:
520 if ipinst is not None:
524 ipinst.hooks.synchronize_with_editor(filename, lineno, 0)
521 ipinst.hooks.synchronize_with_editor(filename, lineno, 0)
525
522
526 return list
523 return list
527
524
528 def show_exception_only(self, etype, value):
525 def show_exception_only(self, etype, value):
529 """Only print the exception type and message, without a traceback.
526 """Only print the exception type and message, without a traceback.
530
527
531 Parameters
528 Parameters
532 ----------
529 ----------
533 etype : exception type
530 etype : exception type
534 value : exception value
531 value : exception value
535 """
532 """
536 # This method needs to use __call__ from *this* class, not the one from
533 # This method needs to use __call__ from *this* class, not the one from
537 # a subclass whose signature or behavior may be different
534 # a subclass whose signature or behavior may be different
538 Term.cout.flush()
535 if self.out_stream == 'stdout':
539 ostream = sys.stdout if self.out_stream == 'stdout' else Term.cerr
536 ostream = sys.stdout
537 else:
538 ostream = IPython.utils.io.Term.cerr
539 ostream.flush()
540 ostream.write(ListTB.text(self, etype, value, []))
540 ostream.write(ListTB.text(self, etype, value, []))
541 ostream.flush()
541 ostream.flush()
542
542
543 def _some_str(self, value):
543 def _some_str(self, value):
544 # Lifted from traceback.py
544 # Lifted from traceback.py
545 try:
545 try:
546 return str(value)
546 return str(value)
547 except:
547 except:
548 return '<unprintable %s object>' % type(value).__name__
548 return '<unprintable %s object>' % type(value).__name__
549
549
550 #----------------------------------------------------------------------------
550 #----------------------------------------------------------------------------
551 class VerboseTB(TBTools):
551 class VerboseTB(TBTools):
552 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
552 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
553 of HTML. Requires inspect and pydoc. Crazy, man.
553 of HTML. Requires inspect and pydoc. Crazy, man.
554
554
555 Modified version which optionally strips the topmost entries from the
555 Modified version which optionally strips the topmost entries from the
556 traceback, to be used with alternate interpreters (because their own code
556 traceback, to be used with alternate interpreters (because their own code
557 would appear in the traceback)."""
557 would appear in the traceback)."""
558
558
559 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
559 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
560 call_pdb = 0, include_vars=1):
560 call_pdb = 0, include_vars=1):
561 """Specify traceback offset, headers and color scheme.
561 """Specify traceback offset, headers and color scheme.
562
562
563 Define how many frames to drop from the tracebacks. Calling it with
563 Define how many frames to drop from the tracebacks. Calling it with
564 tb_offset=1 allows use of this handler in interpreters which will have
564 tb_offset=1 allows use of this handler in interpreters which will have
565 their own code at the top of the traceback (VerboseTB will first
565 their own code at the top of the traceback (VerboseTB will first
566 remove that frame before printing the traceback info)."""
566 remove that frame before printing the traceback info)."""
567 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
567 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
568 self.tb_offset = tb_offset
568 self.tb_offset = tb_offset
569 self.long_header = long_header
569 self.long_header = long_header
570 self.include_vars = include_vars
570 self.include_vars = include_vars
571
571
572 def text(self, etype, evalue, etb, context=5):
572 def text(self, etype, evalue, etb, context=5):
573 """Return a nice text document describing the traceback."""
573 """Return a nice text document describing the traceback."""
574
574
575 # some locals
575 # some locals
576 try:
576 try:
577 etype = etype.__name__
577 etype = etype.__name__
578 except AttributeError:
578 except AttributeError:
579 pass
579 pass
580 Colors = self.Colors # just a shorthand + quicker name lookup
580 Colors = self.Colors # just a shorthand + quicker name lookup
581 ColorsNormal = Colors.Normal # used a lot
581 ColorsNormal = Colors.Normal # used a lot
582 col_scheme = self.color_scheme_table.active_scheme_name
582 col_scheme = self.color_scheme_table.active_scheme_name
583 indent = ' '*INDENT_SIZE
583 indent = ' '*INDENT_SIZE
584 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
584 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
585 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
585 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
586 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
586 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
587
587
588 # some internal-use functions
588 # some internal-use functions
589 def text_repr(value):
589 def text_repr(value):
590 """Hopefully pretty robust repr equivalent."""
590 """Hopefully pretty robust repr equivalent."""
591 # this is pretty horrible but should always return *something*
591 # this is pretty horrible but should always return *something*
592 try:
592 try:
593 return pydoc.text.repr(value)
593 return pydoc.text.repr(value)
594 except KeyboardInterrupt:
594 except KeyboardInterrupt:
595 raise
595 raise
596 except:
596 except:
597 try:
597 try:
598 return repr(value)
598 return repr(value)
599 except KeyboardInterrupt:
599 except KeyboardInterrupt:
600 raise
600 raise
601 except:
601 except:
602 try:
602 try:
603 # all still in an except block so we catch
603 # all still in an except block so we catch
604 # getattr raising
604 # getattr raising
605 name = getattr(value, '__name__', None)
605 name = getattr(value, '__name__', None)
606 if name:
606 if name:
607 # ick, recursion
607 # ick, recursion
608 return text_repr(name)
608 return text_repr(name)
609 klass = getattr(value, '__class__', None)
609 klass = getattr(value, '__class__', None)
610 if klass:
610 if klass:
611 return '%s instance' % text_repr(klass)
611 return '%s instance' % text_repr(klass)
612 except KeyboardInterrupt:
612 except KeyboardInterrupt:
613 raise
613 raise
614 except:
614 except:
615 return 'UNRECOVERABLE REPR FAILURE'
615 return 'UNRECOVERABLE REPR FAILURE'
616 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
616 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
617 def nullrepr(value, repr=text_repr): return ''
617 def nullrepr(value, repr=text_repr): return ''
618
618
619 # meat of the code begins
619 # meat of the code begins
620 try:
620 try:
621 etype = etype.__name__
621 etype = etype.__name__
622 except AttributeError:
622 except AttributeError:
623 pass
623 pass
624
624
625 if self.long_header:
625 if self.long_header:
626 # Header with the exception type, python version, and date
626 # Header with the exception type, python version, and date
627 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
627 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
628 date = time.ctime(time.time())
628 date = time.ctime(time.time())
629
629
630 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
630 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
631 exc, ' '*(75-len(str(etype))-len(pyver)),
631 exc, ' '*(75-len(str(etype))-len(pyver)),
632 pyver, string.rjust(date, 75) )
632 pyver, string.rjust(date, 75) )
633 head += "\nA problem occured executing Python code. Here is the sequence of function"\
633 head += "\nA problem occured executing Python code. Here is the sequence of function"\
634 "\ncalls leading up to the error, with the most recent (innermost) call last."
634 "\ncalls leading up to the error, with the most recent (innermost) call last."
635 else:
635 else:
636 # Simplified header
636 # Simplified header
637 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
637 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
638 string.rjust('Traceback (most recent call last)',
638 string.rjust('Traceback (most recent call last)',
639 75 - len(str(etype)) ) )
639 75 - len(str(etype)) ) )
640 frames = []
640 frames = []
641 # Flush cache before calling inspect. This helps alleviate some of the
641 # Flush cache before calling inspect. This helps alleviate some of the
642 # problems with python 2.3's inspect.py.
642 # problems with python 2.3's inspect.py.
643 linecache.checkcache()
643 linecache.checkcache()
644 # Drop topmost frames if requested
644 # Drop topmost frames if requested
645 try:
645 try:
646 # Try the default getinnerframes and Alex's: Alex's fixes some
646 # Try the default getinnerframes and Alex's: Alex's fixes some
647 # problems, but it generates empty tracebacks for console errors
647 # problems, but it generates empty tracebacks for console errors
648 # (5 blanks lines) where none should be returned.
648 # (5 blanks lines) where none should be returned.
649 #records = inspect.getinnerframes(etb, context)[self.tb_offset:]
649 #records = inspect.getinnerframes(etb, context)[self.tb_offset:]
650 #print 'python records:', records # dbg
650 #print 'python records:', records # dbg
651 records = _fixed_getinnerframes(etb, context,self.tb_offset)
651 records = _fixed_getinnerframes(etb, context,self.tb_offset)
652 #print 'alex records:', records # dbg
652 #print 'alex records:', records # dbg
653 except:
653 except:
654
654
655 # FIXME: I've been getting many crash reports from python 2.3
655 # FIXME: I've been getting many crash reports from python 2.3
656 # users, traceable to inspect.py. If I can find a small test-case
656 # users, traceable to inspect.py. If I can find a small test-case
657 # to reproduce this, I should either write a better workaround or
657 # to reproduce this, I should either write a better workaround or
658 # file a bug report against inspect (if that's the real problem).
658 # file a bug report against inspect (if that's the real problem).
659 # So far, I haven't been able to find an isolated example to
659 # So far, I haven't been able to find an isolated example to
660 # reproduce the problem.
660 # reproduce the problem.
661 inspect_error()
661 inspect_error()
662 traceback.print_exc(file=Term.cerr)
662 traceback.print_exc(file=IPython.utils.io.Term.cerr)
663 info('\nUnfortunately, your original traceback can not be constructed.\n')
663 info('\nUnfortunately, your original traceback can not be constructed.\n')
664 return ''
664 return ''
665
665
666 # build some color string templates outside these nested loops
666 # build some color string templates outside these nested loops
667 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
667 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
668 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
668 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
669 ColorsNormal)
669 ColorsNormal)
670 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
670 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
671 (Colors.vName, Colors.valEm, ColorsNormal)
671 (Colors.vName, Colors.valEm, ColorsNormal)
672 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
672 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
673 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
673 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
674 Colors.vName, ColorsNormal)
674 Colors.vName, ColorsNormal)
675 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
675 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
676 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
676 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
677 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
677 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
678 ColorsNormal)
678 ColorsNormal)
679
679
680 # now, loop over all records printing context and info
680 # now, loop over all records printing context and info
681 abspath = os.path.abspath
681 abspath = os.path.abspath
682 for frame, file, lnum, func, lines, index in records:
682 for frame, file, lnum, func, lines, index in records:
683 #print '*** record:',file,lnum,func,lines,index # dbg
683 #print '*** record:',file,lnum,func,lines,index # dbg
684 try:
684 try:
685 file = file and abspath(file) or '?'
685 file = file and abspath(file) or '?'
686 except OSError:
686 except OSError:
687 # if file is '<console>' or something not in the filesystem,
687 # if file is '<console>' or something not in the filesystem,
688 # the abspath call will throw an OSError. Just ignore it and
688 # the abspath call will throw an OSError. Just ignore it and
689 # keep the original file string.
689 # keep the original file string.
690 pass
690 pass
691 link = tpl_link % file
691 link = tpl_link % file
692 try:
692 try:
693 args, varargs, varkw, locals = inspect.getargvalues(frame)
693 args, varargs, varkw, locals = inspect.getargvalues(frame)
694 except:
694 except:
695 # This can happen due to a bug in python2.3. We should be
695 # This can happen due to a bug in python2.3. We should be
696 # able to remove this try/except when 2.4 becomes a
696 # able to remove this try/except when 2.4 becomes a
697 # requirement. Bug details at http://python.org/sf/1005466
697 # requirement. Bug details at http://python.org/sf/1005466
698 inspect_error()
698 inspect_error()
699 traceback.print_exc(file=Term.cerr)
699 traceback.print_exc(file=IPython.utils.io.Term.cerr)
700 info("\nIPython's exception reporting continues...\n")
700 info("\nIPython's exception reporting continues...\n")
701
701
702 if func == '?':
702 if func == '?':
703 call = ''
703 call = ''
704 else:
704 else:
705 # Decide whether to include variable details or not
705 # Decide whether to include variable details or not
706 var_repr = self.include_vars and eqrepr or nullrepr
706 var_repr = self.include_vars and eqrepr or nullrepr
707 try:
707 try:
708 call = tpl_call % (func,inspect.formatargvalues(args,
708 call = tpl_call % (func,inspect.formatargvalues(args,
709 varargs, varkw,
709 varargs, varkw,
710 locals,formatvalue=var_repr))
710 locals,formatvalue=var_repr))
711 except KeyError:
711 except KeyError:
712 # Very odd crash from inspect.formatargvalues(). The
712 # Very odd crash from inspect.formatargvalues(). The
713 # scenario under which it appeared was a call to
713 # scenario under which it appeared was a call to
714 # view(array,scale) in NumTut.view.view(), where scale had
714 # view(array,scale) in NumTut.view.view(), where scale had
715 # been defined as a scalar (it should be a tuple). Somehow
715 # been defined as a scalar (it should be a tuple). Somehow
716 # inspect messes up resolving the argument list of view()
716 # inspect messes up resolving the argument list of view()
717 # and barfs out. At some point I should dig into this one
717 # and barfs out. At some point I should dig into this one
718 # and file a bug report about it.
718 # and file a bug report about it.
719 inspect_error()
719 inspect_error()
720 traceback.print_exc(file=Term.cerr)
720 traceback.print_exc(file=IPython.utils.io.Term.cerr)
721 info("\nIPython's exception reporting continues...\n")
721 info("\nIPython's exception reporting continues...\n")
722 call = tpl_call_fail % func
722 call = tpl_call_fail % func
723
723
724 # Initialize a list of names on the current line, which the
724 # Initialize a list of names on the current line, which the
725 # tokenizer below will populate.
725 # tokenizer below will populate.
726 names = []
726 names = []
727
727
728 def tokeneater(token_type, token, start, end, line):
728 def tokeneater(token_type, token, start, end, line):
729 """Stateful tokeneater which builds dotted names.
729 """Stateful tokeneater which builds dotted names.
730
730
731 The list of names it appends to (from the enclosing scope) can
731 The list of names it appends to (from the enclosing scope) can
732 contain repeated composite names. This is unavoidable, since
732 contain repeated composite names. This is unavoidable, since
733 there is no way to disambguate partial dotted structures until
733 there is no way to disambguate partial dotted structures until
734 the full list is known. The caller is responsible for pruning
734 the full list is known. The caller is responsible for pruning
735 the final list of duplicates before using it."""
735 the final list of duplicates before using it."""
736
736
737 # build composite names
737 # build composite names
738 if token == '.':
738 if token == '.':
739 try:
739 try:
740 names[-1] += '.'
740 names[-1] += '.'
741 # store state so the next token is added for x.y.z names
741 # store state so the next token is added for x.y.z names
742 tokeneater.name_cont = True
742 tokeneater.name_cont = True
743 return
743 return
744 except IndexError:
744 except IndexError:
745 pass
745 pass
746 if token_type == tokenize.NAME and token not in keyword.kwlist:
746 if token_type == tokenize.NAME and token not in keyword.kwlist:
747 if tokeneater.name_cont:
747 if tokeneater.name_cont:
748 # Dotted names
748 # Dotted names
749 names[-1] += token
749 names[-1] += token
750 tokeneater.name_cont = False
750 tokeneater.name_cont = False
751 else:
751 else:
752 # Regular new names. We append everything, the caller
752 # Regular new names. We append everything, the caller
753 # will be responsible for pruning the list later. It's
753 # will be responsible for pruning the list later. It's
754 # very tricky to try to prune as we go, b/c composite
754 # very tricky to try to prune as we go, b/c composite
755 # names can fool us. The pruning at the end is easy
755 # names can fool us. The pruning at the end is easy
756 # to do (or the caller can print a list with repeated
756 # to do (or the caller can print a list with repeated
757 # names if so desired.
757 # names if so desired.
758 names.append(token)
758 names.append(token)
759 elif token_type == tokenize.NEWLINE:
759 elif token_type == tokenize.NEWLINE:
760 raise IndexError
760 raise IndexError
761 # we need to store a bit of state in the tokenizer to build
761 # we need to store a bit of state in the tokenizer to build
762 # dotted names
762 # dotted names
763 tokeneater.name_cont = False
763 tokeneater.name_cont = False
764
764
765 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
765 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
766 line = getline(file, lnum[0])
766 line = getline(file, lnum[0])
767 lnum[0] += 1
767 lnum[0] += 1
768 return line
768 return line
769
769
770 # Build the list of names on this line of code where the exception
770 # Build the list of names on this line of code where the exception
771 # occurred.
771 # occurred.
772 try:
772 try:
773 # This builds the names list in-place by capturing it from the
773 # This builds the names list in-place by capturing it from the
774 # enclosing scope.
774 # enclosing scope.
775 tokenize.tokenize(linereader, tokeneater)
775 tokenize.tokenize(linereader, tokeneater)
776 except IndexError:
776 except IndexError:
777 # signals exit of tokenizer
777 # signals exit of tokenizer
778 pass
778 pass
779 except tokenize.TokenError,msg:
779 except tokenize.TokenError,msg:
780 _m = ("An unexpected error occurred while tokenizing input\n"
780 _m = ("An unexpected error occurred while tokenizing input\n"
781 "The following traceback may be corrupted or invalid\n"
781 "The following traceback may be corrupted or invalid\n"
782 "The error message is: %s\n" % msg)
782 "The error message is: %s\n" % msg)
783 error(_m)
783 error(_m)
784
784
785 # prune names list of duplicates, but keep the right order
785 # prune names list of duplicates, but keep the right order
786 unique_names = uniq_stable(names)
786 unique_names = uniq_stable(names)
787
787
788 # Start loop over vars
788 # Start loop over vars
789 lvals = []
789 lvals = []
790 if self.include_vars:
790 if self.include_vars:
791 for name_full in unique_names:
791 for name_full in unique_names:
792 name_base = name_full.split('.',1)[0]
792 name_base = name_full.split('.',1)[0]
793 if name_base in frame.f_code.co_varnames:
793 if name_base in frame.f_code.co_varnames:
794 if locals.has_key(name_base):
794 if locals.has_key(name_base):
795 try:
795 try:
796 value = repr(eval(name_full,locals))
796 value = repr(eval(name_full,locals))
797 except:
797 except:
798 value = undefined
798 value = undefined
799 else:
799 else:
800 value = undefined
800 value = undefined
801 name = tpl_local_var % name_full
801 name = tpl_local_var % name_full
802 else:
802 else:
803 if frame.f_globals.has_key(name_base):
803 if frame.f_globals.has_key(name_base):
804 try:
804 try:
805 value = repr(eval(name_full,frame.f_globals))
805 value = repr(eval(name_full,frame.f_globals))
806 except:
806 except:
807 value = undefined
807 value = undefined
808 else:
808 else:
809 value = undefined
809 value = undefined
810 name = tpl_global_var % name_full
810 name = tpl_global_var % name_full
811 lvals.append(tpl_name_val % (name,value))
811 lvals.append(tpl_name_val % (name,value))
812 if lvals:
812 if lvals:
813 lvals = '%s%s' % (indent,em_normal.join(lvals))
813 lvals = '%s%s' % (indent,em_normal.join(lvals))
814 else:
814 else:
815 lvals = ''
815 lvals = ''
816
816
817 level = '%s %s\n' % (link,call)
817 level = '%s %s\n' % (link,call)
818
818
819 if index is None:
819 if index is None:
820 frames.append(level)
820 frames.append(level)
821 else:
821 else:
822 frames.append('%s%s' % (level,''.join(
822 frames.append('%s%s' % (level,''.join(
823 _format_traceback_lines(lnum,index,lines,Colors,lvals,
823 _format_traceback_lines(lnum,index,lines,Colors,lvals,
824 col_scheme))))
824 col_scheme))))
825
825
826 # Get (safely) a string form of the exception info
826 # Get (safely) a string form of the exception info
827 try:
827 try:
828 etype_str,evalue_str = map(str,(etype,evalue))
828 etype_str,evalue_str = map(str,(etype,evalue))
829 except:
829 except:
830 # User exception is improperly defined.
830 # User exception is improperly defined.
831 etype,evalue = str,sys.exc_info()[:2]
831 etype,evalue = str,sys.exc_info()[:2]
832 etype_str,evalue_str = map(str,(etype,evalue))
832 etype_str,evalue_str = map(str,(etype,evalue))
833 # ... and format it
833 # ... and format it
834 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
834 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
835 ColorsNormal, evalue_str)]
835 ColorsNormal, evalue_str)]
836 if type(evalue) is types.InstanceType:
836 if type(evalue) is types.InstanceType:
837 try:
837 try:
838 names = [w for w in dir(evalue) if isinstance(w, basestring)]
838 names = [w for w in dir(evalue) if isinstance(w, basestring)]
839 except:
839 except:
840 # Every now and then, an object with funny inernals blows up
840 # Every now and then, an object with funny inernals blows up
841 # when dir() is called on it. We do the best we can to report
841 # when dir() is called on it. We do the best we can to report
842 # the problem and continue
842 # the problem and continue
843 _m = '%sException reporting error (object with broken dir())%s:'
843 _m = '%sException reporting error (object with broken dir())%s:'
844 exception.append(_m % (Colors.excName,ColorsNormal))
844 exception.append(_m % (Colors.excName,ColorsNormal))
845 etype_str,evalue_str = map(str,sys.exc_info()[:2])
845 etype_str,evalue_str = map(str,sys.exc_info()[:2])
846 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
846 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
847 ColorsNormal, evalue_str))
847 ColorsNormal, evalue_str))
848 names = []
848 names = []
849 for name in names:
849 for name in names:
850 value = text_repr(getattr(evalue, name))
850 value = text_repr(getattr(evalue, name))
851 exception.append('\n%s%s = %s' % (indent, name, value))
851 exception.append('\n%s%s = %s' % (indent, name, value))
852
852
853 # vds: >>
853 # vds: >>
854 if records:
854 if records:
855 filepath, lnum = records[-1][1:3]
855 filepath, lnum = records[-1][1:3]
856 #print "file:", str(file), "linenb", str(lnum) # dbg
856 #print "file:", str(file), "linenb", str(lnum) # dbg
857 filepath = os.path.abspath(filepath)
857 filepath = os.path.abspath(filepath)
858 ipinst = ipapi.get()
858 ipinst = ipapi.get()
859 if ipinst is not None:
859 if ipinst is not None:
860 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
860 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
861 # vds: <<
861 # vds: <<
862
862
863 # return all our info assembled as a single string
863 # return all our info assembled as a single string
864 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
864 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
865
865
866 def debugger(self,force=False):
866 def debugger(self,force=False):
867 """Call up the pdb debugger if desired, always clean up the tb
867 """Call up the pdb debugger if desired, always clean up the tb
868 reference.
868 reference.
869
869
870 Keywords:
870 Keywords:
871
871
872 - force(False): by default, this routine checks the instance call_pdb
872 - force(False): by default, this routine checks the instance call_pdb
873 flag and does not actually invoke the debugger if the flag is false.
873 flag and does not actually invoke the debugger if the flag is false.
874 The 'force' option forces the debugger to activate even if the flag
874 The 'force' option forces the debugger to activate even if the flag
875 is false.
875 is false.
876
876
877 If the call_pdb flag is set, the pdb interactive debugger is
877 If the call_pdb flag is set, the pdb interactive debugger is
878 invoked. In all cases, the self.tb reference to the current traceback
878 invoked. In all cases, the self.tb reference to the current traceback
879 is deleted to prevent lingering references which hamper memory
879 is deleted to prevent lingering references which hamper memory
880 management.
880 management.
881
881
882 Note that each call to pdb() does an 'import readline', so if your app
882 Note that each call to pdb() does an 'import readline', so if your app
883 requires a special setup for the readline completers, you'll have to
883 requires a special setup for the readline completers, you'll have to
884 fix that by hand after invoking the exception handler."""
884 fix that by hand after invoking the exception handler."""
885
885
886 if force or self.call_pdb:
886 if force or self.call_pdb:
887 if self.pdb is None:
887 if self.pdb is None:
888 self.pdb = debugger.Pdb(
888 self.pdb = debugger.Pdb(
889 self.color_scheme_table.active_scheme_name)
889 self.color_scheme_table.active_scheme_name)
890 # the system displayhook may have changed, restore the original
890 # the system displayhook may have changed, restore the original
891 # for pdb
891 # for pdb
892 display_trap = DisplayTrap(None, sys.__displayhook__)
892 display_trap = DisplayTrap(None, sys.__displayhook__)
893 with display_trap:
893 with display_trap:
894 self.pdb.reset()
894 self.pdb.reset()
895 # Find the right frame so we don't pop up inside ipython itself
895 # Find the right frame so we don't pop up inside ipython itself
896 if hasattr(self,'tb') and self.tb is not None:
896 if hasattr(self,'tb') and self.tb is not None:
897 etb = self.tb
897 etb = self.tb
898 else:
898 else:
899 etb = self.tb = sys.last_traceback
899 etb = self.tb = sys.last_traceback
900 while self.tb is not None and self.tb.tb_next is not None:
900 while self.tb is not None and self.tb.tb_next is not None:
901 self.tb = self.tb.tb_next
901 self.tb = self.tb.tb_next
902 if etb and etb.tb_next:
902 if etb and etb.tb_next:
903 etb = etb.tb_next
903 etb = etb.tb_next
904 self.pdb.botframe = etb.tb_frame
904 self.pdb.botframe = etb.tb_frame
905 self.pdb.interaction(self.tb.tb_frame, self.tb)
905 self.pdb.interaction(self.tb.tb_frame, self.tb)
906
906
907 if hasattr(self,'tb'):
907 if hasattr(self,'tb'):
908 del self.tb
908 del self.tb
909
909
910 def handler(self, info=None):
910 def handler(self, info=None):
911 (etype, evalue, etb) = info or sys.exc_info()
911 (etype, evalue, etb) = info or sys.exc_info()
912 self.tb = etb
912 self.tb = etb
913 Term.cout.flush()
913 IPython.utils.io.Term.cout.flush()
914 Term.cerr.write(self.text(etype, evalue, etb))
914 IPython.utils.io.Term.cerr.write(self.text(etype, evalue, etb))
915 Term.cerr.write('\n')
915 IPython.utils.io.Term.cerr.write('\n')
916
916
917 # Changed so an instance can just be called as VerboseTB_inst() and print
917 # Changed so an instance can just be called as VerboseTB_inst() and print
918 # out the right info on its own.
918 # out the right info on its own.
919 def __call__(self, etype=None, evalue=None, etb=None):
919 def __call__(self, etype=None, evalue=None, etb=None):
920 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
920 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
921 if etb is None:
921 if etb is None:
922 self.handler()
922 self.handler()
923 else:
923 else:
924 self.handler((etype, evalue, etb))
924 self.handler((etype, evalue, etb))
925 try:
925 try:
926 self.debugger()
926 self.debugger()
927 except KeyboardInterrupt:
927 except KeyboardInterrupt:
928 print "\nKeyboardInterrupt"
928 print "\nKeyboardInterrupt"
929
929
930 #----------------------------------------------------------------------------
930 #----------------------------------------------------------------------------
931 class FormattedTB(VerboseTB,ListTB):
931 class FormattedTB(VerboseTB,ListTB):
932 """Subclass ListTB but allow calling with a traceback.
932 """Subclass ListTB but allow calling with a traceback.
933
933
934 It can thus be used as a sys.excepthook for Python > 2.1.
934 It can thus be used as a sys.excepthook for Python > 2.1.
935
935
936 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
936 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
937
937
938 Allows a tb_offset to be specified. This is useful for situations where
938 Allows a tb_offset to be specified. This is useful for situations where
939 one needs to remove a number of topmost frames from the traceback (such as
939 one needs to remove a number of topmost frames from the traceback (such as
940 occurs with python programs that themselves execute other python code,
940 occurs with python programs that themselves execute other python code,
941 like Python shells). """
941 like Python shells). """
942
942
943 def __init__(self, mode = 'Plain', color_scheme='Linux',
943 def __init__(self, mode = 'Plain', color_scheme='Linux',
944 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
944 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
945
945
946 # NEVER change the order of this list. Put new modes at the end:
946 # NEVER change the order of this list. Put new modes at the end:
947 self.valid_modes = ['Plain','Context','Verbose']
947 self.valid_modes = ['Plain','Context','Verbose']
948 self.verbose_modes = self.valid_modes[1:3]
948 self.verbose_modes = self.valid_modes[1:3]
949
949
950 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
950 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
951 call_pdb=call_pdb,include_vars=include_vars)
951 call_pdb=call_pdb,include_vars=include_vars)
952 self.set_mode(mode)
952 self.set_mode(mode)
953
953
954 def _extract_tb(self,tb):
954 def _extract_tb(self,tb):
955 if tb:
955 if tb:
956 return traceback.extract_tb(tb)
956 return traceback.extract_tb(tb)
957 else:
957 else:
958 return None
958 return None
959
959
960 def text(self, etype, value, tb,context=5,mode=None):
960 def text(self, etype, value, tb,context=5,mode=None):
961 """Return formatted traceback.
961 """Return formatted traceback.
962
962
963 If the optional mode parameter is given, it overrides the current
963 If the optional mode parameter is given, it overrides the current
964 mode."""
964 mode."""
965
965
966 if mode is None:
966 if mode is None:
967 mode = self.mode
967 mode = self.mode
968 if mode in self.verbose_modes:
968 if mode in self.verbose_modes:
969 # verbose modes need a full traceback
969 # verbose modes need a full traceback
970 return VerboseTB.text(self,etype, value, tb,context=5)
970 return VerboseTB.text(self,etype, value, tb,context=5)
971 else:
971 else:
972 # We must check the source cache because otherwise we can print
972 # We must check the source cache because otherwise we can print
973 # out-of-date source code.
973 # out-of-date source code.
974 linecache.checkcache()
974 linecache.checkcache()
975 # Now we can extract and format the exception
975 # Now we can extract and format the exception
976 elist = self._extract_tb(tb)
976 elist = self._extract_tb(tb)
977 if len(elist) > self.tb_offset:
977 if len(elist) > self.tb_offset:
978 del elist[:self.tb_offset]
978 del elist[:self.tb_offset]
979 return ListTB.text(self,etype,value,elist)
979 return ListTB.text(self,etype,value,elist)
980
980
981 def set_mode(self,mode=None):
981 def set_mode(self,mode=None):
982 """Switch to the desired mode.
982 """Switch to the desired mode.
983
983
984 If mode is not specified, cycles through the available modes."""
984 If mode is not specified, cycles through the available modes."""
985
985
986 if not mode:
986 if not mode:
987 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
987 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
988 len(self.valid_modes)
988 len(self.valid_modes)
989 self.mode = self.valid_modes[new_idx]
989 self.mode = self.valid_modes[new_idx]
990 elif mode not in self.valid_modes:
990 elif mode not in self.valid_modes:
991 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
991 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
992 'Valid modes: '+str(self.valid_modes)
992 'Valid modes: '+str(self.valid_modes)
993 else:
993 else:
994 self.mode = mode
994 self.mode = mode
995 # include variable details only in 'Verbose' mode
995 # include variable details only in 'Verbose' mode
996 self.include_vars = (self.mode == self.valid_modes[2])
996 self.include_vars = (self.mode == self.valid_modes[2])
997
997
998 # some convenient shorcuts
998 # some convenient shorcuts
999 def plain(self):
999 def plain(self):
1000 self.set_mode(self.valid_modes[0])
1000 self.set_mode(self.valid_modes[0])
1001
1001
1002 def context(self):
1002 def context(self):
1003 self.set_mode(self.valid_modes[1])
1003 self.set_mode(self.valid_modes[1])
1004
1004
1005 def verbose(self):
1005 def verbose(self):
1006 self.set_mode(self.valid_modes[2])
1006 self.set_mode(self.valid_modes[2])
1007
1007
1008 #----------------------------------------------------------------------------
1008 #----------------------------------------------------------------------------
1009 class AutoFormattedTB(FormattedTB):
1009 class AutoFormattedTB(FormattedTB):
1010 """A traceback printer which can be called on the fly.
1010 """A traceback printer which can be called on the fly.
1011
1011
1012 It will find out about exceptions by itself.
1012 It will find out about exceptions by itself.
1013
1013
1014 A brief example:
1014 A brief example:
1015
1015
1016 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1016 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1017 try:
1017 try:
1018 ...
1018 ...
1019 except:
1019 except:
1020 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1020 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1021 """
1021 """
1022
1022
1023 def __call__(self,etype=None,evalue=None,etb=None,
1023 def __call__(self,etype=None,evalue=None,etb=None,
1024 out=None,tb_offset=None):
1024 out=None,tb_offset=None):
1025 """Print out a formatted exception traceback.
1025 """Print out a formatted exception traceback.
1026
1026
1027 Optional arguments:
1027 Optional arguments:
1028 - out: an open file-like object to direct output to.
1028 - out: an open file-like object to direct output to.
1029
1029
1030 - tb_offset: the number of frames to skip over in the stack, on a
1030 - tb_offset: the number of frames to skip over in the stack, on a
1031 per-call basis (this overrides temporarily the instance's tb_offset
1031 per-call basis (this overrides temporarily the instance's tb_offset
1032 given at initialization time. """
1032 given at initialization time. """
1033
1033
1034 if out is None:
1034 if out is None:
1035 out = sys.stdout if self.out_stream=='stdout' else self.out_stream
1035 if self.out_stream == 'stdout':
1036 Term.cout.flush()
1036 out = sys.stdout
1037 else:
1038 out = IPython.utils.io.Term.cerr
1039 out.flush()
1037 if tb_offset is not None:
1040 if tb_offset is not None:
1038 tb_offset, self.tb_offset = self.tb_offset, tb_offset
1041 tb_offset, self.tb_offset = self.tb_offset, tb_offset
1039 out.write(self.text(etype, evalue, etb))
1042 out.write(self.text(etype, evalue, etb))
1040 out.write('\n')
1043 out.write('\n')
1041 self.tb_offset = tb_offset
1044 self.tb_offset = tb_offset
1042 else:
1045 else:
1043 out.write(self.text(etype, evalue, etb))
1046 out.write(self.text(etype, evalue, etb))
1044 out.write('\n')
1047 out.write('\n')
1045 out.flush()
1048 out.flush()
1046 try:
1049 try:
1047 self.debugger()
1050 self.debugger()
1048 except KeyboardInterrupt:
1051 except KeyboardInterrupt:
1049 print "\nKeyboardInterrupt"
1052 print "\nKeyboardInterrupt"
1050
1053
1051 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
1054 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
1052 if etype is None:
1055 if etype is None:
1053 etype,value,tb = sys.exc_info()
1056 etype,value,tb = sys.exc_info()
1054 self.tb = tb
1057 self.tb = tb
1055 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
1058 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
1056
1059
1057 #---------------------------------------------------------------------------
1060 #---------------------------------------------------------------------------
1058 # A simple class to preserve Nathan's original functionality.
1061 # A simple class to preserve Nathan's original functionality.
1059 class ColorTB(FormattedTB):
1062 class ColorTB(FormattedTB):
1060 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1063 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1061 def __init__(self,color_scheme='Linux',call_pdb=0):
1064 def __init__(self,color_scheme='Linux',call_pdb=0):
1062 FormattedTB.__init__(self,color_scheme=color_scheme,
1065 FormattedTB.__init__(self,color_scheme=color_scheme,
1063 call_pdb=call_pdb)
1066 call_pdb=call_pdb)
1064
1067
1065 #----------------------------------------------------------------------------
1068 #----------------------------------------------------------------------------
1066 # module testing (minimal)
1069 # module testing (minimal)
1067 if __name__ == "__main__":
1070 if __name__ == "__main__":
1068 def spam(c, (d, e)):
1071 def spam(c, (d, e)):
1069 x = c + d
1072 x = c + d
1070 y = c * d
1073 y = c * d
1071 foo(x, y)
1074 foo(x, y)
1072
1075
1073 def foo(a, b, bar=1):
1076 def foo(a, b, bar=1):
1074 eggs(a, b + bar)
1077 eggs(a, b + bar)
1075
1078
1076 def eggs(f, g, z=globals()):
1079 def eggs(f, g, z=globals()):
1077 h = f + g
1080 h = f + g
1078 i = f - g
1081 i = f - g
1079 return h / i
1082 return h / i
1080
1083
1081 print ''
1084 print ''
1082 print '*** Before ***'
1085 print '*** Before ***'
1083 try:
1086 try:
1084 print spam(1, (2, 3))
1087 print spam(1, (2, 3))
1085 except:
1088 except:
1086 traceback.print_exc()
1089 traceback.print_exc()
1087 print ''
1090 print ''
1088
1091
1089 handler = ColorTB()
1092 handler = ColorTB()
1090 print '*** ColorTB ***'
1093 print '*** ColorTB ***'
1091 try:
1094 try:
1092 print spam(1, (2, 3))
1095 print spam(1, (2, 3))
1093 except:
1096 except:
1094 apply(handler, sys.exc_info() )
1097 apply(handler, sys.exc_info() )
1095 print ''
1098 print ''
1096
1099
1097 handler = VerboseTB()
1100 handler = VerboseTB()
1098 print '*** VerboseTB ***'
1101 print '*** VerboseTB ***'
1099 try:
1102 try:
1100 print spam(1, (2, 3))
1103 print spam(1, (2, 3))
1101 except:
1104 except:
1102 apply(handler, sys.exc_info() )
1105 apply(handler, sys.exc_info() )
1103 print ''
1106 print ''
1104
1107
@@ -1,518 +1,518 b''
1 #!/usr/bin/python
1 #!/usr/bin/python
2 # -*- coding: iso-8859-15 -*-
2 # -*- coding: iso-8859-15 -*-
3 '''
3 '''
4 Provides IPython remote instance.
4 Provides IPython remote instance.
5
5
6 @author: Laurent Dufrechou
6 @author: Laurent Dufrechou
7 laurent.dufrechou _at_ gmail.com
7 laurent.dufrechou _at_ gmail.com
8 @license: BSD
8 @license: BSD
9
9
10 All rights reserved. This program and the accompanying materials are made
10 All rights reserved. This program and the accompanying materials are made
11 available under the terms of the BSD which accompanies this distribution, and
11 available under the terms of the BSD which accompanies this distribution, and
12 is available at U{http://www.opensource.org/licenses/bsd-license.php}
12 is available at U{http://www.opensource.org/licenses/bsd-license.php}
13 '''
13 '''
14
14
15 __version__ = 0.9
15 __version__ = 0.9
16 __author__ = "Laurent Dufrechou"
16 __author__ = "Laurent Dufrechou"
17 __email__ = "laurent.dufrechou _at_ gmail.com"
17 __email__ = "laurent.dufrechou _at_ gmail.com"
18 __license__ = "BSD"
18 __license__ = "BSD"
19
19
20 import re
20 import re
21 import sys
21 import sys
22 import os
22 import os
23 import locale
23 import locale
24 from thread_ex import ThreadEx
24 from thread_ex import ThreadEx
25
25
26 from IPython.core import iplib
26 from IPython.core import iplib
27 from IPython.utils.io import Term
27 import IPython.utils.io
28
28
29 ##############################################################################
29 ##############################################################################
30 class _Helper(object):
30 class _Helper(object):
31 """Redefine the built-in 'help'.
31 """Redefine the built-in 'help'.
32 This is a wrapper around pydoc.help (with a twist).
32 This is a wrapper around pydoc.help (with a twist).
33 """
33 """
34
34
35 def __init__(self, pager):
35 def __init__(self, pager):
36 self._pager = pager
36 self._pager = pager
37
37
38 def __repr__(self):
38 def __repr__(self):
39 return "Type help() for interactive help, " \
39 return "Type help() for interactive help, " \
40 "or help(object) for help about object."
40 "or help(object) for help about object."
41
41
42 def __call__(self, *args, **kwds):
42 def __call__(self, *args, **kwds):
43 class DummyWriter(object):
43 class DummyWriter(object):
44 '''Dumy class to handle help output'''
44 '''Dumy class to handle help output'''
45 def __init__(self, pager):
45 def __init__(self, pager):
46 self._pager = pager
46 self._pager = pager
47
47
48 def write(self, data):
48 def write(self, data):
49 '''hook to fill self._pager'''
49 '''hook to fill self._pager'''
50 self._pager(data)
50 self._pager(data)
51
51
52 import pydoc
52 import pydoc
53 pydoc.help.output = DummyWriter(self._pager)
53 pydoc.help.output = DummyWriter(self._pager)
54 pydoc.help.interact = lambda :1
54 pydoc.help.interact = lambda :1
55
55
56 return pydoc.help(*args, **kwds)
56 return pydoc.help(*args, **kwds)
57
57
58
58
59 ##############################################################################
59 ##############################################################################
60 class _CodeExecutor(ThreadEx):
60 class _CodeExecutor(ThreadEx):
61 ''' Thread that execute ipython code '''
61 ''' Thread that execute ipython code '''
62 def __init__(self, instance):
62 def __init__(self, instance):
63 ThreadEx.__init__(self)
63 ThreadEx.__init__(self)
64 self.instance = instance
64 self.instance = instance
65
65
66 def run(self):
66 def run(self):
67 '''Thread main loop'''
67 '''Thread main loop'''
68 try:
68 try:
69 self.instance._doc_text = None
69 self.instance._doc_text = None
70 self.instance._help_text = None
70 self.instance._help_text = None
71 self.instance._execute()
71 self.instance._execute()
72 # used for uper class to generate event after execution
72 # used for uper class to generate event after execution
73 self.instance._after_execute()
73 self.instance._after_execute()
74
74
75 except KeyboardInterrupt:
75 except KeyboardInterrupt:
76 pass
76 pass
77
77
78
78
79 ##############################################################################
79 ##############################################################################
80 class NonBlockingIPShell(object):
80 class NonBlockingIPShell(object):
81 '''
81 '''
82 Create an IPython instance, running the commands in a separate,
82 Create an IPython instance, running the commands in a separate,
83 non-blocking thread.
83 non-blocking thread.
84 This allows embedding in any GUI without blockage.
84 This allows embedding in any GUI without blockage.
85
85
86 Note: The ThreadEx class supports asynchroneous function call
86 Note: The ThreadEx class supports asynchroneous function call
87 via raise_exc()
87 via raise_exc()
88 '''
88 '''
89
89
90 def __init__(self, user_ns={}, user_global_ns=None,
90 def __init__(self, user_ns={}, user_global_ns=None,
91 cin=None, cout=None, cerr=None,
91 cin=None, cout=None, cerr=None,
92 ask_exit_handler=None):
92 ask_exit_handler=None):
93 '''
93 '''
94 @param user_ns: User namespace.
94 @param user_ns: User namespace.
95 @type user_ns: dictionary
95 @type user_ns: dictionary
96 @param user_global_ns: User global namespace.
96 @param user_global_ns: User global namespace.
97 @type user_global_ns: dictionary.
97 @type user_global_ns: dictionary.
98 @param cin: Console standard input.
98 @param cin: Console standard input.
99 @type cin: IO stream
99 @type cin: IO stream
100 @param cout: Console standard output.
100 @param cout: Console standard output.
101 @type cout: IO stream
101 @type cout: IO stream
102 @param cerr: Console standard error.
102 @param cerr: Console standard error.
103 @type cerr: IO stream
103 @type cerr: IO stream
104 @param exit_handler: Replacement for builtin exit() function
104 @param exit_handler: Replacement for builtin exit() function
105 @type exit_handler: function
105 @type exit_handler: function
106 @param time_loop: Define the sleep time between two thread's loop
106 @param time_loop: Define the sleep time between two thread's loop
107 @type int
107 @type int
108 '''
108 '''
109 #ipython0 initialisation
109 #ipython0 initialisation
110 self._IP = None
110 self._IP = None
111 self.init_ipython0(user_ns, user_global_ns,
111 self.init_ipython0(user_ns, user_global_ns,
112 cin, cout, cerr,
112 cin, cout, cerr,
113 ask_exit_handler)
113 ask_exit_handler)
114
114
115 #vars used by _execute
115 #vars used by _execute
116 self._iter_more = 0
116 self._iter_more = 0
117 self._history_level = 0
117 self._history_level = 0
118 self._complete_sep = re.compile('[\s\{\}\[\]\(\)\=]')
118 self._complete_sep = re.compile('[\s\{\}\[\]\(\)\=]')
119 self._prompt = str(self._IP.outputcache.prompt1).strip()
119 self._prompt = str(self._IP.outputcache.prompt1).strip()
120
120
121 #thread working vars
121 #thread working vars
122 self._line_to_execute = ''
122 self._line_to_execute = ''
123 self._threading = True
123 self._threading = True
124
124
125 #vars that will be checked by GUI loop to handle thread states...
125 #vars that will be checked by GUI loop to handle thread states...
126 #will be replaced later by PostEvent GUI funtions...
126 #will be replaced later by PostEvent GUI funtions...
127 self._doc_text = None
127 self._doc_text = None
128 self._help_text = None
128 self._help_text = None
129 self._add_button = None
129 self._add_button = None
130
130
131 def init_ipython0(self, user_ns={}, user_global_ns=None,
131 def init_ipython0(self, user_ns={}, user_global_ns=None,
132 cin=None, cout=None, cerr=None,
132 cin=None, cout=None, cerr=None,
133 ask_exit_handler=None):
133 ask_exit_handler=None):
134 ''' Initialize an ipython0 instance '''
134 ''' Initialize an ipython0 instance '''
135
135
136 #first we redefine in/out/error functions of IPython
136 #first we redefine in/out/error functions of IPython
137 #BUG: we've got a limitation form ipython0 there
137 #BUG: we've got a limitation form ipython0 there
138 #only one instance can be instanciated else tehre will be
138 #only one instance can be instanciated else tehre will be
139 #cin/cout/cerr clash...
139 #cin/cout/cerr clash...
140 if cin:
140 if cin:
141 Term.cin = cin
141 Term.cin = cin
142 if cout:
142 if cout:
143 Term.cout = cout
143 Term.cout = cout
144 if cerr:
144 if cerr:
145 Term.cerr = cerr
145 Term.cerr = cerr
146
146
147 excepthook = sys.excepthook
147 excepthook = sys.excepthook
148
148
149 #Hack to save sys.displayhook, because ipython seems to overwrite it...
149 #Hack to save sys.displayhook, because ipython seems to overwrite it...
150 self.sys_displayhook_ori = sys.displayhook
150 self.sys_displayhook_ori = sys.displayhook
151 ipython0 = iplib.InteractiveShell(
151 ipython0 = iplib.InteractiveShell(
152 parent=None, config=None,
152 parent=None, config=None,
153 user_ns=user_ns,
153 user_ns=user_ns,
154 user_global_ns=user_global_ns
154 user_global_ns=user_global_ns
155 )
155 )
156 self._IP = ipython0
156 self._IP = ipython0
157
157
158 #we save ipython0 displayhook and we restore sys.displayhook
158 #we save ipython0 displayhook and we restore sys.displayhook
159 self.displayhook = sys.displayhook
159 self.displayhook = sys.displayhook
160 sys.displayhook = self.sys_displayhook_ori
160 sys.displayhook = self.sys_displayhook_ori
161
161
162 #we replace IPython default encoding by wx locale encoding
162 #we replace IPython default encoding by wx locale encoding
163 loc = locale.getpreferredencoding()
163 loc = locale.getpreferredencoding()
164 if loc:
164 if loc:
165 self._IP.stdin_encoding = loc
165 self._IP.stdin_encoding = loc
166 #we replace the ipython default pager by our pager
166 #we replace the ipython default pager by our pager
167 self._IP.set_hook('show_in_pager', self._pager)
167 self._IP.set_hook('show_in_pager', self._pager)
168
168
169 #we replace the ipython default shell command caller
169 #we replace the ipython default shell command caller
170 #by our shell handler
170 #by our shell handler
171 self._IP.set_hook('shell_hook', self._shell)
171 self._IP.set_hook('shell_hook', self._shell)
172
172
173 #we replace the ipython default input command caller by our method
173 #we replace the ipython default input command caller by our method
174 iplib.raw_input_original = self._raw_input_original
174 iplib.raw_input_original = self._raw_input_original
175 #we replace the ipython default exit command by our method
175 #we replace the ipython default exit command by our method
176 self._IP.exit = ask_exit_handler
176 self._IP.exit = ask_exit_handler
177 #we replace the help command
177 #we replace the help command
178 self._IP.user_ns['help'] = _Helper(self._pager_help)
178 self._IP.user_ns['help'] = _Helper(self._pager_help)
179
179
180 #we disable cpaste magic... until we found a way to use it properly.
180 #we disable cpaste magic... until we found a way to use it properly.
181 def bypass_magic(self, arg):
181 def bypass_magic(self, arg):
182 print '%this magic is currently disabled.'
182 print '%this magic is currently disabled.'
183 ipython0.define_magic('cpaste', bypass_magic)
183 ipython0.define_magic('cpaste', bypass_magic)
184
184
185 import __builtin__
185 import __builtin__
186 __builtin__.raw_input = self._raw_input
186 __builtin__.raw_input = self._raw_input
187
187
188 sys.excepthook = excepthook
188 sys.excepthook = excepthook
189
189
190 #----------------------- Thread management section ----------------------
190 #----------------------- Thread management section ----------------------
191 def do_execute(self, line):
191 def do_execute(self, line):
192 """
192 """
193 Tell the thread to process the 'line' command
193 Tell the thread to process the 'line' command
194 """
194 """
195
195
196 self._line_to_execute = line
196 self._line_to_execute = line
197
197
198 if self._threading:
198 if self._threading:
199 #we launch the ipython line execution in a thread to make it
199 #we launch the ipython line execution in a thread to make it
200 #interruptible with include it in self namespace to be able
200 #interruptible with include it in self namespace to be able
201 #to call ce.raise_exc(KeyboardInterrupt)
201 #to call ce.raise_exc(KeyboardInterrupt)
202 self.ce = _CodeExecutor(self)
202 self.ce = _CodeExecutor(self)
203 self.ce.start()
203 self.ce.start()
204 else:
204 else:
205 try:
205 try:
206 self._doc_text = None
206 self._doc_text = None
207 self._help_text = None
207 self._help_text = None
208 self._execute()
208 self._execute()
209 # used for uper class to generate event after execution
209 # used for uper class to generate event after execution
210 self._after_execute()
210 self._after_execute()
211
211
212 except KeyboardInterrupt:
212 except KeyboardInterrupt:
213 pass
213 pass
214
214
215 #----------------------- IPython management section ----------------------
215 #----------------------- IPython management section ----------------------
216 def get_threading(self):
216 def get_threading(self):
217 """
217 """
218 Returns threading status, is set to True, then each command sent to
218 Returns threading status, is set to True, then each command sent to
219 the interpreter will be executed in a separated thread allowing,
219 the interpreter will be executed in a separated thread allowing,
220 for example, breaking a long running commands.
220 for example, breaking a long running commands.
221 Disallowing it, permits better compatibilty with instance that is embedding
221 Disallowing it, permits better compatibilty with instance that is embedding
222 IPython instance.
222 IPython instance.
223
223
224 @return: Execution method
224 @return: Execution method
225 @rtype: bool
225 @rtype: bool
226 """
226 """
227 return self._threading
227 return self._threading
228
228
229 def set_threading(self, state):
229 def set_threading(self, state):
230 """
230 """
231 Sets threading state, if set to True, then each command sent to
231 Sets threading state, if set to True, then each command sent to
232 the interpreter will be executed in a separated thread allowing,
232 the interpreter will be executed in a separated thread allowing,
233 for example, breaking a long running commands.
233 for example, breaking a long running commands.
234 Disallowing it, permits better compatibilty with instance that is embedding
234 Disallowing it, permits better compatibilty with instance that is embedding
235 IPython instance.
235 IPython instance.
236
236
237 @param state: Sets threading state
237 @param state: Sets threading state
238 @type bool
238 @type bool
239 """
239 """
240 self._threading = state
240 self._threading = state
241
241
242 def get_doc_text(self):
242 def get_doc_text(self):
243 """
243 """
244 Returns the output of the processing that need to be paged (if any)
244 Returns the output of the processing that need to be paged (if any)
245
245
246 @return: The std output string.
246 @return: The std output string.
247 @rtype: string
247 @rtype: string
248 """
248 """
249 return self._doc_text
249 return self._doc_text
250
250
251 def get_help_text(self):
251 def get_help_text(self):
252 """
252 """
253 Returns the output of the processing that need to be paged via help pager(if any)
253 Returns the output of the processing that need to be paged via help pager(if any)
254
254
255 @return: The std output string.
255 @return: The std output string.
256 @rtype: string
256 @rtype: string
257 """
257 """
258 return self._help_text
258 return self._help_text
259
259
260 def get_banner(self):
260 def get_banner(self):
261 """
261 """
262 Returns the IPython banner for useful info on IPython instance
262 Returns the IPython banner for useful info on IPython instance
263
263
264 @return: The banner string.
264 @return: The banner string.
265 @rtype: string
265 @rtype: string
266 """
266 """
267 return self._IP.banner
267 return self._IP.banner
268
268
269 def get_prompt_count(self):
269 def get_prompt_count(self):
270 """
270 """
271 Returns the prompt number.
271 Returns the prompt number.
272 Each time a user execute a line in the IPython shell the prompt count is increased
272 Each time a user execute a line in the IPython shell the prompt count is increased
273
273
274 @return: The prompt number
274 @return: The prompt number
275 @rtype: int
275 @rtype: int
276 """
276 """
277 return self._IP.outputcache.prompt_count
277 return self._IP.outputcache.prompt_count
278
278
279 def get_prompt(self):
279 def get_prompt(self):
280 """
280 """
281 Returns current prompt inside IPython instance
281 Returns current prompt inside IPython instance
282 (Can be In [...]: ot ...:)
282 (Can be In [...]: ot ...:)
283
283
284 @return: The current prompt.
284 @return: The current prompt.
285 @rtype: string
285 @rtype: string
286 """
286 """
287 return self._prompt
287 return self._prompt
288
288
289 def get_indentation(self):
289 def get_indentation(self):
290 """
290 """
291 Returns the current indentation level
291 Returns the current indentation level
292 Usefull to put the caret at the good start position if we want to do autoindentation.
292 Usefull to put the caret at the good start position if we want to do autoindentation.
293
293
294 @return: The indentation level.
294 @return: The indentation level.
295 @rtype: int
295 @rtype: int
296 """
296 """
297 return self._IP.indent_current_nsp
297 return self._IP.indent_current_nsp
298
298
299 def update_namespace(self, ns_dict):
299 def update_namespace(self, ns_dict):
300 '''
300 '''
301 Add the current dictionary to the shell namespace.
301 Add the current dictionary to the shell namespace.
302
302
303 @param ns_dict: A dictionary of symbol-values.
303 @param ns_dict: A dictionary of symbol-values.
304 @type ns_dict: dictionary
304 @type ns_dict: dictionary
305 '''
305 '''
306 self._IP.user_ns.update(ns_dict)
306 self._IP.user_ns.update(ns_dict)
307
307
308 def complete(self, line):
308 def complete(self, line):
309 '''
309 '''
310 Returns an auto completed line and/or posibilities for completion.
310 Returns an auto completed line and/or posibilities for completion.
311
311
312 @param line: Given line so far.
312 @param line: Given line so far.
313 @type line: string
313 @type line: string
314
314
315 @return: Line completed as for as possible,
315 @return: Line completed as for as possible,
316 and possible further completions.
316 and possible further completions.
317 @rtype: tuple
317 @rtype: tuple
318 '''
318 '''
319 split_line = self._complete_sep.split(line)
319 split_line = self._complete_sep.split(line)
320 possibilities = self._IP.complete(split_line[-1])
320 possibilities = self._IP.complete(split_line[-1])
321 if possibilities:
321 if possibilities:
322
322
323 def _common_prefix(str1, str2):
323 def _common_prefix(str1, str2):
324 '''
324 '''
325 Reduction function. returns common prefix of two given strings.
325 Reduction function. returns common prefix of two given strings.
326
326
327 @param str1: First string.
327 @param str1: First string.
328 @type str1: string
328 @type str1: string
329 @param str2: Second string
329 @param str2: Second string
330 @type str2: string
330 @type str2: string
331
331
332 @return: Common prefix to both strings.
332 @return: Common prefix to both strings.
333 @rtype: string
333 @rtype: string
334 '''
334 '''
335 for i in range(len(str1)):
335 for i in range(len(str1)):
336 if not str2.startswith(str1[:i+1]):
336 if not str2.startswith(str1[:i+1]):
337 return str1[:i]
337 return str1[:i]
338 return str1
338 return str1
339 common_prefix = reduce(_common_prefix, possibilities)
339 common_prefix = reduce(_common_prefix, possibilities)
340 completed = line[:-len(split_line[-1])]+common_prefix
340 completed = line[:-len(split_line[-1])]+common_prefix
341 else:
341 else:
342 completed = line
342 completed = line
343 return completed, possibilities
343 return completed, possibilities
344
344
345 def history_back(self):
345 def history_back(self):
346 '''
346 '''
347 Provides one history command back.
347 Provides one history command back.
348
348
349 @return: The command string.
349 @return: The command string.
350 @rtype: string
350 @rtype: string
351 '''
351 '''
352 history = ''
352 history = ''
353 #the below while loop is used to suppress empty history lines
353 #the below while loop is used to suppress empty history lines
354 while((history == '' or history == '\n') and self._history_level >0):
354 while((history == '' or history == '\n') and self._history_level >0):
355 if self._history_level >= 1:
355 if self._history_level >= 1:
356 self._history_level -= 1
356 self._history_level -= 1
357 history = self._get_history()
357 history = self._get_history()
358 return history
358 return history
359
359
360 def history_forward(self):
360 def history_forward(self):
361 '''
361 '''
362 Provides one history command forward.
362 Provides one history command forward.
363
363
364 @return: The command string.
364 @return: The command string.
365 @rtype: string
365 @rtype: string
366 '''
366 '''
367 history = ''
367 history = ''
368 #the below while loop is used to suppress empty history lines
368 #the below while loop is used to suppress empty history lines
369 while((history == '' or history == '\n') \
369 while((history == '' or history == '\n') \
370 and self._history_level <= self._get_history_max_index()):
370 and self._history_level <= self._get_history_max_index()):
371 if self._history_level < self._get_history_max_index():
371 if self._history_level < self._get_history_max_index():
372 self._history_level += 1
372 self._history_level += 1
373 history = self._get_history()
373 history = self._get_history()
374 else:
374 else:
375 if self._history_level == self._get_history_max_index():
375 if self._history_level == self._get_history_max_index():
376 history = self._get_history()
376 history = self._get_history()
377 self._history_level += 1
377 self._history_level += 1
378 else:
378 else:
379 history = ''
379 history = ''
380 return history
380 return history
381
381
382 def init_history_index(self):
382 def init_history_index(self):
383 '''
383 '''
384 set history to last command entered
384 set history to last command entered
385 '''
385 '''
386 self._history_level = self._get_history_max_index()+1
386 self._history_level = self._get_history_max_index()+1
387
387
388 #----------------------- IPython PRIVATE management section --------------
388 #----------------------- IPython PRIVATE management section --------------
389 def _after_execute(self):
389 def _after_execute(self):
390 '''
390 '''
391 Can be redefined to generate post event after excution is done
391 Can be redefined to generate post event after excution is done
392 '''
392 '''
393 pass
393 pass
394
394
395 def _ask_exit(self):
395 def _ask_exit(self):
396 '''
396 '''
397 Can be redefined to generate post event to exit the Ipython shell
397 Can be redefined to generate post event to exit the Ipython shell
398 '''
398 '''
399 pass
399 pass
400
400
401 def _get_history_max_index(self):
401 def _get_history_max_index(self):
402 '''
402 '''
403 returns the max length of the history buffer
403 returns the max length of the history buffer
404
404
405 @return: history length
405 @return: history length
406 @rtype: int
406 @rtype: int
407 '''
407 '''
408 return len(self._IP.input_hist_raw)-1
408 return len(self._IP.input_hist_raw)-1
409
409
410 def _get_history(self):
410 def _get_history(self):
411 '''
411 '''
412 Get's the command string of the current history level.
412 Get's the command string of the current history level.
413
413
414 @return: Historic command stri
414 @return: Historic command stri
415 @rtype: string
415 @rtype: string
416 '''
416 '''
417 rv = self._IP.input_hist_raw[self._history_level].strip('\n')
417 rv = self._IP.input_hist_raw[self._history_level].strip('\n')
418 return rv
418 return rv
419
419
420 def _pager_help(self, text):
420 def _pager_help(self, text):
421 '''
421 '''
422 This function is used as a callback replacment to IPython help pager function
422 This function is used as a callback replacment to IPython help pager function
423
423
424 It puts the 'text' value inside the self._help_text string that can be retrived via
424 It puts the 'text' value inside the self._help_text string that can be retrived via
425 get_help_text function.
425 get_help_text function.
426 '''
426 '''
427 if self._help_text == None:
427 if self._help_text == None:
428 self._help_text = text
428 self._help_text = text
429 else:
429 else:
430 self._help_text += text
430 self._help_text += text
431
431
432 def _pager(self, IP, text):
432 def _pager(self, IP, text):
433 '''
433 '''
434 This function is used as a callback replacment to IPython pager function
434 This function is used as a callback replacment to IPython pager function
435
435
436 It puts the 'text' value inside the self._doc_text string that can be retrived via
436 It puts the 'text' value inside the self._doc_text string that can be retrived via
437 get_doc_text function.
437 get_doc_text function.
438 '''
438 '''
439 self._doc_text = text
439 self._doc_text = text
440
440
441 def _raw_input_original(self, prompt=''):
441 def _raw_input_original(self, prompt=''):
442 '''
442 '''
443 Custom raw_input() replacement. Get's current line from console buffer.
443 Custom raw_input() replacement. Get's current line from console buffer.
444
444
445 @param prompt: Prompt to print. Here for compatability as replacement.
445 @param prompt: Prompt to print. Here for compatability as replacement.
446 @type prompt: string
446 @type prompt: string
447
447
448 @return: The current command line text.
448 @return: The current command line text.
449 @rtype: string
449 @rtype: string
450 '''
450 '''
451 return self._line_to_execute
451 return self._line_to_execute
452
452
453 def _raw_input(self, prompt=''):
453 def _raw_input(self, prompt=''):
454 """ A replacement from python's raw_input.
454 """ A replacement from python's raw_input.
455 """
455 """
456 raise NotImplementedError
456 raise NotImplementedError
457
457
458 def _execute(self):
458 def _execute(self):
459 '''
459 '''
460 Executes the current line provided by the shell object.
460 Executes the current line provided by the shell object.
461 '''
461 '''
462
462
463 orig_stdout = sys.stdout
463 orig_stdout = sys.stdout
464 sys.stdout = Term.cout
464 sys.stdout = Term.cout
465 #self.sys_displayhook_ori = sys.displayhook
465 #self.sys_displayhook_ori = sys.displayhook
466 #sys.displayhook = self.displayhook
466 #sys.displayhook = self.displayhook
467
467
468 try:
468 try:
469 line = self._IP.raw_input(None, self._iter_more)
469 line = self._IP.raw_input(None, self._iter_more)
470 if self._IP.autoindent:
470 if self._IP.autoindent:
471 self._IP.readline_startup_hook(None)
471 self._IP.readline_startup_hook(None)
472
472
473 except KeyboardInterrupt:
473 except KeyboardInterrupt:
474 self._IP.write('\nKeyboardInterrupt\n')
474 self._IP.write('\nKeyboardInterrupt\n')
475 self._IP.resetbuffer()
475 self._IP.resetbuffer()
476 # keep cache in sync with the prompt counter:
476 # keep cache in sync with the prompt counter:
477 self._IP.outputcache.prompt_count -= 1
477 self._IP.outputcache.prompt_count -= 1
478
478
479 if self._IP.autoindent:
479 if self._IP.autoindent:
480 self._IP.indent_current_nsp = 0
480 self._IP.indent_current_nsp = 0
481 self._iter_more = 0
481 self._iter_more = 0
482 except:
482 except:
483 self._IP.showtraceback()
483 self._IP.showtraceback()
484 else:
484 else:
485 self._IP.write(str(self._IP.outputcache.prompt_out).strip())
485 self._IP.write(str(self._IP.outputcache.prompt_out).strip())
486 self._iter_more = self._IP.push_line(line)
486 self._iter_more = self._IP.push_line(line)
487 if (self._IP.SyntaxTB.last_syntax_error and \
487 if (self._IP.SyntaxTB.last_syntax_error and \
488 self._IP.autoedit_syntax):
488 self._IP.autoedit_syntax):
489 self._IP.edit_syntax_error()
489 self._IP.edit_syntax_error()
490 if self._iter_more:
490 if self._iter_more:
491 self._prompt = str(self._IP.outputcache.prompt2).strip()
491 self._prompt = str(self._IP.outputcache.prompt2).strip()
492 if self._IP.autoindent:
492 if self._IP.autoindent:
493 self._IP.readline_startup_hook(self._IP.pre_readline)
493 self._IP.readline_startup_hook(self._IP.pre_readline)
494 else:
494 else:
495 self._prompt = str(self._IP.outputcache.prompt1).strip()
495 self._prompt = str(self._IP.outputcache.prompt1).strip()
496 self._IP.indent_current_nsp = 0 #we set indentation to 0
496 self._IP.indent_current_nsp = 0 #we set indentation to 0
497
497
498 sys.stdout = orig_stdout
498 sys.stdout = orig_stdout
499 #sys.displayhook = self.sys_displayhook_ori
499 #sys.displayhook = self.sys_displayhook_ori
500
500
501 def _shell(self, ip, cmd):
501 def _shell(self, ip, cmd):
502 '''
502 '''
503 Replacement method to allow shell commands without them blocking.
503 Replacement method to allow shell commands without them blocking.
504
504
505 @param ip: Ipython instance, same as self._IP
505 @param ip: Ipython instance, same as self._IP
506 @type cmd: Ipython instance
506 @type cmd: Ipython instance
507 @param cmd: Shell command to execute.
507 @param cmd: Shell command to execute.
508 @type cmd: string
508 @type cmd: string
509 '''
509 '''
510 stdin, stdout = os.popen4(cmd)
510 stdin, stdout = os.popen4(cmd)
511 result = stdout.read().decode('cp437').\
511 result = stdout.read().decode('cp437').\
512 encode(locale.getpreferredencoding())
512 encode(locale.getpreferredencoding())
513 #we use print command because the shell command is called
513 #we use print command because the shell command is called
514 #inside IPython instance and thus is redirected to thread cout
514 #inside IPython instance and thus is redirected to thread cout
515 #"\x01\x1b[1;36m\x02" <-- add colour to the text...
515 #"\x01\x1b[1;36m\x02" <-- add colour to the text...
516 print "\x01\x1b[1;36m\x02"+result
516 print "\x01\x1b[1;36m\x02"+result
517 stdout.close()
517 stdout.close()
518 stdin.close()
518 stdin.close()
@@ -1,2328 +1,2328 b''
1 # -*- coding: iso-8859-1 -*-
1 # -*- coding: iso-8859-1 -*-
2
2
3 """
3 """
4 ``ipipe`` provides classes to be used in an interactive Python session. Doing a
4 ``ipipe`` provides classes to be used in an interactive Python session. Doing a
5 ``from ipipe import *`` is the preferred way to do this. The name of all
5 ``from ipipe import *`` is the preferred way to do this. The name of all
6 objects imported this way starts with ``i`` to minimize collisions.
6 objects imported this way starts with ``i`` to minimize collisions.
7
7
8 ``ipipe`` supports "pipeline expressions", which is something resembling Unix
8 ``ipipe`` supports "pipeline expressions", which is something resembling Unix
9 pipes. An example is::
9 pipes. An example is::
10
10
11 >>> ienv | isort("key.lower()")
11 >>> ienv | isort("key.lower()")
12
12
13 This gives a listing of all environment variables sorted by name.
13 This gives a listing of all environment variables sorted by name.
14
14
15
15
16 There are three types of objects in a pipeline expression:
16 There are three types of objects in a pipeline expression:
17
17
18 * ``Table``s: These objects produce items. Examples are ``ils`` (listing the
18 * ``Table``s: These objects produce items. Examples are ``ils`` (listing the
19 current directory, ``ienv`` (listing environment variables), ``ipwd`` (listing
19 current directory, ``ienv`` (listing environment variables), ``ipwd`` (listing
20 user accounts) and ``igrp`` (listing user groups). A ``Table`` must be the
20 user accounts) and ``igrp`` (listing user groups). A ``Table`` must be the
21 first object in a pipe expression.
21 first object in a pipe expression.
22
22
23 * ``Pipe``s: These objects sit in the middle of a pipe expression. They
23 * ``Pipe``s: These objects sit in the middle of a pipe expression. They
24 transform the input in some way (e.g. filtering or sorting it). Examples are:
24 transform the input in some way (e.g. filtering or sorting it). Examples are:
25 ``ifilter`` (which filters the input pipe), ``isort`` (which sorts the input
25 ``ifilter`` (which filters the input pipe), ``isort`` (which sorts the input
26 pipe) and ``ieval`` (which evaluates a function or expression for each object
26 pipe) and ``ieval`` (which evaluates a function or expression for each object
27 in the input pipe).
27 in the input pipe).
28
28
29 * ``Display``s: These objects can be put as the last object in a pipeline
29 * ``Display``s: These objects can be put as the last object in a pipeline
30 expression. There are responsible for displaying the result of the pipeline
30 expression. There are responsible for displaying the result of the pipeline
31 expression. If a pipeline expression doesn't end in a display object a default
31 expression. If a pipeline expression doesn't end in a display object a default
32 display objects will be used. One example is ``ibrowse`` which is a ``curses``
32 display objects will be used. One example is ``ibrowse`` which is a ``curses``
33 based browser.
33 based browser.
34
34
35
35
36 Adding support for pipeline expressions to your own objects can be done through
36 Adding support for pipeline expressions to your own objects can be done through
37 three extensions points (all of them optional):
37 three extensions points (all of them optional):
38
38
39 * An object that will be displayed as a row by a ``Display`` object should
39 * An object that will be displayed as a row by a ``Display`` object should
40 implement the method ``__xattrs__(self, mode)`` method or register an
40 implement the method ``__xattrs__(self, mode)`` method or register an
41 implementation of the generic function ``xattrs``. For more info see ``xattrs``.
41 implementation of the generic function ``xattrs``. For more info see ``xattrs``.
42
42
43 * When an object ``foo`` is displayed by a ``Display`` object, the generic
43 * When an object ``foo`` is displayed by a ``Display`` object, the generic
44 function ``xrepr`` is used.
44 function ``xrepr`` is used.
45
45
46 * Objects that can be iterated by ``Pipe``s must iterable. For special cases,
46 * Objects that can be iterated by ``Pipe``s must iterable. For special cases,
47 where iteration for display is different than the normal iteration a special
47 where iteration for display is different than the normal iteration a special
48 implementation can be registered with the generic function ``xiter``. This
48 implementation can be registered with the generic function ``xiter``. This
49 makes it possible to use dictionaries and modules in pipeline expressions,
49 makes it possible to use dictionaries and modules in pipeline expressions,
50 for example::
50 for example::
51
51
52 >>> import sys
52 >>> import sys
53 >>> sys | ifilter("isinstance(value, int)") | idump
53 >>> sys | ifilter("isinstance(value, int)") | idump
54 key |value
54 key |value
55 api_version| 1012
55 api_version| 1012
56 dllhandle | 503316480
56 dllhandle | 503316480
57 hexversion | 33817328
57 hexversion | 33817328
58 maxint |2147483647
58 maxint |2147483647
59 maxunicode | 65535
59 maxunicode | 65535
60 >>> sys.modules | ifilter("_.value is not None") | isort("_.key.lower()")
60 >>> sys.modules | ifilter("_.value is not None") | isort("_.key.lower()")
61 ...
61 ...
62
62
63 Note: The expression strings passed to ``ifilter()`` and ``isort()`` can
63 Note: The expression strings passed to ``ifilter()`` and ``isort()`` can
64 refer to the object to be filtered or sorted via the variable ``_`` and to any
64 refer to the object to be filtered or sorted via the variable ``_`` and to any
65 of the attributes of the object, i.e.::
65 of the attributes of the object, i.e.::
66
66
67 >>> sys.modules | ifilter("_.value is not None") | isort("_.key.lower()")
67 >>> sys.modules | ifilter("_.value is not None") | isort("_.key.lower()")
68
68
69 does the same as::
69 does the same as::
70
70
71 >>> sys.modules | ifilter("value is not None") | isort("key.lower()")
71 >>> sys.modules | ifilter("value is not None") | isort("key.lower()")
72
72
73 In addition to expression strings, it's possible to pass callables (taking
73 In addition to expression strings, it's possible to pass callables (taking
74 the object as an argument) to ``ifilter()``, ``isort()`` and ``ieval()``::
74 the object as an argument) to ``ifilter()``, ``isort()`` and ``ieval()``::
75
75
76 >>> sys | ifilter(lambda _:isinstance(_.value, int)) \
76 >>> sys | ifilter(lambda _:isinstance(_.value, int)) \
77 ... | ieval(lambda _: (_.key, hex(_.value))) | idump
77 ... | ieval(lambda _: (_.key, hex(_.value))) | idump
78 0 |1
78 0 |1
79 api_version|0x3f4
79 api_version|0x3f4
80 dllhandle |0x1e000000
80 dllhandle |0x1e000000
81 hexversion |0x20402f0
81 hexversion |0x20402f0
82 maxint |0x7fffffff
82 maxint |0x7fffffff
83 maxunicode |0xffff
83 maxunicode |0xffff
84 """
84 """
85
85
86 skip_doctest = True # ignore top-level docstring as a doctest.
86 skip_doctest = True # ignore top-level docstring as a doctest.
87
87
88 import sys, os, os.path, stat, glob, new, csv, datetime, types
88 import sys, os, os.path, stat, glob, new, csv, datetime, types
89 import itertools, mimetypes, StringIO
89 import itertools, mimetypes, StringIO
90
90
91 try: # Python 2.3 compatibility
91 try: # Python 2.3 compatibility
92 import collections
92 import collections
93 except ImportError:
93 except ImportError:
94 deque = list
94 deque = list
95 else:
95 else:
96 deque = collections.deque
96 deque = collections.deque
97
97
98 try: # Python 2.3 compatibility
98 try: # Python 2.3 compatibility
99 set
99 set
100 except NameError:
100 except NameError:
101 import sets
101 import sets
102 set = sets.Set
102 set = sets.Set
103
103
104 try: # Python 2.3 compatibility
104 try: # Python 2.3 compatibility
105 sorted
105 sorted
106 except NameError:
106 except NameError:
107 def sorted(iterator, key=None, reverse=False):
107 def sorted(iterator, key=None, reverse=False):
108 items = list(iterator)
108 items = list(iterator)
109 if key is not None:
109 if key is not None:
110 items.sort(lambda i1, i2: cmp(key(i1), key(i2)))
110 items.sort(lambda i1, i2: cmp(key(i1), key(i2)))
111 else:
111 else:
112 items.sort()
112 items.sort()
113 if reverse:
113 if reverse:
114 items.reverse()
114 items.reverse()
115 return items
115 return items
116
116
117 try: # Python 2.4 compatibility
117 try: # Python 2.4 compatibility
118 GeneratorExit
118 GeneratorExit
119 except NameError:
119 except NameError:
120 GeneratorExit = SystemExit
120 GeneratorExit = SystemExit
121
121
122 try:
122 try:
123 import pwd
123 import pwd
124 except ImportError:
124 except ImportError:
125 pwd = None
125 pwd = None
126
126
127 try:
127 try:
128 import grp
128 import grp
129 except ImportError:
129 except ImportError:
130 grp = None
130 grp = None
131
131
132 from IPython.external import simplegeneric
132 from IPython.external import simplegeneric
133 from IPython.external import path
133 from IPython.external import path
134
134
135 try:
135 try:
136 from IPython.utils.io import Term
136 import IPython.utils.io
137 from IPython.utils import generics
137 from IPython.utils import generics
138 except ImportError:
138 except ImportError:
139 Term = None
139 Term = None
140 generics = None
140 generics = None
141
141
142 from IPython.core import ipapi
142 from IPython.core import ipapi
143
143
144
144
145 __all__ = [
145 __all__ = [
146 "ifile", "ils", "iglob", "iwalk", "ipwdentry", "ipwd", "igrpentry", "igrp",
146 "ifile", "ils", "iglob", "iwalk", "ipwdentry", "ipwd", "igrpentry", "igrp",
147 "icsv", "ix", "ichain", "isort", "ifilter", "ieval", "ienum",
147 "icsv", "ix", "ichain", "isort", "ifilter", "ieval", "ienum",
148 "ienv", "ihist", "ialias", "icap", "idump", "iless"
148 "ienv", "ihist", "ialias", "icap", "idump", "iless"
149 ]
149 ]
150
150
151
151
152 os.stat_float_times(True) # enable microseconds
152 os.stat_float_times(True) # enable microseconds
153
153
154
154
155 class AttrNamespace(object):
155 class AttrNamespace(object):
156 """
156 """
157 Helper class that is used for providing a namespace for evaluating
157 Helper class that is used for providing a namespace for evaluating
158 expressions containing attribute names of an object.
158 expressions containing attribute names of an object.
159 """
159 """
160 def __init__(self, wrapped):
160 def __init__(self, wrapped):
161 self.wrapped = wrapped
161 self.wrapped = wrapped
162
162
163 def __getitem__(self, name):
163 def __getitem__(self, name):
164 if name == "_":
164 if name == "_":
165 return self.wrapped
165 return self.wrapped
166 try:
166 try:
167 return getattr(self.wrapped, name)
167 return getattr(self.wrapped, name)
168 except AttributeError:
168 except AttributeError:
169 raise KeyError(name)
169 raise KeyError(name)
170
170
171 # Python 2.3 compatibility
171 # Python 2.3 compatibility
172 # use eval workaround to find out which names are used in the
172 # use eval workaround to find out which names are used in the
173 # eval string and put them into the locals. This works for most
173 # eval string and put them into the locals. This works for most
174 # normal uses case, bizarre ones like accessing the locals()
174 # normal uses case, bizarre ones like accessing the locals()
175 # will fail
175 # will fail
176 try:
176 try:
177 eval("_", None, AttrNamespace(None))
177 eval("_", None, AttrNamespace(None))
178 except TypeError:
178 except TypeError:
179 real_eval = eval
179 real_eval = eval
180 def eval(codestring, _globals, _locals):
180 def eval(codestring, _globals, _locals):
181 """
181 """
182 eval(source[, globals[, locals]]) -> value
182 eval(source[, globals[, locals]]) -> value
183
183
184 Evaluate the source in the context of globals and locals.
184 Evaluate the source in the context of globals and locals.
185 The source may be a string representing a Python expression
185 The source may be a string representing a Python expression
186 or a code object as returned by compile().
186 or a code object as returned by compile().
187 The globals must be a dictionary and locals can be any mappping.
187 The globals must be a dictionary and locals can be any mappping.
188
188
189 This function is a workaround for the shortcomings of
189 This function is a workaround for the shortcomings of
190 Python 2.3's eval.
190 Python 2.3's eval.
191 """
191 """
192
192
193 if isinstance(codestring, basestring):
193 if isinstance(codestring, basestring):
194 code = compile(codestring, "_eval", "eval")
194 code = compile(codestring, "_eval", "eval")
195 else:
195 else:
196 code = codestring
196 code = codestring
197 newlocals = {}
197 newlocals = {}
198 for name in code.co_names:
198 for name in code.co_names:
199 try:
199 try:
200 newlocals[name] = _locals[name]
200 newlocals[name] = _locals[name]
201 except KeyError:
201 except KeyError:
202 pass
202 pass
203 return real_eval(code, _globals, newlocals)
203 return real_eval(code, _globals, newlocals)
204
204
205
205
206 noitem = object()
206 noitem = object()
207
207
208
208
209 def item(iterator, index, default=noitem):
209 def item(iterator, index, default=noitem):
210 """
210 """
211 Return the ``index``th item from the iterator ``iterator``.
211 Return the ``index``th item from the iterator ``iterator``.
212 ``index`` must be an integer (negative integers are relative to the
212 ``index`` must be an integer (negative integers are relative to the
213 end (i.e. the last items produced by the iterator)).
213 end (i.e. the last items produced by the iterator)).
214
214
215 If ``default`` is given, this will be the default value when
215 If ``default`` is given, this will be the default value when
216 the iterator doesn't contain an item at this position. Otherwise an
216 the iterator doesn't contain an item at this position. Otherwise an
217 ``IndexError`` will be raised.
217 ``IndexError`` will be raised.
218
218
219 Note that using this function will partially or totally exhaust the
219 Note that using this function will partially or totally exhaust the
220 iterator.
220 iterator.
221 """
221 """
222 i = index
222 i = index
223 if i>=0:
223 if i>=0:
224 for item in iterator:
224 for item in iterator:
225 if not i:
225 if not i:
226 return item
226 return item
227 i -= 1
227 i -= 1
228 else:
228 else:
229 i = -index
229 i = -index
230 cache = deque()
230 cache = deque()
231 for item in iterator:
231 for item in iterator:
232 cache.append(item)
232 cache.append(item)
233 if len(cache)>i:
233 if len(cache)>i:
234 cache.popleft()
234 cache.popleft()
235 if len(cache)==i:
235 if len(cache)==i:
236 return cache.popleft()
236 return cache.popleft()
237 if default is noitem:
237 if default is noitem:
238 raise IndexError(index)
238 raise IndexError(index)
239 else:
239 else:
240 return default
240 return default
241
241
242
242
243 def getglobals(g):
243 def getglobals(g):
244 """
244 """
245 Return the global namespace that is used for expression strings in
245 Return the global namespace that is used for expression strings in
246 ``ifilter`` and others. This is ``g`` or (if ``g`` is ``None``) IPython's
246 ``ifilter`` and others. This is ``g`` or (if ``g`` is ``None``) IPython's
247 user namespace.
247 user namespace.
248 """
248 """
249 if g is None:
249 if g is None:
250 if ipapi is not None:
250 if ipapi is not None:
251 api = ipapi.get()
251 api = ipapi.get()
252 if api is not None:
252 if api is not None:
253 return api.user_ns
253 return api.user_ns
254 return globals()
254 return globals()
255 return g
255 return g
256
256
257
257
258 class Descriptor(object):
258 class Descriptor(object):
259 """
259 """
260 A ``Descriptor`` object is used for describing the attributes of objects.
260 A ``Descriptor`` object is used for describing the attributes of objects.
261 """
261 """
262 def __hash__(self):
262 def __hash__(self):
263 return hash(self.__class__) ^ hash(self.key())
263 return hash(self.__class__) ^ hash(self.key())
264
264
265 def __eq__(self, other):
265 def __eq__(self, other):
266 return self.__class__ is other.__class__ and self.key() == other.key()
266 return self.__class__ is other.__class__ and self.key() == other.key()
267
267
268 def __ne__(self, other):
268 def __ne__(self, other):
269 return self.__class__ is not other.__class__ or self.key() != other.key()
269 return self.__class__ is not other.__class__ or self.key() != other.key()
270
270
271 def key(self):
271 def key(self):
272 pass
272 pass
273
273
274 def name(self):
274 def name(self):
275 """
275 """
276 Return the name of this attribute for display by a ``Display`` object
276 Return the name of this attribute for display by a ``Display`` object
277 (e.g. as a column title).
277 (e.g. as a column title).
278 """
278 """
279 key = self.key()
279 key = self.key()
280 if key is None:
280 if key is None:
281 return "_"
281 return "_"
282 return str(key)
282 return str(key)
283
283
284 def attrtype(self, obj):
284 def attrtype(self, obj):
285 """
285 """
286 Return the type of this attribute (i.e. something like "attribute" or
286 Return the type of this attribute (i.e. something like "attribute" or
287 "method").
287 "method").
288 """
288 """
289
289
290 def valuetype(self, obj):
290 def valuetype(self, obj):
291 """
291 """
292 Return the type of this attribute value of the object ``obj``.
292 Return the type of this attribute value of the object ``obj``.
293 """
293 """
294
294
295 def value(self, obj):
295 def value(self, obj):
296 """
296 """
297 Return the value of this attribute of the object ``obj``.
297 Return the value of this attribute of the object ``obj``.
298 """
298 """
299
299
300 def doc(self, obj):
300 def doc(self, obj):
301 """
301 """
302 Return the documentation for this attribute.
302 Return the documentation for this attribute.
303 """
303 """
304
304
305 def shortdoc(self, obj):
305 def shortdoc(self, obj):
306 """
306 """
307 Return a short documentation for this attribute (defaulting to the
307 Return a short documentation for this attribute (defaulting to the
308 first line).
308 first line).
309 """
309 """
310 doc = self.doc(obj)
310 doc = self.doc(obj)
311 if doc is not None:
311 if doc is not None:
312 doc = doc.strip().splitlines()[0].strip()
312 doc = doc.strip().splitlines()[0].strip()
313 return doc
313 return doc
314
314
315 def iter(self, obj):
315 def iter(self, obj):
316 """
316 """
317 Return an iterator for this attribute of the object ``obj``.
317 Return an iterator for this attribute of the object ``obj``.
318 """
318 """
319 return xiter(self.value(obj))
319 return xiter(self.value(obj))
320
320
321
321
322 class SelfDescriptor(Descriptor):
322 class SelfDescriptor(Descriptor):
323 """
323 """
324 A ``SelfDescriptor`` describes the object itself.
324 A ``SelfDescriptor`` describes the object itself.
325 """
325 """
326 def key(self):
326 def key(self):
327 return None
327 return None
328
328
329 def attrtype(self, obj):
329 def attrtype(self, obj):
330 return "self"
330 return "self"
331
331
332 def valuetype(self, obj):
332 def valuetype(self, obj):
333 return type(obj)
333 return type(obj)
334
334
335 def value(self, obj):
335 def value(self, obj):
336 return obj
336 return obj
337
337
338 def __repr__(self):
338 def __repr__(self):
339 return "Self"
339 return "Self"
340
340
341 selfdescriptor = SelfDescriptor() # there's no need for more than one
341 selfdescriptor = SelfDescriptor() # there's no need for more than one
342
342
343
343
344 class AttributeDescriptor(Descriptor):
344 class AttributeDescriptor(Descriptor):
345 """
345 """
346 An ``AttributeDescriptor`` describes a simple attribute of an object.
346 An ``AttributeDescriptor`` describes a simple attribute of an object.
347 """
347 """
348 __slots__ = ("_name", "_doc")
348 __slots__ = ("_name", "_doc")
349
349
350 def __init__(self, name, doc=None):
350 def __init__(self, name, doc=None):
351 self._name = name
351 self._name = name
352 self._doc = doc
352 self._doc = doc
353
353
354 def key(self):
354 def key(self):
355 return self._name
355 return self._name
356
356
357 def doc(self, obj):
357 def doc(self, obj):
358 return self._doc
358 return self._doc
359
359
360 def attrtype(self, obj):
360 def attrtype(self, obj):
361 return "attr"
361 return "attr"
362
362
363 def valuetype(self, obj):
363 def valuetype(self, obj):
364 return type(getattr(obj, self._name))
364 return type(getattr(obj, self._name))
365
365
366 def value(self, obj):
366 def value(self, obj):
367 return getattr(obj, self._name)
367 return getattr(obj, self._name)
368
368
369 def __repr__(self):
369 def __repr__(self):
370 if self._doc is None:
370 if self._doc is None:
371 return "Attribute(%r)" % self._name
371 return "Attribute(%r)" % self._name
372 else:
372 else:
373 return "Attribute(%r, %r)" % (self._name, self._doc)
373 return "Attribute(%r, %r)" % (self._name, self._doc)
374
374
375
375
376 class IndexDescriptor(Descriptor):
376 class IndexDescriptor(Descriptor):
377 """
377 """
378 An ``IndexDescriptor`` describes an "attribute" of an object that is fetched
378 An ``IndexDescriptor`` describes an "attribute" of an object that is fetched
379 via ``__getitem__``.
379 via ``__getitem__``.
380 """
380 """
381 __slots__ = ("_index",)
381 __slots__ = ("_index",)
382
382
383 def __init__(self, index):
383 def __init__(self, index):
384 self._index = index
384 self._index = index
385
385
386 def key(self):
386 def key(self):
387 return self._index
387 return self._index
388
388
389 def attrtype(self, obj):
389 def attrtype(self, obj):
390 return "item"
390 return "item"
391
391
392 def valuetype(self, obj):
392 def valuetype(self, obj):
393 return type(obj[self._index])
393 return type(obj[self._index])
394
394
395 def value(self, obj):
395 def value(self, obj):
396 return obj[self._index]
396 return obj[self._index]
397
397
398 def __repr__(self):
398 def __repr__(self):
399 return "Index(%r)" % self._index
399 return "Index(%r)" % self._index
400
400
401
401
402 class MethodDescriptor(Descriptor):
402 class MethodDescriptor(Descriptor):
403 """
403 """
404 A ``MethodDescriptor`` describes a method of an object that can be called
404 A ``MethodDescriptor`` describes a method of an object that can be called
405 without argument. Note that this method shouldn't change the object.
405 without argument. Note that this method shouldn't change the object.
406 """
406 """
407 __slots__ = ("_name", "_doc")
407 __slots__ = ("_name", "_doc")
408
408
409 def __init__(self, name, doc=None):
409 def __init__(self, name, doc=None):
410 self._name = name
410 self._name = name
411 self._doc = doc
411 self._doc = doc
412
412
413 def key(self):
413 def key(self):
414 return self._name
414 return self._name
415
415
416 def doc(self, obj):
416 def doc(self, obj):
417 if self._doc is None:
417 if self._doc is None:
418 return getattr(obj, self._name).__doc__
418 return getattr(obj, self._name).__doc__
419 return self._doc
419 return self._doc
420
420
421 def attrtype(self, obj):
421 def attrtype(self, obj):
422 return "method"
422 return "method"
423
423
424 def valuetype(self, obj):
424 def valuetype(self, obj):
425 return type(self.value(obj))
425 return type(self.value(obj))
426
426
427 def value(self, obj):
427 def value(self, obj):
428 return getattr(obj, self._name)()
428 return getattr(obj, self._name)()
429
429
430 def __repr__(self):
430 def __repr__(self):
431 if self._doc is None:
431 if self._doc is None:
432 return "Method(%r)" % self._name
432 return "Method(%r)" % self._name
433 else:
433 else:
434 return "Method(%r, %r)" % (self._name, self._doc)
434 return "Method(%r, %r)" % (self._name, self._doc)
435
435
436
436
437 class IterAttributeDescriptor(Descriptor):
437 class IterAttributeDescriptor(Descriptor):
438 """
438 """
439 An ``IterAttributeDescriptor`` works like an ``AttributeDescriptor`` but
439 An ``IterAttributeDescriptor`` works like an ``AttributeDescriptor`` but
440 doesn't return an attribute values (because this value might be e.g. a large
440 doesn't return an attribute values (because this value might be e.g. a large
441 list).
441 list).
442 """
442 """
443 __slots__ = ("_name", "_doc")
443 __slots__ = ("_name", "_doc")
444
444
445 def __init__(self, name, doc=None):
445 def __init__(self, name, doc=None):
446 self._name = name
446 self._name = name
447 self._doc = doc
447 self._doc = doc
448
448
449 def key(self):
449 def key(self):
450 return self._name
450 return self._name
451
451
452 def doc(self, obj):
452 def doc(self, obj):
453 return self._doc
453 return self._doc
454
454
455 def attrtype(self, obj):
455 def attrtype(self, obj):
456 return "iter"
456 return "iter"
457
457
458 def valuetype(self, obj):
458 def valuetype(self, obj):
459 return noitem
459 return noitem
460
460
461 def value(self, obj):
461 def value(self, obj):
462 return noitem
462 return noitem
463
463
464 def iter(self, obj):
464 def iter(self, obj):
465 return xiter(getattr(obj, self._name))
465 return xiter(getattr(obj, self._name))
466
466
467 def __repr__(self):
467 def __repr__(self):
468 if self._doc is None:
468 if self._doc is None:
469 return "IterAttribute(%r)" % self._name
469 return "IterAttribute(%r)" % self._name
470 else:
470 else:
471 return "IterAttribute(%r, %r)" % (self._name, self._doc)
471 return "IterAttribute(%r, %r)" % (self._name, self._doc)
472
472
473
473
474 class IterMethodDescriptor(Descriptor):
474 class IterMethodDescriptor(Descriptor):
475 """
475 """
476 An ``IterMethodDescriptor`` works like an ``MethodDescriptor`` but doesn't
476 An ``IterMethodDescriptor`` works like an ``MethodDescriptor`` but doesn't
477 return an attribute values (because this value might be e.g. a large list).
477 return an attribute values (because this value might be e.g. a large list).
478 """
478 """
479 __slots__ = ("_name", "_doc")
479 __slots__ = ("_name", "_doc")
480
480
481 def __init__(self, name, doc=None):
481 def __init__(self, name, doc=None):
482 self._name = name
482 self._name = name
483 self._doc = doc
483 self._doc = doc
484
484
485 def key(self):
485 def key(self):
486 return self._name
486 return self._name
487
487
488 def doc(self, obj):
488 def doc(self, obj):
489 if self._doc is None:
489 if self._doc is None:
490 return getattr(obj, self._name).__doc__
490 return getattr(obj, self._name).__doc__
491 return self._doc
491 return self._doc
492
492
493 def attrtype(self, obj):
493 def attrtype(self, obj):
494 return "itermethod"
494 return "itermethod"
495
495
496 def valuetype(self, obj):
496 def valuetype(self, obj):
497 return noitem
497 return noitem
498
498
499 def value(self, obj):
499 def value(self, obj):
500 return noitem
500 return noitem
501
501
502 def iter(self, obj):
502 def iter(self, obj):
503 return xiter(getattr(obj, self._name)())
503 return xiter(getattr(obj, self._name)())
504
504
505 def __repr__(self):
505 def __repr__(self):
506 if self._doc is None:
506 if self._doc is None:
507 return "IterMethod(%r)" % self._name
507 return "IterMethod(%r)" % self._name
508 else:
508 else:
509 return "IterMethod(%r, %r)" % (self._name, self._doc)
509 return "IterMethod(%r, %r)" % (self._name, self._doc)
510
510
511
511
512 class FunctionDescriptor(Descriptor):
512 class FunctionDescriptor(Descriptor):
513 """
513 """
514 A ``FunctionDescriptor`` turns a function into a descriptor. The function
514 A ``FunctionDescriptor`` turns a function into a descriptor. The function
515 will be called with the object to get the type and value of the attribute.
515 will be called with the object to get the type and value of the attribute.
516 """
516 """
517 __slots__ = ("_function", "_name", "_doc")
517 __slots__ = ("_function", "_name", "_doc")
518
518
519 def __init__(self, function, name=None, doc=None):
519 def __init__(self, function, name=None, doc=None):
520 self._function = function
520 self._function = function
521 self._name = name
521 self._name = name
522 self._doc = doc
522 self._doc = doc
523
523
524 def key(self):
524 def key(self):
525 return self._function
525 return self._function
526
526
527 def name(self):
527 def name(self):
528 if self._name is not None:
528 if self._name is not None:
529 return self._name
529 return self._name
530 return getattr(self._function, "__xname__", self._function.__name__)
530 return getattr(self._function, "__xname__", self._function.__name__)
531
531
532 def doc(self, obj):
532 def doc(self, obj):
533 if self._doc is None:
533 if self._doc is None:
534 return self._function.__doc__
534 return self._function.__doc__
535 return self._doc
535 return self._doc
536
536
537 def attrtype(self, obj):
537 def attrtype(self, obj):
538 return "function"
538 return "function"
539
539
540 def valuetype(self, obj):
540 def valuetype(self, obj):
541 return type(self._function(obj))
541 return type(self._function(obj))
542
542
543 def value(self, obj):
543 def value(self, obj):
544 return self._function(obj)
544 return self._function(obj)
545
545
546 def __repr__(self):
546 def __repr__(self):
547 if self._doc is None:
547 if self._doc is None:
548 return "Function(%r)" % self._name
548 return "Function(%r)" % self._name
549 else:
549 else:
550 return "Function(%r, %r)" % (self._name, self._doc)
550 return "Function(%r, %r)" % (self._name, self._doc)
551
551
552
552
553 class Table(object):
553 class Table(object):
554 """
554 """
555 A ``Table`` is an object that produces items (just like a normal Python
555 A ``Table`` is an object that produces items (just like a normal Python
556 iterator/generator does) and can be used as the first object in a pipeline
556 iterator/generator does) and can be used as the first object in a pipeline
557 expression. The displayhook will open the default browser for such an object
557 expression. The displayhook will open the default browser for such an object
558 (instead of simply printing the ``repr()`` result).
558 (instead of simply printing the ``repr()`` result).
559 """
559 """
560
560
561 # We want to support ``foo`` and ``foo()`` in pipeline expression:
561 # We want to support ``foo`` and ``foo()`` in pipeline expression:
562 # So we implement the required operators (``|`` and ``+``) in the metaclass,
562 # So we implement the required operators (``|`` and ``+``) in the metaclass,
563 # instantiate the class and forward the operator to the instance
563 # instantiate the class and forward the operator to the instance
564 class __metaclass__(type):
564 class __metaclass__(type):
565 def __iter__(self):
565 def __iter__(self):
566 return iter(self())
566 return iter(self())
567
567
568 def __or__(self, other):
568 def __or__(self, other):
569 return self() | other
569 return self() | other
570
570
571 def __add__(self, other):
571 def __add__(self, other):
572 return self() + other
572 return self() + other
573
573
574 def __radd__(self, other):
574 def __radd__(self, other):
575 return other + self()
575 return other + self()
576
576
577 def __getitem__(self, index):
577 def __getitem__(self, index):
578 return self()[index]
578 return self()[index]
579
579
580 def __getitem__(self, index):
580 def __getitem__(self, index):
581 return item(self, index)
581 return item(self, index)
582
582
583 def __contains__(self, item):
583 def __contains__(self, item):
584 for haveitem in self:
584 for haveitem in self:
585 if item == haveitem:
585 if item == haveitem:
586 return True
586 return True
587 return False
587 return False
588
588
589 def __or__(self, other):
589 def __or__(self, other):
590 # autoinstantiate right hand side
590 # autoinstantiate right hand side
591 if isinstance(other, type) and issubclass(other, (Table, Display)):
591 if isinstance(other, type) and issubclass(other, (Table, Display)):
592 other = other()
592 other = other()
593 # treat simple strings and functions as ``ieval`` instances
593 # treat simple strings and functions as ``ieval`` instances
594 elif not isinstance(other, Display) and not isinstance(other, Table):
594 elif not isinstance(other, Display) and not isinstance(other, Table):
595 other = ieval(other)
595 other = ieval(other)
596 # forward operations to the right hand side
596 # forward operations to the right hand side
597 return other.__ror__(self)
597 return other.__ror__(self)
598
598
599 def __add__(self, other):
599 def __add__(self, other):
600 # autoinstantiate right hand side
600 # autoinstantiate right hand side
601 if isinstance(other, type) and issubclass(other, Table):
601 if isinstance(other, type) and issubclass(other, Table):
602 other = other()
602 other = other()
603 return ichain(self, other)
603 return ichain(self, other)
604
604
605 def __radd__(self, other):
605 def __radd__(self, other):
606 # autoinstantiate left hand side
606 # autoinstantiate left hand side
607 if isinstance(other, type) and issubclass(other, Table):
607 if isinstance(other, type) and issubclass(other, Table):
608 other = other()
608 other = other()
609 return ichain(other, self)
609 return ichain(other, self)
610
610
611
611
612 class Pipe(Table):
612 class Pipe(Table):
613 """
613 """
614 A ``Pipe`` is an object that can be used in a pipeline expression. It
614 A ``Pipe`` is an object that can be used in a pipeline expression. It
615 processes the objects it gets from its input ``Table``/``Pipe``. Note that
615 processes the objects it gets from its input ``Table``/``Pipe``. Note that
616 a ``Pipe`` object can't be used as the first object in a pipeline
616 a ``Pipe`` object can't be used as the first object in a pipeline
617 expression, as it doesn't produces items itself.
617 expression, as it doesn't produces items itself.
618 """
618 """
619 class __metaclass__(Table.__metaclass__):
619 class __metaclass__(Table.__metaclass__):
620 def __ror__(self, input):
620 def __ror__(self, input):
621 return input | self()
621 return input | self()
622
622
623 def __ror__(self, input):
623 def __ror__(self, input):
624 # autoinstantiate left hand side
624 # autoinstantiate left hand side
625 if isinstance(input, type) and issubclass(input, Table):
625 if isinstance(input, type) and issubclass(input, Table):
626 input = input()
626 input = input()
627 self.input = input
627 self.input = input
628 return self
628 return self
629
629
630
630
631 def xrepr(item, mode="default"):
631 def xrepr(item, mode="default"):
632 """
632 """
633 Generic function that adds color output and different display modes to ``repr``.
633 Generic function that adds color output and different display modes to ``repr``.
634
634
635 The result of an ``xrepr`` call is iterable and consists of ``(style, string)``
635 The result of an ``xrepr`` call is iterable and consists of ``(style, string)``
636 tuples. The ``style`` in this tuple must be a ``Style`` object from the
636 tuples. The ``style`` in this tuple must be a ``Style`` object from the
637 ``astring`` module. To reconfigure the output the first yielded tuple can be
637 ``astring`` module. To reconfigure the output the first yielded tuple can be
638 a ``(aligment, full)`` tuple instead of a ``(style, string)`` tuple.
638 a ``(aligment, full)`` tuple instead of a ``(style, string)`` tuple.
639 ``alignment`` can be -1 for left aligned, 0 for centered and 1 for right
639 ``alignment`` can be -1 for left aligned, 0 for centered and 1 for right
640 aligned (the default is left alignment). ``full`` is a boolean that specifies
640 aligned (the default is left alignment). ``full`` is a boolean that specifies
641 whether the complete output must be displayed or the ``Display`` object is
641 whether the complete output must be displayed or the ``Display`` object is
642 allowed to stop output after enough text has been produced (e.g. a syntax
642 allowed to stop output after enough text has been produced (e.g. a syntax
643 highlighted text line would use ``True``, but for a large data structure
643 highlighted text line would use ``True``, but for a large data structure
644 (i.e. a nested list, tuple or dictionary) ``False`` would be used).
644 (i.e. a nested list, tuple or dictionary) ``False`` would be used).
645 The default is full output.
645 The default is full output.
646
646
647 There are four different possible values for ``mode`` depending on where
647 There are four different possible values for ``mode`` depending on where
648 the ``Display`` object will display ``item``:
648 the ``Display`` object will display ``item``:
649
649
650 ``"header"``
650 ``"header"``
651 ``item`` will be displayed in a header line (this is used by ``ibrowse``).
651 ``item`` will be displayed in a header line (this is used by ``ibrowse``).
652
652
653 ``"footer"``
653 ``"footer"``
654 ``item`` will be displayed in a footer line (this is used by ``ibrowse``).
654 ``item`` will be displayed in a footer line (this is used by ``ibrowse``).
655
655
656 ``"cell"``
656 ``"cell"``
657 ``item`` will be displayed in a table cell/list.
657 ``item`` will be displayed in a table cell/list.
658
658
659 ``"default"``
659 ``"default"``
660 default mode. If an ``xrepr`` implementation recursively outputs objects,
660 default mode. If an ``xrepr`` implementation recursively outputs objects,
661 ``"default"`` must be passed in the recursive calls to ``xrepr``.
661 ``"default"`` must be passed in the recursive calls to ``xrepr``.
662
662
663 If no implementation is registered for ``item``, ``xrepr`` will try the
663 If no implementation is registered for ``item``, ``xrepr`` will try the
664 ``__xrepr__`` method on ``item``. If ``item`` doesn't have an ``__xrepr__``
664 ``__xrepr__`` method on ``item``. If ``item`` doesn't have an ``__xrepr__``
665 method it falls back to ``repr``/``__repr__`` for all modes.
665 method it falls back to ``repr``/``__repr__`` for all modes.
666 """
666 """
667 try:
667 try:
668 func = item.__xrepr__
668 func = item.__xrepr__
669 except AttributeError:
669 except AttributeError:
670 yield (astyle.style_default, repr(item))
670 yield (astyle.style_default, repr(item))
671 else:
671 else:
672 try:
672 try:
673 for x in func(mode):
673 for x in func(mode):
674 yield x
674 yield x
675 except (KeyboardInterrupt, SystemExit, GeneratorExit):
675 except (KeyboardInterrupt, SystemExit, GeneratorExit):
676 raise
676 raise
677 except Exception:
677 except Exception:
678 yield (astyle.style_default, repr(item))
678 yield (astyle.style_default, repr(item))
679 xrepr = simplegeneric.generic(xrepr)
679 xrepr = simplegeneric.generic(xrepr)
680
680
681
681
682 def xrepr_none(self, mode="default"):
682 def xrepr_none(self, mode="default"):
683 yield (astyle.style_type_none, repr(self))
683 yield (astyle.style_type_none, repr(self))
684 xrepr.when_object(None)(xrepr_none)
684 xrepr.when_object(None)(xrepr_none)
685
685
686
686
687 def xrepr_noitem(self, mode="default"):
687 def xrepr_noitem(self, mode="default"):
688 yield (2, True)
688 yield (2, True)
689 yield (astyle.style_nodata, "<?>")
689 yield (astyle.style_nodata, "<?>")
690 xrepr.when_object(noitem)(xrepr_noitem)
690 xrepr.when_object(noitem)(xrepr_noitem)
691
691
692
692
693 def xrepr_bool(self, mode="default"):
693 def xrepr_bool(self, mode="default"):
694 yield (astyle.style_type_bool, repr(self))
694 yield (astyle.style_type_bool, repr(self))
695 xrepr.when_type(bool)(xrepr_bool)
695 xrepr.when_type(bool)(xrepr_bool)
696
696
697
697
698 def xrepr_str(self, mode="default"):
698 def xrepr_str(self, mode="default"):
699 if mode == "cell":
699 if mode == "cell":
700 yield (astyle.style_default, repr(self.expandtabs(tab))[1:-1])
700 yield (astyle.style_default, repr(self.expandtabs(tab))[1:-1])
701 else:
701 else:
702 yield (astyle.style_default, repr(self))
702 yield (astyle.style_default, repr(self))
703 xrepr.when_type(str)(xrepr_str)
703 xrepr.when_type(str)(xrepr_str)
704
704
705
705
706 def xrepr_unicode(self, mode="default"):
706 def xrepr_unicode(self, mode="default"):
707 if mode == "cell":
707 if mode == "cell":
708 yield (astyle.style_default, repr(self.expandtabs(tab))[2:-1])
708 yield (astyle.style_default, repr(self.expandtabs(tab))[2:-1])
709 else:
709 else:
710 yield (astyle.style_default, repr(self))
710 yield (astyle.style_default, repr(self))
711 xrepr.when_type(unicode)(xrepr_unicode)
711 xrepr.when_type(unicode)(xrepr_unicode)
712
712
713
713
714 def xrepr_number(self, mode="default"):
714 def xrepr_number(self, mode="default"):
715 yield (1, True)
715 yield (1, True)
716 yield (astyle.style_type_number, repr(self))
716 yield (astyle.style_type_number, repr(self))
717 xrepr.when_type(int)(xrepr_number)
717 xrepr.when_type(int)(xrepr_number)
718 xrepr.when_type(long)(xrepr_number)
718 xrepr.when_type(long)(xrepr_number)
719 xrepr.when_type(float)(xrepr_number)
719 xrepr.when_type(float)(xrepr_number)
720
720
721
721
722 def xrepr_complex(self, mode="default"):
722 def xrepr_complex(self, mode="default"):
723 yield (astyle.style_type_number, repr(self))
723 yield (astyle.style_type_number, repr(self))
724 xrepr.when_type(complex)(xrepr_number)
724 xrepr.when_type(complex)(xrepr_number)
725
725
726
726
727 def xrepr_datetime(self, mode="default"):
727 def xrepr_datetime(self, mode="default"):
728 if mode == "cell":
728 if mode == "cell":
729 # Don't use strftime() here, as this requires year >= 1900
729 # Don't use strftime() here, as this requires year >= 1900
730 yield (astyle.style_type_datetime,
730 yield (astyle.style_type_datetime,
731 "%04d-%02d-%02d %02d:%02d:%02d.%06d" % \
731 "%04d-%02d-%02d %02d:%02d:%02d.%06d" % \
732 (self.year, self.month, self.day,
732 (self.year, self.month, self.day,
733 self.hour, self.minute, self.second,
733 self.hour, self.minute, self.second,
734 self.microsecond),
734 self.microsecond),
735 )
735 )
736 else:
736 else:
737 yield (astyle.style_type_datetime, repr(self))
737 yield (astyle.style_type_datetime, repr(self))
738 xrepr.when_type(datetime.datetime)(xrepr_datetime)
738 xrepr.when_type(datetime.datetime)(xrepr_datetime)
739
739
740
740
741 def xrepr_date(self, mode="default"):
741 def xrepr_date(self, mode="default"):
742 if mode == "cell":
742 if mode == "cell":
743 yield (astyle.style_type_datetime,
743 yield (astyle.style_type_datetime,
744 "%04d-%02d-%02d" % (self.year, self.month, self.day))
744 "%04d-%02d-%02d" % (self.year, self.month, self.day))
745 else:
745 else:
746 yield (astyle.style_type_datetime, repr(self))
746 yield (astyle.style_type_datetime, repr(self))
747 xrepr.when_type(datetime.date)(xrepr_date)
747 xrepr.when_type(datetime.date)(xrepr_date)
748
748
749
749
750 def xrepr_time(self, mode="default"):
750 def xrepr_time(self, mode="default"):
751 if mode == "cell":
751 if mode == "cell":
752 yield (astyle.style_type_datetime,
752 yield (astyle.style_type_datetime,
753 "%02d:%02d:%02d.%06d" % \
753 "%02d:%02d:%02d.%06d" % \
754 (self.hour, self.minute, self.second, self.microsecond))
754 (self.hour, self.minute, self.second, self.microsecond))
755 else:
755 else:
756 yield (astyle.style_type_datetime, repr(self))
756 yield (astyle.style_type_datetime, repr(self))
757 xrepr.when_type(datetime.time)(xrepr_time)
757 xrepr.when_type(datetime.time)(xrepr_time)
758
758
759
759
760 def xrepr_timedelta(self, mode="default"):
760 def xrepr_timedelta(self, mode="default"):
761 yield (astyle.style_type_datetime, repr(self))
761 yield (astyle.style_type_datetime, repr(self))
762 xrepr.when_type(datetime.timedelta)(xrepr_timedelta)
762 xrepr.when_type(datetime.timedelta)(xrepr_timedelta)
763
763
764
764
765 def xrepr_type(self, mode="default"):
765 def xrepr_type(self, mode="default"):
766 if self.__module__ == "__builtin__":
766 if self.__module__ == "__builtin__":
767 yield (astyle.style_type_type, self.__name__)
767 yield (astyle.style_type_type, self.__name__)
768 else:
768 else:
769 yield (astyle.style_type_type, "%s.%s" % (self.__module__, self.__name__))
769 yield (astyle.style_type_type, "%s.%s" % (self.__module__, self.__name__))
770 xrepr.when_type(type)(xrepr_type)
770 xrepr.when_type(type)(xrepr_type)
771
771
772
772
773 def xrepr_exception(self, mode="default"):
773 def xrepr_exception(self, mode="default"):
774 if self.__class__.__module__ == "exceptions":
774 if self.__class__.__module__ == "exceptions":
775 classname = self.__class__.__name__
775 classname = self.__class__.__name__
776 else:
776 else:
777 classname = "%s.%s" % \
777 classname = "%s.%s" % \
778 (self.__class__.__module__, self.__class__.__name__)
778 (self.__class__.__module__, self.__class__.__name__)
779 if mode == "header" or mode == "footer":
779 if mode == "header" or mode == "footer":
780 yield (astyle.style_error, "%s: %s" % (classname, self))
780 yield (astyle.style_error, "%s: %s" % (classname, self))
781 else:
781 else:
782 yield (astyle.style_error, classname)
782 yield (astyle.style_error, classname)
783 xrepr.when_type(Exception)(xrepr_exception)
783 xrepr.when_type(Exception)(xrepr_exception)
784
784
785
785
786 def xrepr_listtuple(self, mode="default"):
786 def xrepr_listtuple(self, mode="default"):
787 if mode == "header" or mode == "footer":
787 if mode == "header" or mode == "footer":
788 if self.__class__.__module__ == "__builtin__":
788 if self.__class__.__module__ == "__builtin__":
789 classname = self.__class__.__name__
789 classname = self.__class__.__name__
790 else:
790 else:
791 classname = "%s.%s" % \
791 classname = "%s.%s" % \
792 (self.__class__.__module__,self.__class__.__name__)
792 (self.__class__.__module__,self.__class__.__name__)
793 yield (astyle.style_default,
793 yield (astyle.style_default,
794 "<%s object with %d items at 0x%x>" % \
794 "<%s object with %d items at 0x%x>" % \
795 (classname, len(self), id(self)))
795 (classname, len(self), id(self)))
796 else:
796 else:
797 yield (-1, False)
797 yield (-1, False)
798 if isinstance(self, list):
798 if isinstance(self, list):
799 yield (astyle.style_default, "[")
799 yield (astyle.style_default, "[")
800 end = "]"
800 end = "]"
801 else:
801 else:
802 yield (astyle.style_default, "(")
802 yield (astyle.style_default, "(")
803 end = ")"
803 end = ")"
804 for (i, subself) in enumerate(self):
804 for (i, subself) in enumerate(self):
805 if i:
805 if i:
806 yield (astyle.style_default, ", ")
806 yield (astyle.style_default, ", ")
807 for part in xrepr(subself, "default"):
807 for part in xrepr(subself, "default"):
808 yield part
808 yield part
809 yield (astyle.style_default, end)
809 yield (astyle.style_default, end)
810 xrepr.when_type(list)(xrepr_listtuple)
810 xrepr.when_type(list)(xrepr_listtuple)
811 xrepr.when_type(tuple)(xrepr_listtuple)
811 xrepr.when_type(tuple)(xrepr_listtuple)
812
812
813
813
814 def xrepr_dict(self, mode="default"):
814 def xrepr_dict(self, mode="default"):
815 if mode == "header" or mode == "footer":
815 if mode == "header" or mode == "footer":
816 if self.__class__.__module__ == "__builtin__":
816 if self.__class__.__module__ == "__builtin__":
817 classname = self.__class__.__name__
817 classname = self.__class__.__name__
818 else:
818 else:
819 classname = "%s.%s" % \
819 classname = "%s.%s" % \
820 (self.__class__.__module__,self.__class__.__name__)
820 (self.__class__.__module__,self.__class__.__name__)
821 yield (astyle.style_default,
821 yield (astyle.style_default,
822 "<%s object with %d items at 0x%x>" % \
822 "<%s object with %d items at 0x%x>" % \
823 (classname, len(self), id(self)))
823 (classname, len(self), id(self)))
824 else:
824 else:
825 yield (-1, False)
825 yield (-1, False)
826 if isinstance(self, dict):
826 if isinstance(self, dict):
827 yield (astyle.style_default, "{")
827 yield (astyle.style_default, "{")
828 end = "}"
828 end = "}"
829 else:
829 else:
830 yield (astyle.style_default, "dictproxy((")
830 yield (astyle.style_default, "dictproxy((")
831 end = "})"
831 end = "})"
832 for (i, (key, value)) in enumerate(self.iteritems()):
832 for (i, (key, value)) in enumerate(self.iteritems()):
833 if i:
833 if i:
834 yield (astyle.style_default, ", ")
834 yield (astyle.style_default, ", ")
835 for part in xrepr(key, "default"):
835 for part in xrepr(key, "default"):
836 yield part
836 yield part
837 yield (astyle.style_default, ": ")
837 yield (astyle.style_default, ": ")
838 for part in xrepr(value, "default"):
838 for part in xrepr(value, "default"):
839 yield part
839 yield part
840 yield (astyle.style_default, end)
840 yield (astyle.style_default, end)
841 xrepr.when_type(dict)(xrepr_dict)
841 xrepr.when_type(dict)(xrepr_dict)
842 xrepr.when_type(types.DictProxyType)(xrepr_dict)
842 xrepr.when_type(types.DictProxyType)(xrepr_dict)
843
843
844
844
845 def upgradexattr(attr):
845 def upgradexattr(attr):
846 """
846 """
847 Convert an attribute descriptor string to a real descriptor object.
847 Convert an attribute descriptor string to a real descriptor object.
848
848
849 If attr already is a descriptor object return it unmodified. A
849 If attr already is a descriptor object return it unmodified. A
850 ``SelfDescriptor`` will be returned if ``attr`` is ``None``. ``"foo"``
850 ``SelfDescriptor`` will be returned if ``attr`` is ``None``. ``"foo"``
851 returns an ``AttributeDescriptor`` for the attribute named ``"foo"``.
851 returns an ``AttributeDescriptor`` for the attribute named ``"foo"``.
852 ``"foo()"`` returns a ``MethodDescriptor`` for the method named ``"foo"``.
852 ``"foo()"`` returns a ``MethodDescriptor`` for the method named ``"foo"``.
853 ``"-foo"`` will return an ``IterAttributeDescriptor`` for the attribute
853 ``"-foo"`` will return an ``IterAttributeDescriptor`` for the attribute
854 named ``"foo"`` and ``"-foo()"`` will return an ``IterMethodDescriptor``
854 named ``"foo"`` and ``"-foo()"`` will return an ``IterMethodDescriptor``
855 for the method named ``"foo"``. Furthermore integers will return the appropriate
855 for the method named ``"foo"``. Furthermore integers will return the appropriate
856 ``IndexDescriptor`` and callables will return a ``FunctionDescriptor``.
856 ``IndexDescriptor`` and callables will return a ``FunctionDescriptor``.
857 """
857 """
858 if attr is None:
858 if attr is None:
859 return selfdescriptor
859 return selfdescriptor
860 elif isinstance(attr, Descriptor):
860 elif isinstance(attr, Descriptor):
861 return attr
861 return attr
862 elif isinstance(attr, basestring):
862 elif isinstance(attr, basestring):
863 if attr.endswith("()"):
863 if attr.endswith("()"):
864 if attr.startswith("-"):
864 if attr.startswith("-"):
865 return IterMethodDescriptor(attr[1:-2])
865 return IterMethodDescriptor(attr[1:-2])
866 else:
866 else:
867 return MethodDescriptor(attr[:-2])
867 return MethodDescriptor(attr[:-2])
868 else:
868 else:
869 if attr.startswith("-"):
869 if attr.startswith("-"):
870 return IterAttributeDescriptor(attr[1:])
870 return IterAttributeDescriptor(attr[1:])
871 else:
871 else:
872 return AttributeDescriptor(attr)
872 return AttributeDescriptor(attr)
873 elif isinstance(attr, (int, long)):
873 elif isinstance(attr, (int, long)):
874 return IndexDescriptor(attr)
874 return IndexDescriptor(attr)
875 elif callable(attr):
875 elif callable(attr):
876 return FunctionDescriptor(attr)
876 return FunctionDescriptor(attr)
877 else:
877 else:
878 raise TypeError("can't handle descriptor %r" % attr)
878 raise TypeError("can't handle descriptor %r" % attr)
879
879
880
880
881 def xattrs(item, mode="default"):
881 def xattrs(item, mode="default"):
882 """
882 """
883 Generic function that returns an iterable of attribute descriptors
883 Generic function that returns an iterable of attribute descriptors
884 to be used for displaying the attributes ob the object ``item`` in display
884 to be used for displaying the attributes ob the object ``item`` in display
885 mode ``mode``.
885 mode ``mode``.
886
886
887 There are two possible modes:
887 There are two possible modes:
888
888
889 ``"detail"``
889 ``"detail"``
890 The ``Display`` object wants to display a detailed list of the object
890 The ``Display`` object wants to display a detailed list of the object
891 attributes.
891 attributes.
892
892
893 ``"default"``
893 ``"default"``
894 The ``Display`` object wants to display the object in a list view.
894 The ``Display`` object wants to display the object in a list view.
895
895
896 If no implementation is registered for the object ``item`` ``xattrs`` falls
896 If no implementation is registered for the object ``item`` ``xattrs`` falls
897 back to trying the ``__xattrs__`` method of the object. If this doesn't
897 back to trying the ``__xattrs__`` method of the object. If this doesn't
898 exist either, ``dir(item)`` is used for ``"detail"`` mode and ``(None,)``
898 exist either, ``dir(item)`` is used for ``"detail"`` mode and ``(None,)``
899 for ``"default"`` mode.
899 for ``"default"`` mode.
900
900
901 The implementation must yield attribute descriptors (see the class
901 The implementation must yield attribute descriptors (see the class
902 ``Descriptor`` for more info). The ``__xattrs__`` method may also return
902 ``Descriptor`` for more info). The ``__xattrs__`` method may also return
903 attribute descriptor strings (and ``None``) which will be converted to real
903 attribute descriptor strings (and ``None``) which will be converted to real
904 descriptors by ``upgradexattr()``.
904 descriptors by ``upgradexattr()``.
905 """
905 """
906 try:
906 try:
907 func = item.__xattrs__
907 func = item.__xattrs__
908 except AttributeError:
908 except AttributeError:
909 if mode == "detail":
909 if mode == "detail":
910 for attrname in dir(item):
910 for attrname in dir(item):
911 yield AttributeDescriptor(attrname)
911 yield AttributeDescriptor(attrname)
912 else:
912 else:
913 yield selfdescriptor
913 yield selfdescriptor
914 else:
914 else:
915 for attr in func(mode):
915 for attr in func(mode):
916 yield upgradexattr(attr)
916 yield upgradexattr(attr)
917 xattrs = simplegeneric.generic(xattrs)
917 xattrs = simplegeneric.generic(xattrs)
918
918
919
919
920 def xattrs_complex(self, mode="default"):
920 def xattrs_complex(self, mode="default"):
921 if mode == "detail":
921 if mode == "detail":
922 return (AttributeDescriptor("real"), AttributeDescriptor("imag"))
922 return (AttributeDescriptor("real"), AttributeDescriptor("imag"))
923 return (selfdescriptor,)
923 return (selfdescriptor,)
924 xattrs.when_type(complex)(xattrs_complex)
924 xattrs.when_type(complex)(xattrs_complex)
925
925
926
926
927 def _isdict(item):
927 def _isdict(item):
928 try:
928 try:
929 itermeth = item.__class__.__iter__
929 itermeth = item.__class__.__iter__
930 except (AttributeError, TypeError):
930 except (AttributeError, TypeError):
931 return False
931 return False
932 return itermeth is dict.__iter__ or itermeth is types.DictProxyType.__iter__
932 return itermeth is dict.__iter__ or itermeth is types.DictProxyType.__iter__
933
933
934
934
935 def _isstr(item):
935 def _isstr(item):
936 if not isinstance(item, basestring):
936 if not isinstance(item, basestring):
937 return False
937 return False
938 try:
938 try:
939 itermeth = item.__class__.__iter__
939 itermeth = item.__class__.__iter__
940 except AttributeError:
940 except AttributeError:
941 return True
941 return True
942 return False # ``__iter__`` has been redefined
942 return False # ``__iter__`` has been redefined
943
943
944
944
945 def xiter(item):
945 def xiter(item):
946 """
946 """
947 Generic function that implements iteration for pipeline expression. If no
947 Generic function that implements iteration for pipeline expression. If no
948 implementation is registered for ``item`` ``xiter`` falls back to ``iter``.
948 implementation is registered for ``item`` ``xiter`` falls back to ``iter``.
949 """
949 """
950 try:
950 try:
951 func = item.__xiter__
951 func = item.__xiter__
952 except AttributeError:
952 except AttributeError:
953 if _isdict(item):
953 if _isdict(item):
954 def items(item):
954 def items(item):
955 fields = ("key", "value")
955 fields = ("key", "value")
956 for (key, value) in item.iteritems():
956 for (key, value) in item.iteritems():
957 yield Fields(fields, key=key, value=value)
957 yield Fields(fields, key=key, value=value)
958 return items(item)
958 return items(item)
959 elif isinstance(item, new.module):
959 elif isinstance(item, new.module):
960 def items(item):
960 def items(item):
961 fields = ("key", "value")
961 fields = ("key", "value")
962 for key in sorted(item.__dict__):
962 for key in sorted(item.__dict__):
963 yield Fields(fields, key=key, value=getattr(item, key))
963 yield Fields(fields, key=key, value=getattr(item, key))
964 return items(item)
964 return items(item)
965 elif _isstr(item):
965 elif _isstr(item):
966 if not item:
966 if not item:
967 raise ValueError("can't enter empty string")
967 raise ValueError("can't enter empty string")
968 lines = item.splitlines()
968 lines = item.splitlines()
969 if len(lines) == 1:
969 if len(lines) == 1:
970 def iterone(item):
970 def iterone(item):
971 yield item
971 yield item
972 return iterone(item)
972 return iterone(item)
973 else:
973 else:
974 return iter(lines)
974 return iter(lines)
975 return iter(item)
975 return iter(item)
976 else:
976 else:
977 return iter(func()) # iter() just to be safe
977 return iter(func()) # iter() just to be safe
978 xiter = simplegeneric.generic(xiter)
978 xiter = simplegeneric.generic(xiter)
979
979
980
980
981 class ichain(Pipe):
981 class ichain(Pipe):
982 """
982 """
983 Chains multiple ``Table``s into one.
983 Chains multiple ``Table``s into one.
984 """
984 """
985
985
986 def __init__(self, *iters):
986 def __init__(self, *iters):
987 self.iters = iters
987 self.iters = iters
988
988
989 def __iter__(self):
989 def __iter__(self):
990 return itertools.chain(*self.iters)
990 return itertools.chain(*self.iters)
991
991
992 def __xrepr__(self, mode="default"):
992 def __xrepr__(self, mode="default"):
993 if mode == "header" or mode == "footer":
993 if mode == "header" or mode == "footer":
994 for (i, item) in enumerate(self.iters):
994 for (i, item) in enumerate(self.iters):
995 if i:
995 if i:
996 yield (astyle.style_default, "+")
996 yield (astyle.style_default, "+")
997 if isinstance(item, Pipe):
997 if isinstance(item, Pipe):
998 yield (astyle.style_default, "(")
998 yield (astyle.style_default, "(")
999 for part in xrepr(item, mode):
999 for part in xrepr(item, mode):
1000 yield part
1000 yield part
1001 if isinstance(item, Pipe):
1001 if isinstance(item, Pipe):
1002 yield (astyle.style_default, ")")
1002 yield (astyle.style_default, ")")
1003 else:
1003 else:
1004 yield (astyle.style_default, repr(self))
1004 yield (astyle.style_default, repr(self))
1005
1005
1006 def __repr__(self):
1006 def __repr__(self):
1007 args = ", ".join([repr(it) for it in self.iters])
1007 args = ", ".join([repr(it) for it in self.iters])
1008 return "%s.%s(%s)" % \
1008 return "%s.%s(%s)" % \
1009 (self.__class__.__module__, self.__class__.__name__, args)
1009 (self.__class__.__module__, self.__class__.__name__, args)
1010
1010
1011
1011
1012 class ifile(path.path):
1012 class ifile(path.path):
1013 """
1013 """
1014 file (or directory) object.
1014 file (or directory) object.
1015 """
1015 """
1016
1016
1017 def getmode(self):
1017 def getmode(self):
1018 return self.stat().st_mode
1018 return self.stat().st_mode
1019 mode = property(getmode, None, None, "Access mode")
1019 mode = property(getmode, None, None, "Access mode")
1020
1020
1021 def gettype(self):
1021 def gettype(self):
1022 data = [
1022 data = [
1023 (stat.S_ISREG, "file"),
1023 (stat.S_ISREG, "file"),
1024 (stat.S_ISDIR, "dir"),
1024 (stat.S_ISDIR, "dir"),
1025 (stat.S_ISCHR, "chardev"),
1025 (stat.S_ISCHR, "chardev"),
1026 (stat.S_ISBLK, "blockdev"),
1026 (stat.S_ISBLK, "blockdev"),
1027 (stat.S_ISFIFO, "fifo"),
1027 (stat.S_ISFIFO, "fifo"),
1028 (stat.S_ISLNK, "symlink"),
1028 (stat.S_ISLNK, "symlink"),
1029 (stat.S_ISSOCK,"socket"),
1029 (stat.S_ISSOCK,"socket"),
1030 ]
1030 ]
1031 lstat = self.lstat()
1031 lstat = self.lstat()
1032 if lstat is not None:
1032 if lstat is not None:
1033 types = set([text for (func, text) in data if func(lstat.st_mode)])
1033 types = set([text for (func, text) in data if func(lstat.st_mode)])
1034 else:
1034 else:
1035 types = set()
1035 types = set()
1036 m = self.mode
1036 m = self.mode
1037 types.update([text for (func, text) in data if func(m)])
1037 types.update([text for (func, text) in data if func(m)])
1038 return ", ".join(types)
1038 return ", ".join(types)
1039 type = property(gettype, None, None, "file type (file, directory, link, etc.)")
1039 type = property(gettype, None, None, "file type (file, directory, link, etc.)")
1040
1040
1041 def getmodestr(self):
1041 def getmodestr(self):
1042 m = self.mode
1042 m = self.mode
1043 data = [
1043 data = [
1044 (stat.S_IRUSR, "-r"),
1044 (stat.S_IRUSR, "-r"),
1045 (stat.S_IWUSR, "-w"),
1045 (stat.S_IWUSR, "-w"),
1046 (stat.S_IXUSR, "-x"),
1046 (stat.S_IXUSR, "-x"),
1047 (stat.S_IRGRP, "-r"),
1047 (stat.S_IRGRP, "-r"),
1048 (stat.S_IWGRP, "-w"),
1048 (stat.S_IWGRP, "-w"),
1049 (stat.S_IXGRP, "-x"),
1049 (stat.S_IXGRP, "-x"),
1050 (stat.S_IROTH, "-r"),
1050 (stat.S_IROTH, "-r"),
1051 (stat.S_IWOTH, "-w"),
1051 (stat.S_IWOTH, "-w"),
1052 (stat.S_IXOTH, "-x"),
1052 (stat.S_IXOTH, "-x"),
1053 ]
1053 ]
1054 return "".join([text[bool(m&bit)] for (bit, text) in data])
1054 return "".join([text[bool(m&bit)] for (bit, text) in data])
1055
1055
1056 modestr = property(getmodestr, None, None, "Access mode as string")
1056 modestr = property(getmodestr, None, None, "Access mode as string")
1057
1057
1058 def getblocks(self):
1058 def getblocks(self):
1059 return self.stat().st_blocks
1059 return self.stat().st_blocks
1060 blocks = property(getblocks, None, None, "File size in blocks")
1060 blocks = property(getblocks, None, None, "File size in blocks")
1061
1061
1062 def getblksize(self):
1062 def getblksize(self):
1063 return self.stat().st_blksize
1063 return self.stat().st_blksize
1064 blksize = property(getblksize, None, None, "Filesystem block size")
1064 blksize = property(getblksize, None, None, "Filesystem block size")
1065
1065
1066 def getdev(self):
1066 def getdev(self):
1067 return self.stat().st_dev
1067 return self.stat().st_dev
1068 dev = property(getdev)
1068 dev = property(getdev)
1069
1069
1070 def getnlink(self):
1070 def getnlink(self):
1071 return self.stat().st_nlink
1071 return self.stat().st_nlink
1072 nlink = property(getnlink, None, None, "Number of links")
1072 nlink = property(getnlink, None, None, "Number of links")
1073
1073
1074 def getuid(self):
1074 def getuid(self):
1075 return self.stat().st_uid
1075 return self.stat().st_uid
1076 uid = property(getuid, None, None, "User id of file owner")
1076 uid = property(getuid, None, None, "User id of file owner")
1077
1077
1078 def getgid(self):
1078 def getgid(self):
1079 return self.stat().st_gid
1079 return self.stat().st_gid
1080 gid = property(getgid, None, None, "Group id of file owner")
1080 gid = property(getgid, None, None, "Group id of file owner")
1081
1081
1082 def getowner(self):
1082 def getowner(self):
1083 stat = self.stat()
1083 stat = self.stat()
1084 try:
1084 try:
1085 return pwd.getpwuid(stat.st_uid).pw_name
1085 return pwd.getpwuid(stat.st_uid).pw_name
1086 except KeyError:
1086 except KeyError:
1087 return stat.st_uid
1087 return stat.st_uid
1088 owner = property(getowner, None, None, "Owner name (or id)")
1088 owner = property(getowner, None, None, "Owner name (or id)")
1089
1089
1090 def getgroup(self):
1090 def getgroup(self):
1091 stat = self.stat()
1091 stat = self.stat()
1092 try:
1092 try:
1093 return grp.getgrgid(stat.st_gid).gr_name
1093 return grp.getgrgid(stat.st_gid).gr_name
1094 except KeyError:
1094 except KeyError:
1095 return stat.st_gid
1095 return stat.st_gid
1096 group = property(getgroup, None, None, "Group name (or id)")
1096 group = property(getgroup, None, None, "Group name (or id)")
1097
1097
1098 def getadate(self):
1098 def getadate(self):
1099 return datetime.datetime.utcfromtimestamp(self.atime)
1099 return datetime.datetime.utcfromtimestamp(self.atime)
1100 adate = property(getadate, None, None, "Access date")
1100 adate = property(getadate, None, None, "Access date")
1101
1101
1102 def getcdate(self):
1102 def getcdate(self):
1103 return datetime.datetime.utcfromtimestamp(self.ctime)
1103 return datetime.datetime.utcfromtimestamp(self.ctime)
1104 cdate = property(getcdate, None, None, "Creation date")
1104 cdate = property(getcdate, None, None, "Creation date")
1105
1105
1106 def getmdate(self):
1106 def getmdate(self):
1107 return datetime.datetime.utcfromtimestamp(self.mtime)
1107 return datetime.datetime.utcfromtimestamp(self.mtime)
1108 mdate = property(getmdate, None, None, "Modification date")
1108 mdate = property(getmdate, None, None, "Modification date")
1109
1109
1110 def mimetype(self):
1110 def mimetype(self):
1111 """
1111 """
1112 Return MIME type guessed from the extension.
1112 Return MIME type guessed from the extension.
1113 """
1113 """
1114 return mimetypes.guess_type(self.basename())[0]
1114 return mimetypes.guess_type(self.basename())[0]
1115
1115
1116 def encoding(self):
1116 def encoding(self):
1117 """
1117 """
1118 Return guessed compression (like "compress" or "gzip").
1118 Return guessed compression (like "compress" or "gzip").
1119 """
1119 """
1120 return mimetypes.guess_type(self.basename())[1]
1120 return mimetypes.guess_type(self.basename())[1]
1121
1121
1122 def __repr__(self):
1122 def __repr__(self):
1123 return "ifile(%s)" % path._base.__repr__(self)
1123 return "ifile(%s)" % path._base.__repr__(self)
1124
1124
1125 if sys.platform == "win32":
1125 if sys.platform == "win32":
1126 defaultattrs = (None, "type", "size", "modestr", "mdate")
1126 defaultattrs = (None, "type", "size", "modestr", "mdate")
1127 else:
1127 else:
1128 defaultattrs = (None, "type", "size", "modestr", "owner", "group", "mdate")
1128 defaultattrs = (None, "type", "size", "modestr", "owner", "group", "mdate")
1129
1129
1130 def __xattrs__(self, mode="default"):
1130 def __xattrs__(self, mode="default"):
1131 if mode == "detail":
1131 if mode == "detail":
1132 return (
1132 return (
1133 "name",
1133 "name",
1134 "basename()",
1134 "basename()",
1135 "abspath()",
1135 "abspath()",
1136 "realpath()",
1136 "realpath()",
1137 "type",
1137 "type",
1138 "mode",
1138 "mode",
1139 "modestr",
1139 "modestr",
1140 "stat()",
1140 "stat()",
1141 "lstat()",
1141 "lstat()",
1142 "uid",
1142 "uid",
1143 "gid",
1143 "gid",
1144 "owner",
1144 "owner",
1145 "group",
1145 "group",
1146 "dev",
1146 "dev",
1147 "nlink",
1147 "nlink",
1148 "ctime",
1148 "ctime",
1149 "mtime",
1149 "mtime",
1150 "atime",
1150 "atime",
1151 "cdate",
1151 "cdate",
1152 "mdate",
1152 "mdate",
1153 "adate",
1153 "adate",
1154 "size",
1154 "size",
1155 "blocks",
1155 "blocks",
1156 "blksize",
1156 "blksize",
1157 "isdir()",
1157 "isdir()",
1158 "islink()",
1158 "islink()",
1159 "mimetype()",
1159 "mimetype()",
1160 "encoding()",
1160 "encoding()",
1161 "-listdir()",
1161 "-listdir()",
1162 "-dirs()",
1162 "-dirs()",
1163 "-files()",
1163 "-files()",
1164 "-walk()",
1164 "-walk()",
1165 "-walkdirs()",
1165 "-walkdirs()",
1166 "-walkfiles()",
1166 "-walkfiles()",
1167 )
1167 )
1168 else:
1168 else:
1169 return self.defaultattrs
1169 return self.defaultattrs
1170
1170
1171
1171
1172 def xiter_ifile(self):
1172 def xiter_ifile(self):
1173 if self.isdir():
1173 if self.isdir():
1174 yield (self / os.pardir).abspath()
1174 yield (self / os.pardir).abspath()
1175 for child in sorted(self.listdir()):
1175 for child in sorted(self.listdir()):
1176 yield child
1176 yield child
1177 else:
1177 else:
1178 f = self.open("rb")
1178 f = self.open("rb")
1179 for line in f:
1179 for line in f:
1180 yield line
1180 yield line
1181 f.close()
1181 f.close()
1182 xiter.when_type(ifile)(xiter_ifile)
1182 xiter.when_type(ifile)(xiter_ifile)
1183
1183
1184
1184
1185 # We need to implement ``xrepr`` for ``ifile`` as a generic function, because
1185 # We need to implement ``xrepr`` for ``ifile`` as a generic function, because
1186 # otherwise ``xrepr_str`` would kick in.
1186 # otherwise ``xrepr_str`` would kick in.
1187 def xrepr_ifile(self, mode="default"):
1187 def xrepr_ifile(self, mode="default"):
1188 try:
1188 try:
1189 if self.isdir():
1189 if self.isdir():
1190 name = "idir"
1190 name = "idir"
1191 style = astyle.style_dir
1191 style = astyle.style_dir
1192 else:
1192 else:
1193 name = "ifile"
1193 name = "ifile"
1194 style = astyle.style_file
1194 style = astyle.style_file
1195 except IOError:
1195 except IOError:
1196 name = "ifile"
1196 name = "ifile"
1197 style = astyle.style_default
1197 style = astyle.style_default
1198 if mode in ("cell", "header", "footer"):
1198 if mode in ("cell", "header", "footer"):
1199 abspath = repr(path._base(self.normpath()))
1199 abspath = repr(path._base(self.normpath()))
1200 if abspath.startswith("u"):
1200 if abspath.startswith("u"):
1201 abspath = abspath[2:-1]
1201 abspath = abspath[2:-1]
1202 else:
1202 else:
1203 abspath = abspath[1:-1]
1203 abspath = abspath[1:-1]
1204 if mode == "cell":
1204 if mode == "cell":
1205 yield (style, abspath)
1205 yield (style, abspath)
1206 else:
1206 else:
1207 yield (style, "%s(%s)" % (name, abspath))
1207 yield (style, "%s(%s)" % (name, abspath))
1208 else:
1208 else:
1209 yield (style, repr(self))
1209 yield (style, repr(self))
1210 xrepr.when_type(ifile)(xrepr_ifile)
1210 xrepr.when_type(ifile)(xrepr_ifile)
1211
1211
1212
1212
1213 class ils(Table):
1213 class ils(Table):
1214 """
1214 """
1215 List the current (or a specified) directory.
1215 List the current (or a specified) directory.
1216
1216
1217 Examples::
1217 Examples::
1218
1218
1219 >>> ils
1219 >>> ils
1220 <class 'IPython.extensions.ipipe.ils'>
1220 <class 'IPython.extensions.ipipe.ils'>
1221 >>> ils("/usr/local/lib/python2.4")
1221 >>> ils("/usr/local/lib/python2.4")
1222 IPython.extensions.ipipe.ils('/usr/local/lib/python2.4')
1222 IPython.extensions.ipipe.ils('/usr/local/lib/python2.4')
1223 >>> ils("~")
1223 >>> ils("~")
1224 IPython.extensions.ipipe.ils('/home/fperez')
1224 IPython.extensions.ipipe.ils('/home/fperez')
1225 # all-random
1225 # all-random
1226 """
1226 """
1227 def __init__(self, base=os.curdir, dirs=True, files=True):
1227 def __init__(self, base=os.curdir, dirs=True, files=True):
1228 self.base = os.path.expanduser(base)
1228 self.base = os.path.expanduser(base)
1229 self.dirs = dirs
1229 self.dirs = dirs
1230 self.files = files
1230 self.files = files
1231
1231
1232 def __iter__(self):
1232 def __iter__(self):
1233 base = ifile(self.base)
1233 base = ifile(self.base)
1234 yield (base / os.pardir).abspath()
1234 yield (base / os.pardir).abspath()
1235 for child in sorted(base.listdir()):
1235 for child in sorted(base.listdir()):
1236 if self.dirs:
1236 if self.dirs:
1237 if self.files:
1237 if self.files:
1238 yield child
1238 yield child
1239 else:
1239 else:
1240 if child.isdir():
1240 if child.isdir():
1241 yield child
1241 yield child
1242 elif self.files:
1242 elif self.files:
1243 if not child.isdir():
1243 if not child.isdir():
1244 yield child
1244 yield child
1245
1245
1246 def __xrepr__(self, mode="default"):
1246 def __xrepr__(self, mode="default"):
1247 return xrepr(ifile(self.base), mode)
1247 return xrepr(ifile(self.base), mode)
1248
1248
1249 def __repr__(self):
1249 def __repr__(self):
1250 return "%s.%s(%r)" % \
1250 return "%s.%s(%r)" % \
1251 (self.__class__.__module__, self.__class__.__name__, self.base)
1251 (self.__class__.__module__, self.__class__.__name__, self.base)
1252
1252
1253
1253
1254 class iglob(Table):
1254 class iglob(Table):
1255 """
1255 """
1256 List all files and directories matching a specified pattern.
1256 List all files and directories matching a specified pattern.
1257 (See ``glob.glob()`` for more info.).
1257 (See ``glob.glob()`` for more info.).
1258
1258
1259 Examples::
1259 Examples::
1260
1260
1261 >>> iglob("*.py")
1261 >>> iglob("*.py")
1262 IPython.extensions.ipipe.iglob('*.py')
1262 IPython.extensions.ipipe.iglob('*.py')
1263 """
1263 """
1264 def __init__(self, glob):
1264 def __init__(self, glob):
1265 self.glob = glob
1265 self.glob = glob
1266
1266
1267 def __iter__(self):
1267 def __iter__(self):
1268 for name in glob.glob(self.glob):
1268 for name in glob.glob(self.glob):
1269 yield ifile(name)
1269 yield ifile(name)
1270
1270
1271 def __xrepr__(self, mode="default"):
1271 def __xrepr__(self, mode="default"):
1272 if mode == "header" or mode == "footer" or mode == "cell":
1272 if mode == "header" or mode == "footer" or mode == "cell":
1273 yield (astyle.style_default,
1273 yield (astyle.style_default,
1274 "%s(%r)" % (self.__class__.__name__, self.glob))
1274 "%s(%r)" % (self.__class__.__name__, self.glob))
1275 else:
1275 else:
1276 yield (astyle.style_default, repr(self))
1276 yield (astyle.style_default, repr(self))
1277
1277
1278 def __repr__(self):
1278 def __repr__(self):
1279 return "%s.%s(%r)" % \
1279 return "%s.%s(%r)" % \
1280 (self.__class__.__module__, self.__class__.__name__, self.glob)
1280 (self.__class__.__module__, self.__class__.__name__, self.glob)
1281
1281
1282
1282
1283 class iwalk(Table):
1283 class iwalk(Table):
1284 """
1284 """
1285 List all files and directories in a directory and it's subdirectory::
1285 List all files and directories in a directory and it's subdirectory::
1286
1286
1287 >>> iwalk
1287 >>> iwalk
1288 <class 'IPython.extensions.ipipe.iwalk'>
1288 <class 'IPython.extensions.ipipe.iwalk'>
1289 >>> iwalk("/usr/lib")
1289 >>> iwalk("/usr/lib")
1290 IPython.extensions.ipipe.iwalk('/usr/lib')
1290 IPython.extensions.ipipe.iwalk('/usr/lib')
1291 >>> iwalk("~")
1291 >>> iwalk("~")
1292 IPython.extensions.ipipe.iwalk('/home/fperez') # random
1292 IPython.extensions.ipipe.iwalk('/home/fperez') # random
1293
1293
1294 """
1294 """
1295 def __init__(self, base=os.curdir, dirs=True, files=True):
1295 def __init__(self, base=os.curdir, dirs=True, files=True):
1296 self.base = os.path.expanduser(base)
1296 self.base = os.path.expanduser(base)
1297 self.dirs = dirs
1297 self.dirs = dirs
1298 self.files = files
1298 self.files = files
1299
1299
1300 def __iter__(self):
1300 def __iter__(self):
1301 for (dirpath, dirnames, filenames) in os.walk(self.base):
1301 for (dirpath, dirnames, filenames) in os.walk(self.base):
1302 if self.dirs:
1302 if self.dirs:
1303 for name in sorted(dirnames):
1303 for name in sorted(dirnames):
1304 yield ifile(os.path.join(dirpath, name))
1304 yield ifile(os.path.join(dirpath, name))
1305 if self.files:
1305 if self.files:
1306 for name in sorted(filenames):
1306 for name in sorted(filenames):
1307 yield ifile(os.path.join(dirpath, name))
1307 yield ifile(os.path.join(dirpath, name))
1308
1308
1309 def __xrepr__(self, mode="default"):
1309 def __xrepr__(self, mode="default"):
1310 if mode == "header" or mode == "footer" or mode == "cell":
1310 if mode == "header" or mode == "footer" or mode == "cell":
1311 yield (astyle.style_default,
1311 yield (astyle.style_default,
1312 "%s(%r)" % (self.__class__.__name__, self.base))
1312 "%s(%r)" % (self.__class__.__name__, self.base))
1313 else:
1313 else:
1314 yield (astyle.style_default, repr(self))
1314 yield (astyle.style_default, repr(self))
1315
1315
1316 def __repr__(self):
1316 def __repr__(self):
1317 return "%s.%s(%r)" % \
1317 return "%s.%s(%r)" % \
1318 (self.__class__.__module__, self.__class__.__name__, self.base)
1318 (self.__class__.__module__, self.__class__.__name__, self.base)
1319
1319
1320
1320
1321 class ipwdentry(object):
1321 class ipwdentry(object):
1322 """
1322 """
1323 ``ipwdentry`` objects encapsulate entries in the Unix user account and
1323 ``ipwdentry`` objects encapsulate entries in the Unix user account and
1324 password database.
1324 password database.
1325 """
1325 """
1326 def __init__(self, id):
1326 def __init__(self, id):
1327 self._id = id
1327 self._id = id
1328 self._entry = None
1328 self._entry = None
1329
1329
1330 def __eq__(self, other):
1330 def __eq__(self, other):
1331 return self.__class__ is other.__class__ and self._id == other._id
1331 return self.__class__ is other.__class__ and self._id == other._id
1332
1332
1333 def __ne__(self, other):
1333 def __ne__(self, other):
1334 return self.__class__ is not other.__class__ or self._id != other._id
1334 return self.__class__ is not other.__class__ or self._id != other._id
1335
1335
1336 def _getentry(self):
1336 def _getentry(self):
1337 if self._entry is None:
1337 if self._entry is None:
1338 if isinstance(self._id, basestring):
1338 if isinstance(self._id, basestring):
1339 self._entry = pwd.getpwnam(self._id)
1339 self._entry = pwd.getpwnam(self._id)
1340 else:
1340 else:
1341 self._entry = pwd.getpwuid(self._id)
1341 self._entry = pwd.getpwuid(self._id)
1342 return self._entry
1342 return self._entry
1343
1343
1344 def getname(self):
1344 def getname(self):
1345 if isinstance(self._id, basestring):
1345 if isinstance(self._id, basestring):
1346 return self._id
1346 return self._id
1347 else:
1347 else:
1348 return self._getentry().pw_name
1348 return self._getentry().pw_name
1349 name = property(getname, None, None, "User name")
1349 name = property(getname, None, None, "User name")
1350
1350
1351 def getpasswd(self):
1351 def getpasswd(self):
1352 return self._getentry().pw_passwd
1352 return self._getentry().pw_passwd
1353 passwd = property(getpasswd, None, None, "Password")
1353 passwd = property(getpasswd, None, None, "Password")
1354
1354
1355 def getuid(self):
1355 def getuid(self):
1356 if isinstance(self._id, basestring):
1356 if isinstance(self._id, basestring):
1357 return self._getentry().pw_uid
1357 return self._getentry().pw_uid
1358 else:
1358 else:
1359 return self._id
1359 return self._id
1360 uid = property(getuid, None, None, "User id")
1360 uid = property(getuid, None, None, "User id")
1361
1361
1362 def getgid(self):
1362 def getgid(self):
1363 return self._getentry().pw_gid
1363 return self._getentry().pw_gid
1364 gid = property(getgid, None, None, "Primary group id")
1364 gid = property(getgid, None, None, "Primary group id")
1365
1365
1366 def getgroup(self):
1366 def getgroup(self):
1367 return igrpentry(self.gid)
1367 return igrpentry(self.gid)
1368 group = property(getgroup, None, None, "Group")
1368 group = property(getgroup, None, None, "Group")
1369
1369
1370 def getgecos(self):
1370 def getgecos(self):
1371 return self._getentry().pw_gecos
1371 return self._getentry().pw_gecos
1372 gecos = property(getgecos, None, None, "Information (e.g. full user name)")
1372 gecos = property(getgecos, None, None, "Information (e.g. full user name)")
1373
1373
1374 def getdir(self):
1374 def getdir(self):
1375 return self._getentry().pw_dir
1375 return self._getentry().pw_dir
1376 dir = property(getdir, None, None, "$HOME directory")
1376 dir = property(getdir, None, None, "$HOME directory")
1377
1377
1378 def getshell(self):
1378 def getshell(self):
1379 return self._getentry().pw_shell
1379 return self._getentry().pw_shell
1380 shell = property(getshell, None, None, "Login shell")
1380 shell = property(getshell, None, None, "Login shell")
1381
1381
1382 def __xattrs__(self, mode="default"):
1382 def __xattrs__(self, mode="default"):
1383 return ("name", "passwd", "uid", "gid", "gecos", "dir", "shell")
1383 return ("name", "passwd", "uid", "gid", "gecos", "dir", "shell")
1384
1384
1385 def __repr__(self):
1385 def __repr__(self):
1386 return "%s.%s(%r)" % \
1386 return "%s.%s(%r)" % \
1387 (self.__class__.__module__, self.__class__.__name__, self._id)
1387 (self.__class__.__module__, self.__class__.__name__, self._id)
1388
1388
1389
1389
1390 class ipwd(Table):
1390 class ipwd(Table):
1391 """
1391 """
1392 List all entries in the Unix user account and password database.
1392 List all entries in the Unix user account and password database.
1393
1393
1394 Example::
1394 Example::
1395
1395
1396 >>> ipwd | isort("uid")
1396 >>> ipwd | isort("uid")
1397 <IPython.extensions.ipipe.isort key='uid' reverse=False at 0x849efec>
1397 <IPython.extensions.ipipe.isort key='uid' reverse=False at 0x849efec>
1398 # random
1398 # random
1399 """
1399 """
1400 def __iter__(self):
1400 def __iter__(self):
1401 for entry in pwd.getpwall():
1401 for entry in pwd.getpwall():
1402 yield ipwdentry(entry.pw_name)
1402 yield ipwdentry(entry.pw_name)
1403
1403
1404 def __xrepr__(self, mode="default"):
1404 def __xrepr__(self, mode="default"):
1405 if mode == "header" or mode == "footer" or mode == "cell":
1405 if mode == "header" or mode == "footer" or mode == "cell":
1406 yield (astyle.style_default, "%s()" % self.__class__.__name__)
1406 yield (astyle.style_default, "%s()" % self.__class__.__name__)
1407 else:
1407 else:
1408 yield (astyle.style_default, repr(self))
1408 yield (astyle.style_default, repr(self))
1409
1409
1410
1410
1411 class igrpentry(object):
1411 class igrpentry(object):
1412 """
1412 """
1413 ``igrpentry`` objects encapsulate entries in the Unix group database.
1413 ``igrpentry`` objects encapsulate entries in the Unix group database.
1414 """
1414 """
1415 def __init__(self, id):
1415 def __init__(self, id):
1416 self._id = id
1416 self._id = id
1417 self._entry = None
1417 self._entry = None
1418
1418
1419 def __eq__(self, other):
1419 def __eq__(self, other):
1420 return self.__class__ is other.__class__ and self._id == other._id
1420 return self.__class__ is other.__class__ and self._id == other._id
1421
1421
1422 def __ne__(self, other):
1422 def __ne__(self, other):
1423 return self.__class__ is not other.__class__ or self._id != other._id
1423 return self.__class__ is not other.__class__ or self._id != other._id
1424
1424
1425 def _getentry(self):
1425 def _getentry(self):
1426 if self._entry is None:
1426 if self._entry is None:
1427 if isinstance(self._id, basestring):
1427 if isinstance(self._id, basestring):
1428 self._entry = grp.getgrnam(self._id)
1428 self._entry = grp.getgrnam(self._id)
1429 else:
1429 else:
1430 self._entry = grp.getgrgid(self._id)
1430 self._entry = grp.getgrgid(self._id)
1431 return self._entry
1431 return self._entry
1432
1432
1433 def getname(self):
1433 def getname(self):
1434 if isinstance(self._id, basestring):
1434 if isinstance(self._id, basestring):
1435 return self._id
1435 return self._id
1436 else:
1436 else:
1437 return self._getentry().gr_name
1437 return self._getentry().gr_name
1438 name = property(getname, None, None, "Group name")
1438 name = property(getname, None, None, "Group name")
1439
1439
1440 def getpasswd(self):
1440 def getpasswd(self):
1441 return self._getentry().gr_passwd
1441 return self._getentry().gr_passwd
1442 passwd = property(getpasswd, None, None, "Password")
1442 passwd = property(getpasswd, None, None, "Password")
1443
1443
1444 def getgid(self):
1444 def getgid(self):
1445 if isinstance(self._id, basestring):
1445 if isinstance(self._id, basestring):
1446 return self._getentry().gr_gid
1446 return self._getentry().gr_gid
1447 else:
1447 else:
1448 return self._id
1448 return self._id
1449 gid = property(getgid, None, None, "Group id")
1449 gid = property(getgid, None, None, "Group id")
1450
1450
1451 def getmem(self):
1451 def getmem(self):
1452 return self._getentry().gr_mem
1452 return self._getentry().gr_mem
1453 mem = property(getmem, None, None, "Members")
1453 mem = property(getmem, None, None, "Members")
1454
1454
1455 def __xattrs__(self, mode="default"):
1455 def __xattrs__(self, mode="default"):
1456 return ("name", "passwd", "gid", "mem")
1456 return ("name", "passwd", "gid", "mem")
1457
1457
1458 def __xrepr__(self, mode="default"):
1458 def __xrepr__(self, mode="default"):
1459 if mode == "header" or mode == "footer" or mode == "cell":
1459 if mode == "header" or mode == "footer" or mode == "cell":
1460 yield (astyle.style_default, "group ")
1460 yield (astyle.style_default, "group ")
1461 try:
1461 try:
1462 yield (astyle.style_default, self.name)
1462 yield (astyle.style_default, self.name)
1463 except KeyError:
1463 except KeyError:
1464 if isinstance(self._id, basestring):
1464 if isinstance(self._id, basestring):
1465 yield (astyle.style_default, self.name_id)
1465 yield (astyle.style_default, self.name_id)
1466 else:
1466 else:
1467 yield (astyle.style_type_number, str(self._id))
1467 yield (astyle.style_type_number, str(self._id))
1468 else:
1468 else:
1469 yield (astyle.style_default, repr(self))
1469 yield (astyle.style_default, repr(self))
1470
1470
1471 def __iter__(self):
1471 def __iter__(self):
1472 for member in self.mem:
1472 for member in self.mem:
1473 yield ipwdentry(member)
1473 yield ipwdentry(member)
1474
1474
1475 def __repr__(self):
1475 def __repr__(self):
1476 return "%s.%s(%r)" % \
1476 return "%s.%s(%r)" % \
1477 (self.__class__.__module__, self.__class__.__name__, self._id)
1477 (self.__class__.__module__, self.__class__.__name__, self._id)
1478
1478
1479
1479
1480 class igrp(Table):
1480 class igrp(Table):
1481 """
1481 """
1482 This ``Table`` lists all entries in the Unix group database.
1482 This ``Table`` lists all entries in the Unix group database.
1483 """
1483 """
1484 def __iter__(self):
1484 def __iter__(self):
1485 for entry in grp.getgrall():
1485 for entry in grp.getgrall():
1486 yield igrpentry(entry.gr_name)
1486 yield igrpentry(entry.gr_name)
1487
1487
1488 def __xrepr__(self, mode="default"):
1488 def __xrepr__(self, mode="default"):
1489 if mode == "header" or mode == "footer":
1489 if mode == "header" or mode == "footer":
1490 yield (astyle.style_default, "%s()" % self.__class__.__name__)
1490 yield (astyle.style_default, "%s()" % self.__class__.__name__)
1491 else:
1491 else:
1492 yield (astyle.style_default, repr(self))
1492 yield (astyle.style_default, repr(self))
1493
1493
1494
1494
1495 class Fields(object):
1495 class Fields(object):
1496 def __init__(self, fieldnames, **fields):
1496 def __init__(self, fieldnames, **fields):
1497 self.__fieldnames = [upgradexattr(fieldname) for fieldname in fieldnames]
1497 self.__fieldnames = [upgradexattr(fieldname) for fieldname in fieldnames]
1498 for (key, value) in fields.iteritems():
1498 for (key, value) in fields.iteritems():
1499 setattr(self, key, value)
1499 setattr(self, key, value)
1500
1500
1501 def __xattrs__(self, mode="default"):
1501 def __xattrs__(self, mode="default"):
1502 return self.__fieldnames
1502 return self.__fieldnames
1503
1503
1504 def __xrepr__(self, mode="default"):
1504 def __xrepr__(self, mode="default"):
1505 yield (-1, False)
1505 yield (-1, False)
1506 if mode == "header" or mode == "cell":
1506 if mode == "header" or mode == "cell":
1507 yield (astyle.style_default, self.__class__.__name__)
1507 yield (astyle.style_default, self.__class__.__name__)
1508 yield (astyle.style_default, "(")
1508 yield (astyle.style_default, "(")
1509 for (i, f) in enumerate(self.__fieldnames):
1509 for (i, f) in enumerate(self.__fieldnames):
1510 if i:
1510 if i:
1511 yield (astyle.style_default, ", ")
1511 yield (astyle.style_default, ", ")
1512 yield (astyle.style_default, f.name())
1512 yield (astyle.style_default, f.name())
1513 yield (astyle.style_default, "=")
1513 yield (astyle.style_default, "=")
1514 for part in xrepr(getattr(self, f), "default"):
1514 for part in xrepr(getattr(self, f), "default"):
1515 yield part
1515 yield part
1516 yield (astyle.style_default, ")")
1516 yield (astyle.style_default, ")")
1517 elif mode == "footer":
1517 elif mode == "footer":
1518 yield (astyle.style_default, self.__class__.__name__)
1518 yield (astyle.style_default, self.__class__.__name__)
1519 yield (astyle.style_default, "(")
1519 yield (astyle.style_default, "(")
1520 for (i, f) in enumerate(self.__fieldnames):
1520 for (i, f) in enumerate(self.__fieldnames):
1521 if i:
1521 if i:
1522 yield (astyle.style_default, ", ")
1522 yield (astyle.style_default, ", ")
1523 yield (astyle.style_default, f.name())
1523 yield (astyle.style_default, f.name())
1524 yield (astyle.style_default, ")")
1524 yield (astyle.style_default, ")")
1525 else:
1525 else:
1526 yield (astyle.style_default, repr(self))
1526 yield (astyle.style_default, repr(self))
1527
1527
1528
1528
1529 class FieldTable(Table, list):
1529 class FieldTable(Table, list):
1530 def __init__(self, *fields):
1530 def __init__(self, *fields):
1531 Table.__init__(self)
1531 Table.__init__(self)
1532 list.__init__(self)
1532 list.__init__(self)
1533 self.fields = fields
1533 self.fields = fields
1534
1534
1535 def add(self, **fields):
1535 def add(self, **fields):
1536 self.append(Fields(self.fields, **fields))
1536 self.append(Fields(self.fields, **fields))
1537
1537
1538 def __xrepr__(self, mode="default"):
1538 def __xrepr__(self, mode="default"):
1539 yield (-1, False)
1539 yield (-1, False)
1540 if mode == "header" or mode == "footer":
1540 if mode == "header" or mode == "footer":
1541 yield (astyle.style_default, self.__class__.__name__)
1541 yield (astyle.style_default, self.__class__.__name__)
1542 yield (astyle.style_default, "(")
1542 yield (astyle.style_default, "(")
1543 for (i, f) in enumerate(self.__fieldnames):
1543 for (i, f) in enumerate(self.__fieldnames):
1544 if i:
1544 if i:
1545 yield (astyle.style_default, ", ")
1545 yield (astyle.style_default, ", ")
1546 yield (astyle.style_default, f)
1546 yield (astyle.style_default, f)
1547 yield (astyle.style_default, ")")
1547 yield (astyle.style_default, ")")
1548 else:
1548 else:
1549 yield (astyle.style_default, repr(self))
1549 yield (astyle.style_default, repr(self))
1550
1550
1551 def __repr__(self):
1551 def __repr__(self):
1552 return "<%s.%s object with fields=%r at 0x%x>" % \
1552 return "<%s.%s object with fields=%r at 0x%x>" % \
1553 (self.__class__.__module__, self.__class__.__name__,
1553 (self.__class__.__module__, self.__class__.__name__,
1554 ", ".join(map(repr, self.fields)), id(self))
1554 ", ".join(map(repr, self.fields)), id(self))
1555
1555
1556
1556
1557 class List(list):
1557 class List(list):
1558 def __xattrs__(self, mode="default"):
1558 def __xattrs__(self, mode="default"):
1559 return xrange(len(self))
1559 return xrange(len(self))
1560
1560
1561 def __xrepr__(self, mode="default"):
1561 def __xrepr__(self, mode="default"):
1562 yield (-1, False)
1562 yield (-1, False)
1563 if mode == "header" or mode == "cell" or mode == "footer" or mode == "default":
1563 if mode == "header" or mode == "cell" or mode == "footer" or mode == "default":
1564 yield (astyle.style_default, self.__class__.__name__)
1564 yield (astyle.style_default, self.__class__.__name__)
1565 yield (astyle.style_default, "(")
1565 yield (astyle.style_default, "(")
1566 for (i, item) in enumerate(self):
1566 for (i, item) in enumerate(self):
1567 if i:
1567 if i:
1568 yield (astyle.style_default, ", ")
1568 yield (astyle.style_default, ", ")
1569 for part in xrepr(item, "default"):
1569 for part in xrepr(item, "default"):
1570 yield part
1570 yield part
1571 yield (astyle.style_default, ")")
1571 yield (astyle.style_default, ")")
1572 else:
1572 else:
1573 yield (astyle.style_default, repr(self))
1573 yield (astyle.style_default, repr(self))
1574
1574
1575
1575
1576 class ienv(Table):
1576 class ienv(Table):
1577 """
1577 """
1578 List environment variables.
1578 List environment variables.
1579
1579
1580 Example::
1580 Example::
1581
1581
1582 >>> ienv
1582 >>> ienv
1583 <class 'IPython.extensions.ipipe.ienv'>
1583 <class 'IPython.extensions.ipipe.ienv'>
1584 """
1584 """
1585
1585
1586 def __iter__(self):
1586 def __iter__(self):
1587 fields = ("key", "value")
1587 fields = ("key", "value")
1588 for (key, value) in os.environ.iteritems():
1588 for (key, value) in os.environ.iteritems():
1589 yield Fields(fields, key=key, value=value)
1589 yield Fields(fields, key=key, value=value)
1590
1590
1591 def __xrepr__(self, mode="default"):
1591 def __xrepr__(self, mode="default"):
1592 if mode == "header" or mode == "cell":
1592 if mode == "header" or mode == "cell":
1593 yield (astyle.style_default, "%s()" % self.__class__.__name__)
1593 yield (astyle.style_default, "%s()" % self.__class__.__name__)
1594 else:
1594 else:
1595 yield (astyle.style_default, repr(self))
1595 yield (astyle.style_default, repr(self))
1596
1596
1597
1597
1598 class ihist(Table):
1598 class ihist(Table):
1599 """
1599 """
1600 IPython input history
1600 IPython input history
1601
1601
1602 Example::
1602 Example::
1603
1603
1604 >>> ihist
1604 >>> ihist
1605 <class 'IPython.extensions.ipipe.ihist'>
1605 <class 'IPython.extensions.ipipe.ihist'>
1606 >>> ihist(True) # raw mode
1606 >>> ihist(True) # raw mode
1607 <IPython.extensions.ipipe.ihist object at 0x849602c> # random
1607 <IPython.extensions.ipipe.ihist object at 0x849602c> # random
1608 """
1608 """
1609 def __init__(self, raw=True):
1609 def __init__(self, raw=True):
1610 self.raw = raw
1610 self.raw = raw
1611
1611
1612 def __iter__(self):
1612 def __iter__(self):
1613 api = ipapi.get()
1613 api = ipapi.get()
1614 if self.raw:
1614 if self.raw:
1615 for line in api.input_hist_raw:
1615 for line in api.input_hist_raw:
1616 yield line.rstrip("\n")
1616 yield line.rstrip("\n")
1617 else:
1617 else:
1618 for line in api.input_hist:
1618 for line in api.input_hist:
1619 yield line.rstrip("\n")
1619 yield line.rstrip("\n")
1620
1620
1621
1621
1622 class Alias(object):
1622 class Alias(object):
1623 """
1623 """
1624 Entry in the alias table
1624 Entry in the alias table
1625 """
1625 """
1626 def __init__(self, name, args, command):
1626 def __init__(self, name, args, command):
1627 self.name = name
1627 self.name = name
1628 self.args = args
1628 self.args = args
1629 self.command = command
1629 self.command = command
1630
1630
1631 def __xattrs__(self, mode="default"):
1631 def __xattrs__(self, mode="default"):
1632 return ("name", "args", "command")
1632 return ("name", "args", "command")
1633
1633
1634
1634
1635 class ialias(Table):
1635 class ialias(Table):
1636 """
1636 """
1637 IPython alias list
1637 IPython alias list
1638
1638
1639 Example::
1639 Example::
1640
1640
1641 >>> ialias
1641 >>> ialias
1642 <class 'IPython.extensions.ipipe.ialias'>
1642 <class 'IPython.extensions.ipipe.ialias'>
1643 """
1643 """
1644 def __iter__(self):
1644 def __iter__(self):
1645 api = ipapi.get()
1645 api = ipapi.get()
1646
1646
1647 for (name, (args, command)) in api.alias_manager.alias_table.iteritems():
1647 for (name, (args, command)) in api.alias_manager.alias_table.iteritems():
1648 yield Alias(name, args, command)
1648 yield Alias(name, args, command)
1649
1649
1650
1650
1651 class icsv(Pipe):
1651 class icsv(Pipe):
1652 """
1652 """
1653 This ``Pipe`` turns the input (with must be a pipe outputting lines
1653 This ``Pipe`` turns the input (with must be a pipe outputting lines
1654 or an ``ifile``) into lines of CVS columns.
1654 or an ``ifile``) into lines of CVS columns.
1655 """
1655 """
1656 def __init__(self, **csvargs):
1656 def __init__(self, **csvargs):
1657 """
1657 """
1658 Create an ``icsv`` object. ``cvsargs`` will be passed through as
1658 Create an ``icsv`` object. ``cvsargs`` will be passed through as
1659 keyword arguments to ``cvs.reader()``.
1659 keyword arguments to ``cvs.reader()``.
1660 """
1660 """
1661 self.csvargs = csvargs
1661 self.csvargs = csvargs
1662
1662
1663 def __iter__(self):
1663 def __iter__(self):
1664 input = self.input
1664 input = self.input
1665 if isinstance(input, ifile):
1665 if isinstance(input, ifile):
1666 input = input.open("rb")
1666 input = input.open("rb")
1667 reader = csv.reader(input, **self.csvargs)
1667 reader = csv.reader(input, **self.csvargs)
1668 for line in reader:
1668 for line in reader:
1669 yield List(line)
1669 yield List(line)
1670
1670
1671 def __xrepr__(self, mode="default"):
1671 def __xrepr__(self, mode="default"):
1672 yield (-1, False)
1672 yield (-1, False)
1673 if mode == "header" or mode == "footer":
1673 if mode == "header" or mode == "footer":
1674 input = getattr(self, "input", None)
1674 input = getattr(self, "input", None)
1675 if input is not None:
1675 if input is not None:
1676 for part in xrepr(input, mode):
1676 for part in xrepr(input, mode):
1677 yield part
1677 yield part
1678 yield (astyle.style_default, " | ")
1678 yield (astyle.style_default, " | ")
1679 yield (astyle.style_default, "%s(" % self.__class__.__name__)
1679 yield (astyle.style_default, "%s(" % self.__class__.__name__)
1680 for (i, (name, value)) in enumerate(self.csvargs.iteritems()):
1680 for (i, (name, value)) in enumerate(self.csvargs.iteritems()):
1681 if i:
1681 if i:
1682 yield (astyle.style_default, ", ")
1682 yield (astyle.style_default, ", ")
1683 yield (astyle.style_default, name)
1683 yield (astyle.style_default, name)
1684 yield (astyle.style_default, "=")
1684 yield (astyle.style_default, "=")
1685 for part in xrepr(value, "default"):
1685 for part in xrepr(value, "default"):
1686 yield part
1686 yield part
1687 yield (astyle.style_default, ")")
1687 yield (astyle.style_default, ")")
1688 else:
1688 else:
1689 yield (astyle.style_default, repr(self))
1689 yield (astyle.style_default, repr(self))
1690
1690
1691 def __repr__(self):
1691 def __repr__(self):
1692 args = ", ".join(["%s=%r" % item for item in self.csvargs.iteritems()])
1692 args = ", ".join(["%s=%r" % item for item in self.csvargs.iteritems()])
1693 return "<%s.%s %s at 0x%x>" % \
1693 return "<%s.%s %s at 0x%x>" % \
1694 (self.__class__.__module__, self.__class__.__name__, args, id(self))
1694 (self.__class__.__module__, self.__class__.__name__, args, id(self))
1695
1695
1696
1696
1697 class ix(Table):
1697 class ix(Table):
1698 """
1698 """
1699 Execute a system command and list its output as lines
1699 Execute a system command and list its output as lines
1700 (similar to ``os.popen()``).
1700 (similar to ``os.popen()``).
1701
1701
1702 Examples::
1702 Examples::
1703
1703
1704 >>> ix("ps x")
1704 >>> ix("ps x")
1705 IPython.extensions.ipipe.ix('ps x')
1705 IPython.extensions.ipipe.ix('ps x')
1706
1706
1707 >>> ix("find .") | ifile
1707 >>> ix("find .") | ifile
1708 <IPython.extensions.ipipe.ieval expr=<class 'IPython.extensions.ipipe.ifile'> at 0x8509d2c>
1708 <IPython.extensions.ipipe.ieval expr=<class 'IPython.extensions.ipipe.ifile'> at 0x8509d2c>
1709 # random
1709 # random
1710 """
1710 """
1711 def __init__(self, cmd):
1711 def __init__(self, cmd):
1712 self.cmd = cmd
1712 self.cmd = cmd
1713 self._pipeout = None
1713 self._pipeout = None
1714
1714
1715 def __iter__(self):
1715 def __iter__(self):
1716 (_pipein, self._pipeout) = os.popen4(self.cmd)
1716 (_pipein, self._pipeout) = os.popen4(self.cmd)
1717 _pipein.close()
1717 _pipein.close()
1718 for l in self._pipeout:
1718 for l in self._pipeout:
1719 yield l.rstrip("\r\n")
1719 yield l.rstrip("\r\n")
1720 self._pipeout.close()
1720 self._pipeout.close()
1721 self._pipeout = None
1721 self._pipeout = None
1722
1722
1723 def __del__(self):
1723 def __del__(self):
1724 if self._pipeout is not None and not self._pipeout.closed:
1724 if self._pipeout is not None and not self._pipeout.closed:
1725 self._pipeout.close()
1725 self._pipeout.close()
1726 self._pipeout = None
1726 self._pipeout = None
1727
1727
1728 def __xrepr__(self, mode="default"):
1728 def __xrepr__(self, mode="default"):
1729 if mode == "header" or mode == "footer":
1729 if mode == "header" or mode == "footer":
1730 yield (astyle.style_default,
1730 yield (astyle.style_default,
1731 "%s(%r)" % (self.__class__.__name__, self.cmd))
1731 "%s(%r)" % (self.__class__.__name__, self.cmd))
1732 else:
1732 else:
1733 yield (astyle.style_default, repr(self))
1733 yield (astyle.style_default, repr(self))
1734
1734
1735 def __repr__(self):
1735 def __repr__(self):
1736 return "%s.%s(%r)" % \
1736 return "%s.%s(%r)" % \
1737 (self.__class__.__module__, self.__class__.__name__, self.cmd)
1737 (self.__class__.__module__, self.__class__.__name__, self.cmd)
1738
1738
1739
1739
1740 class ifilter(Pipe):
1740 class ifilter(Pipe):
1741 """
1741 """
1742 Filter an input pipe. Only objects where an expression evaluates to true
1742 Filter an input pipe. Only objects where an expression evaluates to true
1743 (and doesn't raise an exception) are listed.
1743 (and doesn't raise an exception) are listed.
1744
1744
1745 Examples::
1745 Examples::
1746
1746
1747 >>> ils | ifilter("_.isfile() and size>1000")
1747 >>> ils | ifilter("_.isfile() and size>1000")
1748 >>> igrp | ifilter("len(mem)")
1748 >>> igrp | ifilter("len(mem)")
1749 >>> sys.modules | ifilter(lambda _:_.value is not None)
1749 >>> sys.modules | ifilter(lambda _:_.value is not None)
1750 # all-random
1750 # all-random
1751 """
1751 """
1752
1752
1753 def __init__(self, expr, globals=None, errors="raiseifallfail"):
1753 def __init__(self, expr, globals=None, errors="raiseifallfail"):
1754 """
1754 """
1755 Create an ``ifilter`` object. ``expr`` can be a callable or a string
1755 Create an ``ifilter`` object. ``expr`` can be a callable or a string
1756 containing an expression. ``globals`` will be used as the global
1756 containing an expression. ``globals`` will be used as the global
1757 namespace for calling string expressions (defaulting to IPython's
1757 namespace for calling string expressions (defaulting to IPython's
1758 user namespace). ``errors`` specifies how exception during evaluation
1758 user namespace). ``errors`` specifies how exception during evaluation
1759 of ``expr`` are handled:
1759 of ``expr`` are handled:
1760
1760
1761 ``"drop"``
1761 ``"drop"``
1762 drop all items that have errors;
1762 drop all items that have errors;
1763
1763
1764 ``"keep"``
1764 ``"keep"``
1765 keep all items that have errors;
1765 keep all items that have errors;
1766
1766
1767 ``"keeperror"``
1767 ``"keeperror"``
1768 keep the exception of all items that have errors;
1768 keep the exception of all items that have errors;
1769
1769
1770 ``"raise"``
1770 ``"raise"``
1771 raise the exception;
1771 raise the exception;
1772
1772
1773 ``"raiseifallfail"``
1773 ``"raiseifallfail"``
1774 raise the first exception if all items have errors; otherwise drop
1774 raise the first exception if all items have errors; otherwise drop
1775 those with errors (this is the default).
1775 those with errors (this is the default).
1776 """
1776 """
1777 self.expr = expr
1777 self.expr = expr
1778 self.globals = globals
1778 self.globals = globals
1779 self.errors = errors
1779 self.errors = errors
1780
1780
1781 def __iter__(self):
1781 def __iter__(self):
1782 if callable(self.expr):
1782 if callable(self.expr):
1783 test = self.expr
1783 test = self.expr
1784 else:
1784 else:
1785 g = getglobals(self.globals)
1785 g = getglobals(self.globals)
1786 expr = compile(self.expr, "ipipe-expression", "eval")
1786 expr = compile(self.expr, "ipipe-expression", "eval")
1787 def test(item):
1787 def test(item):
1788 return eval(expr, g, AttrNamespace(item))
1788 return eval(expr, g, AttrNamespace(item))
1789
1789
1790 ok = 0
1790 ok = 0
1791 exc_info = None
1791 exc_info = None
1792 for item in xiter(self.input):
1792 for item in xiter(self.input):
1793 try:
1793 try:
1794 if test(item):
1794 if test(item):
1795 yield item
1795 yield item
1796 ok += 1
1796 ok += 1
1797 except (KeyboardInterrupt, SystemExit):
1797 except (KeyboardInterrupt, SystemExit):
1798 raise
1798 raise
1799 except Exception, exc:
1799 except Exception, exc:
1800 if self.errors == "drop":
1800 if self.errors == "drop":
1801 pass # Ignore errors
1801 pass # Ignore errors
1802 elif self.errors == "keep":
1802 elif self.errors == "keep":
1803 yield item
1803 yield item
1804 elif self.errors == "keeperror":
1804 elif self.errors == "keeperror":
1805 yield exc
1805 yield exc
1806 elif self.errors == "raise":
1806 elif self.errors == "raise":
1807 raise
1807 raise
1808 elif self.errors == "raiseifallfail":
1808 elif self.errors == "raiseifallfail":
1809 if exc_info is None:
1809 if exc_info is None:
1810 exc_info = sys.exc_info()
1810 exc_info = sys.exc_info()
1811 if not ok and exc_info is not None:
1811 if not ok and exc_info is not None:
1812 raise exc_info[0], exc_info[1], exc_info[2]
1812 raise exc_info[0], exc_info[1], exc_info[2]
1813
1813
1814 def __xrepr__(self, mode="default"):
1814 def __xrepr__(self, mode="default"):
1815 if mode == "header" or mode == "footer":
1815 if mode == "header" or mode == "footer":
1816 input = getattr(self, "input", None)
1816 input = getattr(self, "input", None)
1817 if input is not None:
1817 if input is not None:
1818 for part in xrepr(input, mode):
1818 for part in xrepr(input, mode):
1819 yield part
1819 yield part
1820 yield (astyle.style_default, " | ")
1820 yield (astyle.style_default, " | ")
1821 yield (astyle.style_default, "%s(" % self.__class__.__name__)
1821 yield (astyle.style_default, "%s(" % self.__class__.__name__)
1822 for part in xrepr(self.expr, "default"):
1822 for part in xrepr(self.expr, "default"):
1823 yield part
1823 yield part
1824 yield (astyle.style_default, ")")
1824 yield (astyle.style_default, ")")
1825 else:
1825 else:
1826 yield (astyle.style_default, repr(self))
1826 yield (astyle.style_default, repr(self))
1827
1827
1828 def __repr__(self):
1828 def __repr__(self):
1829 return "<%s.%s expr=%r at 0x%x>" % \
1829 return "<%s.%s expr=%r at 0x%x>" % \
1830 (self.__class__.__module__, self.__class__.__name__,
1830 (self.__class__.__module__, self.__class__.__name__,
1831 self.expr, id(self))
1831 self.expr, id(self))
1832
1832
1833
1833
1834 class ieval(Pipe):
1834 class ieval(Pipe):
1835 """
1835 """
1836 Evaluate an expression for each object in the input pipe.
1836 Evaluate an expression for each object in the input pipe.
1837
1837
1838 Examples::
1838 Examples::
1839
1839
1840 >>> ils | ieval("_.abspath()")
1840 >>> ils | ieval("_.abspath()")
1841 # random
1841 # random
1842 >>> sys.path | ieval(ifile)
1842 >>> sys.path | ieval(ifile)
1843 # random
1843 # random
1844 """
1844 """
1845
1845
1846 def __init__(self, expr, globals=None, errors="raiseifallfail"):
1846 def __init__(self, expr, globals=None, errors="raiseifallfail"):
1847 """
1847 """
1848 Create an ``ieval`` object. ``expr`` can be a callable or a string
1848 Create an ``ieval`` object. ``expr`` can be a callable or a string
1849 containing an expression. For the meaning of ``globals`` and
1849 containing an expression. For the meaning of ``globals`` and
1850 ``errors`` see ``ifilter``.
1850 ``errors`` see ``ifilter``.
1851 """
1851 """
1852 self.expr = expr
1852 self.expr = expr
1853 self.globals = globals
1853 self.globals = globals
1854 self.errors = errors
1854 self.errors = errors
1855
1855
1856 def __iter__(self):
1856 def __iter__(self):
1857 if callable(self.expr):
1857 if callable(self.expr):
1858 do = self.expr
1858 do = self.expr
1859 else:
1859 else:
1860 g = getglobals(self.globals)
1860 g = getglobals(self.globals)
1861 expr = compile(self.expr, "ipipe-expression", "eval")
1861 expr = compile(self.expr, "ipipe-expression", "eval")
1862 def do(item):
1862 def do(item):
1863 return eval(expr, g, AttrNamespace(item))
1863 return eval(expr, g, AttrNamespace(item))
1864
1864
1865 ok = 0
1865 ok = 0
1866 exc_info = None
1866 exc_info = None
1867 for item in xiter(self.input):
1867 for item in xiter(self.input):
1868 try:
1868 try:
1869 yield do(item)
1869 yield do(item)
1870 except (KeyboardInterrupt, SystemExit):
1870 except (KeyboardInterrupt, SystemExit):
1871 raise
1871 raise
1872 except Exception, exc:
1872 except Exception, exc:
1873 if self.errors == "drop":
1873 if self.errors == "drop":
1874 pass # Ignore errors
1874 pass # Ignore errors
1875 elif self.errors == "keep":
1875 elif self.errors == "keep":
1876 yield item
1876 yield item
1877 elif self.errors == "keeperror":
1877 elif self.errors == "keeperror":
1878 yield exc
1878 yield exc
1879 elif self.errors == "raise":
1879 elif self.errors == "raise":
1880 raise
1880 raise
1881 elif self.errors == "raiseifallfail":
1881 elif self.errors == "raiseifallfail":
1882 if exc_info is None:
1882 if exc_info is None:
1883 exc_info = sys.exc_info()
1883 exc_info = sys.exc_info()
1884 if not ok and exc_info is not None:
1884 if not ok and exc_info is not None:
1885 raise exc_info[0], exc_info[1], exc_info[2]
1885 raise exc_info[0], exc_info[1], exc_info[2]
1886
1886
1887 def __xrepr__(self, mode="default"):
1887 def __xrepr__(self, mode="default"):
1888 if mode == "header" or mode == "footer":
1888 if mode == "header" or mode == "footer":
1889 input = getattr(self, "input", None)
1889 input = getattr(self, "input", None)
1890 if input is not None:
1890 if input is not None:
1891 for part in xrepr(input, mode):
1891 for part in xrepr(input, mode):
1892 yield part
1892 yield part
1893 yield (astyle.style_default, " | ")
1893 yield (astyle.style_default, " | ")
1894 yield (astyle.style_default, "%s(" % self.__class__.__name__)
1894 yield (astyle.style_default, "%s(" % self.__class__.__name__)
1895 for part in xrepr(self.expr, "default"):
1895 for part in xrepr(self.expr, "default"):
1896 yield part
1896 yield part
1897 yield (astyle.style_default, ")")
1897 yield (astyle.style_default, ")")
1898 else:
1898 else:
1899 yield (astyle.style_default, repr(self))
1899 yield (astyle.style_default, repr(self))
1900
1900
1901 def __repr__(self):
1901 def __repr__(self):
1902 return "<%s.%s expr=%r at 0x%x>" % \
1902 return "<%s.%s expr=%r at 0x%x>" % \
1903 (self.__class__.__module__, self.__class__.__name__,
1903 (self.__class__.__module__, self.__class__.__name__,
1904 self.expr, id(self))
1904 self.expr, id(self))
1905
1905
1906
1906
1907 class ienum(Pipe):
1907 class ienum(Pipe):
1908 """
1908 """
1909 Enumerate the input pipe (i.e. wrap each input object in an object
1909 Enumerate the input pipe (i.e. wrap each input object in an object
1910 with ``index`` and ``object`` attributes).
1910 with ``index`` and ``object`` attributes).
1911
1911
1912 Examples::
1912 Examples::
1913
1913
1914 >>> xrange(20) | ieval("_,_*_") | ienum | ifilter("index % 2 == 0") | ieval("object")
1914 >>> xrange(20) | ieval("_,_*_") | ienum | ifilter("index % 2 == 0") | ieval("object")
1915 """
1915 """
1916 skip_doctest = True
1916 skip_doctest = True
1917
1917
1918 def __iter__(self):
1918 def __iter__(self):
1919 fields = ("index", "object")
1919 fields = ("index", "object")
1920 for (index, object) in enumerate(xiter(self.input)):
1920 for (index, object) in enumerate(xiter(self.input)):
1921 yield Fields(fields, index=index, object=object)
1921 yield Fields(fields, index=index, object=object)
1922
1922
1923
1923
1924 class isort(Pipe):
1924 class isort(Pipe):
1925 """
1925 """
1926 Sorts the input pipe.
1926 Sorts the input pipe.
1927
1927
1928 Examples::
1928 Examples::
1929
1929
1930 >>> ils | isort("size")
1930 >>> ils | isort("size")
1931 <IPython.extensions.ipipe.isort key='size' reverse=False at 0x849ec2c>
1931 <IPython.extensions.ipipe.isort key='size' reverse=False at 0x849ec2c>
1932 >>> ils | isort("_.isdir(), _.lower()", reverse=True)
1932 >>> ils | isort("_.isdir(), _.lower()", reverse=True)
1933 <IPython.extensions.ipipe.isort key='_.isdir(), _.lower()' reverse=True at 0x849eacc>
1933 <IPython.extensions.ipipe.isort key='_.isdir(), _.lower()' reverse=True at 0x849eacc>
1934 # all-random
1934 # all-random
1935 """
1935 """
1936
1936
1937 def __init__(self, key=None, globals=None, reverse=False):
1937 def __init__(self, key=None, globals=None, reverse=False):
1938 """
1938 """
1939 Create an ``isort`` object. ``key`` can be a callable or a string
1939 Create an ``isort`` object. ``key`` can be a callable or a string
1940 containing an expression (or ``None`` in which case the items
1940 containing an expression (or ``None`` in which case the items
1941 themselves will be sorted). If ``reverse`` is true the sort order
1941 themselves will be sorted). If ``reverse`` is true the sort order
1942 will be reversed. For the meaning of ``globals`` see ``ifilter``.
1942 will be reversed. For the meaning of ``globals`` see ``ifilter``.
1943 """
1943 """
1944 self.key = key
1944 self.key = key
1945 self.globals = globals
1945 self.globals = globals
1946 self.reverse = reverse
1946 self.reverse = reverse
1947
1947
1948 def __iter__(self):
1948 def __iter__(self):
1949 if self.key is None:
1949 if self.key is None:
1950 items = sorted(xiter(self.input), reverse=self.reverse)
1950 items = sorted(xiter(self.input), reverse=self.reverse)
1951 elif callable(self.key):
1951 elif callable(self.key):
1952 items = sorted(xiter(self.input), key=self.key, reverse=self.reverse)
1952 items = sorted(xiter(self.input), key=self.key, reverse=self.reverse)
1953 else:
1953 else:
1954 g = getglobals(self.globals)
1954 g = getglobals(self.globals)
1955 key = compile(self.key, "ipipe-expression", "eval")
1955 key = compile(self.key, "ipipe-expression", "eval")
1956 def realkey(item):
1956 def realkey(item):
1957 return eval(key, g, AttrNamespace(item))
1957 return eval(key, g, AttrNamespace(item))
1958 items = sorted(xiter(self.input), key=realkey, reverse=self.reverse)
1958 items = sorted(xiter(self.input), key=realkey, reverse=self.reverse)
1959 for item in items:
1959 for item in items:
1960 yield item
1960 yield item
1961
1961
1962 def __xrepr__(self, mode="default"):
1962 def __xrepr__(self, mode="default"):
1963 if mode == "header" or mode == "footer":
1963 if mode == "header" or mode == "footer":
1964 input = getattr(self, "input", None)
1964 input = getattr(self, "input", None)
1965 if input is not None:
1965 if input is not None:
1966 for part in xrepr(input, mode):
1966 for part in xrepr(input, mode):
1967 yield part
1967 yield part
1968 yield (astyle.style_default, " | ")
1968 yield (astyle.style_default, " | ")
1969 yield (astyle.style_default, "%s(" % self.__class__.__name__)
1969 yield (astyle.style_default, "%s(" % self.__class__.__name__)
1970 for part in xrepr(self.key, "default"):
1970 for part in xrepr(self.key, "default"):
1971 yield part
1971 yield part
1972 if self.reverse:
1972 if self.reverse:
1973 yield (astyle.style_default, ", ")
1973 yield (astyle.style_default, ", ")
1974 for part in xrepr(True, "default"):
1974 for part in xrepr(True, "default"):
1975 yield part
1975 yield part
1976 yield (astyle.style_default, ")")
1976 yield (astyle.style_default, ")")
1977 else:
1977 else:
1978 yield (astyle.style_default, repr(self))
1978 yield (astyle.style_default, repr(self))
1979
1979
1980 def __repr__(self):
1980 def __repr__(self):
1981 return "<%s.%s key=%r reverse=%r at 0x%x>" % \
1981 return "<%s.%s key=%r reverse=%r at 0x%x>" % \
1982 (self.__class__.__module__, self.__class__.__name__,
1982 (self.__class__.__module__, self.__class__.__name__,
1983 self.key, self.reverse, id(self))
1983 self.key, self.reverse, id(self))
1984
1984
1985
1985
1986 tab = 3 # for expandtabs()
1986 tab = 3 # for expandtabs()
1987
1987
1988 def _format(field):
1988 def _format(field):
1989 if isinstance(field, str):
1989 if isinstance(field, str):
1990 text = repr(field.expandtabs(tab))[1:-1]
1990 text = repr(field.expandtabs(tab))[1:-1]
1991 elif isinstance(field, unicode):
1991 elif isinstance(field, unicode):
1992 text = repr(field.expandtabs(tab))[2:-1]
1992 text = repr(field.expandtabs(tab))[2:-1]
1993 elif isinstance(field, datetime.datetime):
1993 elif isinstance(field, datetime.datetime):
1994 # Don't use strftime() here, as this requires year >= 1900
1994 # Don't use strftime() here, as this requires year >= 1900
1995 text = "%04d-%02d-%02d %02d:%02d:%02d.%06d" % \
1995 text = "%04d-%02d-%02d %02d:%02d:%02d.%06d" % \
1996 (field.year, field.month, field.day,
1996 (field.year, field.month, field.day,
1997 field.hour, field.minute, field.second, field.microsecond)
1997 field.hour, field.minute, field.second, field.microsecond)
1998 elif isinstance(field, datetime.date):
1998 elif isinstance(field, datetime.date):
1999 text = "%04d-%02d-%02d" % (field.year, field.month, field.day)
1999 text = "%04d-%02d-%02d" % (field.year, field.month, field.day)
2000 else:
2000 else:
2001 text = repr(field)
2001 text = repr(field)
2002 return text
2002 return text
2003
2003
2004
2004
2005 class Display(object):
2005 class Display(object):
2006 class __metaclass__(type):
2006 class __metaclass__(type):
2007 def __ror__(self, input):
2007 def __ror__(self, input):
2008 return input | self()
2008 return input | self()
2009
2009
2010 def __init__(self, input=None):
2010 def __init__(self, input=None):
2011 self.input = input
2011 self.input = input
2012
2012
2013 def __ror__(self, input):
2013 def __ror__(self, input):
2014 self.input = input
2014 self.input = input
2015 return self
2015 return self
2016
2016
2017 def display(self):
2017 def display(self):
2018 pass
2018 pass
2019
2019
2020
2020
2021 class iless(Display):
2021 class iless(Display):
2022 cmd = "less --quit-if-one-screen --LONG-PROMPT --LINE-NUMBERS --chop-long-lines --shift=8 --RAW-CONTROL-CHARS"
2022 cmd = "less --quit-if-one-screen --LONG-PROMPT --LINE-NUMBERS --chop-long-lines --shift=8 --RAW-CONTROL-CHARS"
2023
2023
2024 def display(self):
2024 def display(self):
2025 try:
2025 try:
2026 pager = os.popen(self.cmd, "w")
2026 pager = os.popen(self.cmd, "w")
2027 try:
2027 try:
2028 for item in xiter(self.input):
2028 for item in xiter(self.input):
2029 first = False
2029 first = False
2030 for attr in xattrs(item, "default"):
2030 for attr in xattrs(item, "default"):
2031 if first:
2031 if first:
2032 first = False
2032 first = False
2033 else:
2033 else:
2034 pager.write(" ")
2034 pager.write(" ")
2035 attr = upgradexattr(attr)
2035 attr = upgradexattr(attr)
2036 if not isinstance(attr, SelfDescriptor):
2036 if not isinstance(attr, SelfDescriptor):
2037 pager.write(attr.name())
2037 pager.write(attr.name())
2038 pager.write("=")
2038 pager.write("=")
2039 pager.write(str(attr.value(item)))
2039 pager.write(str(attr.value(item)))
2040 pager.write("\n")
2040 pager.write("\n")
2041 finally:
2041 finally:
2042 pager.close()
2042 pager.close()
2043 except Exception, exc:
2043 except Exception, exc:
2044 print "%s: %s" % (exc.__class__.__name__, str(exc))
2044 print "%s: %s" % (exc.__class__.__name__, str(exc))
2045
2045
2046
2046
2047 class _RedirectIO(object):
2047 class _RedirectIO(object):
2048 def __init__(self,*args,**kwargs):
2048 def __init__(self,*args,**kwargs):
2049 """
2049 """
2050 Map the system output streams to self.
2050 Map the system output streams to self.
2051 """
2051 """
2052 self.stream = StringIO.StringIO()
2052 self.stream = StringIO.StringIO()
2053 self.stdout = sys.stdout
2053 self.stdout = sys.stdout
2054 sys.stdout = self
2054 sys.stdout = self
2055 self.stderr = sys.stderr
2055 self.stderr = sys.stderr
2056 sys.stderr = self
2056 sys.stderr = self
2057
2057
2058 def write(self, text):
2058 def write(self, text):
2059 """
2059 """
2060 Write both to screen and to self.
2060 Write both to screen and to self.
2061 """
2061 """
2062 self.stream.write(text)
2062 self.stream.write(text)
2063 self.stdout.write(text)
2063 self.stdout.write(text)
2064 if "\n" in text:
2064 if "\n" in text:
2065 self.stdout.flush()
2065 self.stdout.flush()
2066
2066
2067 def writelines(self, lines):
2067 def writelines(self, lines):
2068 """
2068 """
2069 Write lines both to screen and to self.
2069 Write lines both to screen and to self.
2070 """
2070 """
2071 self.stream.writelines(lines)
2071 self.stream.writelines(lines)
2072 self.stdout.writelines(lines)
2072 self.stdout.writelines(lines)
2073 self.stdout.flush()
2073 self.stdout.flush()
2074
2074
2075 def restore(self):
2075 def restore(self):
2076 """
2076 """
2077 Restore the default system streams.
2077 Restore the default system streams.
2078 """
2078 """
2079 self.stdout.flush()
2079 self.stdout.flush()
2080 self.stderr.flush()
2080 self.stderr.flush()
2081 sys.stdout = self.stdout
2081 sys.stdout = self.stdout
2082 sys.stderr = self.stderr
2082 sys.stderr = self.stderr
2083
2083
2084
2084
2085 class icap(Table):
2085 class icap(Table):
2086 """
2086 """
2087 Execute a python string and capture any output to stderr/stdout.
2087 Execute a python string and capture any output to stderr/stdout.
2088
2088
2089 Examples::
2089 Examples::
2090
2090
2091 >>> import time
2091 >>> import time
2092 >>> icap("for i in range(10): print i, time.sleep(0.1)")
2092 >>> icap("for i in range(10): print i, time.sleep(0.1)")
2093
2093
2094 """
2094 """
2095 skip_doctest = True
2095 skip_doctest = True
2096
2096
2097 def __init__(self, expr, globals=None):
2097 def __init__(self, expr, globals=None):
2098 self.expr = expr
2098 self.expr = expr
2099 self.globals = globals
2099 self.globals = globals
2100 log = _RedirectIO()
2100 log = _RedirectIO()
2101 try:
2101 try:
2102 exec(expr, getglobals(globals))
2102 exec(expr, getglobals(globals))
2103 finally:
2103 finally:
2104 log.restore()
2104 log.restore()
2105 self.stream = log.stream
2105 self.stream = log.stream
2106
2106
2107 def __iter__(self):
2107 def __iter__(self):
2108 self.stream.seek(0)
2108 self.stream.seek(0)
2109 for line in self.stream:
2109 for line in self.stream:
2110 yield line.rstrip("\r\n")
2110 yield line.rstrip("\r\n")
2111
2111
2112 def __xrepr__(self, mode="default"):
2112 def __xrepr__(self, mode="default"):
2113 if mode == "header" or mode == "footer":
2113 if mode == "header" or mode == "footer":
2114 yield (astyle.style_default,
2114 yield (astyle.style_default,
2115 "%s(%r)" % (self.__class__.__name__, self.expr))
2115 "%s(%r)" % (self.__class__.__name__, self.expr))
2116 else:
2116 else:
2117 yield (astyle.style_default, repr(self))
2117 yield (astyle.style_default, repr(self))
2118
2118
2119 def __repr__(self):
2119 def __repr__(self):
2120 return "%s.%s(%r)" % \
2120 return "%s.%s(%r)" % \
2121 (self.__class__.__module__, self.__class__.__name__, self.expr)
2121 (self.__class__.__module__, self.__class__.__name__, self.expr)
2122
2122
2123
2123
2124 def xformat(value, mode, maxlength):
2124 def xformat(value, mode, maxlength):
2125 align = None
2125 align = None
2126 full = True
2126 full = True
2127 width = 0
2127 width = 0
2128 text = astyle.Text()
2128 text = astyle.Text()
2129 for (style, part) in xrepr(value, mode):
2129 for (style, part) in xrepr(value, mode):
2130 # only consider the first result
2130 # only consider the first result
2131 if align is None:
2131 if align is None:
2132 if isinstance(style, int):
2132 if isinstance(style, int):
2133 # (style, text) really is (alignment, stop)
2133 # (style, text) really is (alignment, stop)
2134 align = style
2134 align = style
2135 full = part
2135 full = part
2136 continue
2136 continue
2137 else:
2137 else:
2138 align = -1
2138 align = -1
2139 full = True
2139 full = True
2140 if not isinstance(style, int):
2140 if not isinstance(style, int):
2141 text.append((style, part))
2141 text.append((style, part))
2142 width += len(part)
2142 width += len(part)
2143 if width >= maxlength and not full:
2143 if width >= maxlength and not full:
2144 text.append((astyle.style_ellisis, "..."))
2144 text.append((astyle.style_ellisis, "..."))
2145 width += 3
2145 width += 3
2146 break
2146 break
2147 if align is None: # default to left alignment
2147 if align is None: # default to left alignment
2148 align = -1
2148 align = -1
2149 return (align, width, text)
2149 return (align, width, text)
2150
2150
2151
2151
2152
2152
2153 import astyle
2153 import astyle
2154
2154
2155 class idump(Display):
2155 class idump(Display):
2156 # The approximate maximum length of a column entry
2156 # The approximate maximum length of a column entry
2157 maxattrlength = 200
2157 maxattrlength = 200
2158
2158
2159 # Style for column names
2159 # Style for column names
2160 style_header = astyle.Style.fromstr("white:black:bold")
2160 style_header = astyle.Style.fromstr("white:black:bold")
2161
2161
2162 def __init__(self, input=None, *attrs):
2162 def __init__(self, input=None, *attrs):
2163 Display.__init__(self, input)
2163 Display.__init__(self, input)
2164 self.attrs = [upgradexattr(attr) for attr in attrs]
2164 self.attrs = [upgradexattr(attr) for attr in attrs]
2165 self.headerpadchar = " "
2165 self.headerpadchar = " "
2166 self.headersepchar = "|"
2166 self.headersepchar = "|"
2167 self.datapadchar = " "
2167 self.datapadchar = " "
2168 self.datasepchar = "|"
2168 self.datasepchar = "|"
2169
2169
2170 def display(self):
2170 def display(self):
2171 stream = Term.cout
2171 stream = Term.cout
2172 allattrs = []
2172 allattrs = []
2173 attrset = set()
2173 attrset = set()
2174 colwidths = {}
2174 colwidths = {}
2175 rows = []
2175 rows = []
2176 for item in xiter(self.input):
2176 for item in xiter(self.input):
2177 row = {}
2177 row = {}
2178 attrs = self.attrs
2178 attrs = self.attrs
2179 if not attrs:
2179 if not attrs:
2180 attrs = xattrs(item, "default")
2180 attrs = xattrs(item, "default")
2181 for attr in attrs:
2181 for attr in attrs:
2182 if attr not in attrset:
2182 if attr not in attrset:
2183 allattrs.append(attr)
2183 allattrs.append(attr)
2184 attrset.add(attr)
2184 attrset.add(attr)
2185 colwidths[attr] = len(attr.name())
2185 colwidths[attr] = len(attr.name())
2186 try:
2186 try:
2187 value = attr.value(item)
2187 value = attr.value(item)
2188 except (KeyboardInterrupt, SystemExit):
2188 except (KeyboardInterrupt, SystemExit):
2189 raise
2189 raise
2190 except Exception, exc:
2190 except Exception, exc:
2191 value = exc
2191 value = exc
2192 (align, width, text) = xformat(value, "cell", self.maxattrlength)
2192 (align, width, text) = xformat(value, "cell", self.maxattrlength)
2193 colwidths[attr] = max(colwidths[attr], width)
2193 colwidths[attr] = max(colwidths[attr], width)
2194 # remember alignment, length and colored parts
2194 # remember alignment, length and colored parts
2195 row[attr] = (align, width, text)
2195 row[attr] = (align, width, text)
2196 rows.append(row)
2196 rows.append(row)
2197
2197
2198 stream.write("\n")
2198 stream.write("\n")
2199 for (i, attr) in enumerate(allattrs):
2199 for (i, attr) in enumerate(allattrs):
2200 attrname = attr.name()
2200 attrname = attr.name()
2201 self.style_header(attrname).write(stream)
2201 self.style_header(attrname).write(stream)
2202 spc = colwidths[attr] - len(attrname)
2202 spc = colwidths[attr] - len(attrname)
2203 if i < len(colwidths)-1:
2203 if i < len(colwidths)-1:
2204 stream.write(self.headerpadchar*spc)
2204 stream.write(self.headerpadchar*spc)
2205 stream.write(self.headersepchar)
2205 stream.write(self.headersepchar)
2206 stream.write("\n")
2206 stream.write("\n")
2207
2207
2208 for row in rows:
2208 for row in rows:
2209 for (i, attr) in enumerate(allattrs):
2209 for (i, attr) in enumerate(allattrs):
2210 (align, width, text) = row[attr]
2210 (align, width, text) = row[attr]
2211 spc = colwidths[attr] - width
2211 spc = colwidths[attr] - width
2212 if align == -1:
2212 if align == -1:
2213 text.write(stream)
2213 text.write(stream)
2214 if i < len(colwidths)-1:
2214 if i < len(colwidths)-1:
2215 stream.write(self.datapadchar*spc)
2215 stream.write(self.datapadchar*spc)
2216 elif align == 0:
2216 elif align == 0:
2217 spc = colwidths[attr] - width
2217 spc = colwidths[attr] - width
2218 spc1 = spc//2
2218 spc1 = spc//2
2219 spc2 = spc-spc1
2219 spc2 = spc-spc1
2220 stream.write(self.datapadchar*spc1)
2220 stream.write(self.datapadchar*spc1)
2221 text.write(stream)
2221 text.write(stream)
2222 if i < len(colwidths)-1:
2222 if i < len(colwidths)-1:
2223 stream.write(self.datapadchar*spc2)
2223 stream.write(self.datapadchar*spc2)
2224 else:
2224 else:
2225 stream.write(self.datapadchar*spc)
2225 stream.write(self.datapadchar*spc)
2226 text.write(stream)
2226 text.write(stream)
2227 if i < len(colwidths)-1:
2227 if i < len(colwidths)-1:
2228 stream.write(self.datasepchar)
2228 stream.write(self.datasepchar)
2229 stream.write("\n")
2229 stream.write("\n")
2230
2230
2231
2231
2232 class AttributeDetail(Table):
2232 class AttributeDetail(Table):
2233 """
2233 """
2234 ``AttributeDetail`` objects are use for displaying a detailed list of object
2234 ``AttributeDetail`` objects are use for displaying a detailed list of object
2235 attributes.
2235 attributes.
2236 """
2236 """
2237 def __init__(self, object, descriptor):
2237 def __init__(self, object, descriptor):
2238 self.object = object
2238 self.object = object
2239 self.descriptor = descriptor
2239 self.descriptor = descriptor
2240
2240
2241 def __iter__(self):
2241 def __iter__(self):
2242 return self.descriptor.iter(self.object)
2242 return self.descriptor.iter(self.object)
2243
2243
2244 def name(self):
2244 def name(self):
2245 return self.descriptor.name()
2245 return self.descriptor.name()
2246
2246
2247 def attrtype(self):
2247 def attrtype(self):
2248 return self.descriptor.attrtype(self.object)
2248 return self.descriptor.attrtype(self.object)
2249
2249
2250 def valuetype(self):
2250 def valuetype(self):
2251 return self.descriptor.valuetype(self.object)
2251 return self.descriptor.valuetype(self.object)
2252
2252
2253 def doc(self):
2253 def doc(self):
2254 return self.descriptor.doc(self.object)
2254 return self.descriptor.doc(self.object)
2255
2255
2256 def shortdoc(self):
2256 def shortdoc(self):
2257 return self.descriptor.shortdoc(self.object)
2257 return self.descriptor.shortdoc(self.object)
2258
2258
2259 def value(self):
2259 def value(self):
2260 return self.descriptor.value(self.object)
2260 return self.descriptor.value(self.object)
2261
2261
2262 def __xattrs__(self, mode="default"):
2262 def __xattrs__(self, mode="default"):
2263 attrs = ("name()", "attrtype()", "valuetype()", "value()", "shortdoc()")
2263 attrs = ("name()", "attrtype()", "valuetype()", "value()", "shortdoc()")
2264 if mode == "detail":
2264 if mode == "detail":
2265 attrs += ("doc()",)
2265 attrs += ("doc()",)
2266 return attrs
2266 return attrs
2267
2267
2268 def __xrepr__(self, mode="default"):
2268 def __xrepr__(self, mode="default"):
2269 yield (-1, True)
2269 yield (-1, True)
2270 valuetype = self.valuetype()
2270 valuetype = self.valuetype()
2271 if valuetype is not noitem:
2271 if valuetype is not noitem:
2272 for part in xrepr(valuetype):
2272 for part in xrepr(valuetype):
2273 yield part
2273 yield part
2274 yield (astyle.style_default, " ")
2274 yield (astyle.style_default, " ")
2275 yield (astyle.style_default, self.attrtype())
2275 yield (astyle.style_default, self.attrtype())
2276 yield (astyle.style_default, " ")
2276 yield (astyle.style_default, " ")
2277 yield (astyle.style_default, self.name())
2277 yield (astyle.style_default, self.name())
2278 yield (astyle.style_default, " of ")
2278 yield (astyle.style_default, " of ")
2279 for part in xrepr(self.object):
2279 for part in xrepr(self.object):
2280 yield part
2280 yield part
2281
2281
2282
2282
2283 try:
2283 try:
2284 from ibrowse import ibrowse
2284 from ibrowse import ibrowse
2285 except ImportError:
2285 except ImportError:
2286 # No curses (probably Windows) => try igrid
2286 # No curses (probably Windows) => try igrid
2287 try:
2287 try:
2288 from igrid import igrid
2288 from igrid import igrid
2289 except ImportError:
2289 except ImportError:
2290 # no wx either => use ``idump`` as the default display.
2290 # no wx either => use ``idump`` as the default display.
2291 defaultdisplay = idump
2291 defaultdisplay = idump
2292 else:
2292 else:
2293 defaultdisplay = igrid
2293 defaultdisplay = igrid
2294 __all__.append("igrid")
2294 __all__.append("igrid")
2295 else:
2295 else:
2296 defaultdisplay = ibrowse
2296 defaultdisplay = ibrowse
2297 __all__.append("ibrowse")
2297 __all__.append("ibrowse")
2298
2298
2299
2299
2300 # If we're running under IPython, register our objects with IPython's
2300 # If we're running under IPython, register our objects with IPython's
2301 # generic function ``result_display``, else install a displayhook
2301 # generic function ``result_display``, else install a displayhook
2302 # directly as sys.displayhook
2302 # directly as sys.displayhook
2303 if generics is not None:
2303 if generics is not None:
2304 def display_display(obj):
2304 def display_display(obj):
2305 return obj.display()
2305 return obj.display()
2306 generics.result_display.when_type(Display)(display_display)
2306 generics.result_display.when_type(Display)(display_display)
2307
2307
2308 def display_tableobject(obj):
2308 def display_tableobject(obj):
2309 return display_display(defaultdisplay(obj))
2309 return display_display(defaultdisplay(obj))
2310 generics.result_display.when_type(Table)(display_tableobject)
2310 generics.result_display.when_type(Table)(display_tableobject)
2311
2311
2312 def display_tableclass(obj):
2312 def display_tableclass(obj):
2313 return display_tableobject(obj())
2313 return display_tableobject(obj())
2314 generics.result_display.when_type(Table.__metaclass__)(display_tableclass)
2314 generics.result_display.when_type(Table.__metaclass__)(display_tableclass)
2315 else:
2315 else:
2316 def installdisplayhook():
2316 def installdisplayhook():
2317 _originalhook = sys.displayhook
2317 _originalhook = sys.displayhook
2318 def displayhook(obj):
2318 def displayhook(obj):
2319 if isinstance(obj, type) and issubclass(obj, Table):
2319 if isinstance(obj, type) and issubclass(obj, Table):
2320 obj = obj()
2320 obj = obj()
2321 if isinstance(obj, Table):
2321 if isinstance(obj, Table):
2322 obj = defaultdisplay(obj)
2322 obj = defaultdisplay(obj)
2323 if isinstance(obj, Display):
2323 if isinstance(obj, Display):
2324 return obj.display()
2324 return obj.display()
2325 else:
2325 else:
2326 _originalhook(obj)
2326 _originalhook(obj)
2327 sys.displayhook = displayhook
2327 sys.displayhook = displayhook
2328 installdisplayhook()
2328 installdisplayhook()
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now