##// END OF EJS Templates
io.Term.cin/out/err replaced by io.stdin/out/err...
MinRK -
Show More
@@ -1,510 +1,509 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, io
35 import IPython.utils.io
36 from IPython.core.excolors import exception_colors
35 from IPython.core.excolors import exception_colors
37
36
38 # See if we can use pydb.
37 # See if we can use pydb.
39 has_pydb = False
38 has_pydb = False
40 prompt = 'ipdb> '
39 prompt = 'ipdb> '
41 #We have to check this directly from sys.argv, config struct not yet available
40 #We have to check this directly from sys.argv, config struct not yet available
42 if '-pydb' in sys.argv:
41 if '-pydb' in sys.argv:
43 try:
42 try:
44 import pydb
43 import pydb
45 if hasattr(pydb.pydb, "runl") and pydb.version>'1.17':
44 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
45 # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we
47 # better protect against it.
46 # better protect against it.
48 has_pydb = True
47 has_pydb = True
49 except ImportError:
48 except ImportError:
50 print "Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available"
49 print "Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available"
51
50
52 if has_pydb:
51 if has_pydb:
53 from pydb import Pdb as OldPdb
52 from pydb import Pdb as OldPdb
54 #print "Using pydb for %run -d and post-mortem" #dbg
53 #print "Using pydb for %run -d and post-mortem" #dbg
55 prompt = 'ipydb> '
54 prompt = 'ipydb> '
56 else:
55 else:
57 from pdb import Pdb as OldPdb
56 from pdb import Pdb as OldPdb
58
57
59 # Allow the set_trace code to operate outside of an ipython instance, even if
58 # 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
59 # it does so with some limitations. The rest of this support is implemented in
61 # the Tracer constructor.
60 # the Tracer constructor.
62 def BdbQuit_excepthook(et,ev,tb):
61 def BdbQuit_excepthook(et,ev,tb):
63 if et==bdb.BdbQuit:
62 if et==bdb.BdbQuit:
64 print 'Exiting Debugger.'
63 print 'Exiting Debugger.'
65 else:
64 else:
66 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
65 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
67
66
68 def BdbQuit_IPython_excepthook(self,et,ev,tb):
67 def BdbQuit_IPython_excepthook(self,et,ev,tb):
69 print 'Exiting Debugger.'
68 print 'Exiting Debugger.'
70
69
71
70
72 class Tracer(object):
71 class Tracer(object):
73 """Class for local debugging, similar to pdb.set_trace.
72 """Class for local debugging, similar to pdb.set_trace.
74
73
75 Instances of this class, when called, behave like pdb.set_trace, but
74 Instances of this class, when called, behave like pdb.set_trace, but
76 providing IPython's enhanced capabilities.
75 providing IPython's enhanced capabilities.
77
76
78 This is implemented as a class which must be initialized in your own code
77 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
78 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
79 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,
80 constructor, ensuring that this code plays nicely with a running IPython,
82 while functioning acceptably (though with limitations) if outside of it.
81 while functioning acceptably (though with limitations) if outside of it.
83 """
82 """
84
83
85 def __init__(self,colors=None):
84 def __init__(self,colors=None):
86 """Create a local debugger instance.
85 """Create a local debugger instance.
87
86
88 :Parameters:
87 :Parameters:
89
88
90 - `colors` (None): a string containing the name of the color scheme to
89 - `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
90 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
91 function will default to the current IPython scheme when running inside
93 IPython, and to 'NoColor' otherwise.
92 IPython, and to 'NoColor' otherwise.
94
93
95 Usage example:
94 Usage example:
96
95
97 from IPython.core.debugger import Tracer; debug_here = Tracer()
96 from IPython.core.debugger import Tracer; debug_here = Tracer()
98
97
99 ... later in your code
98 ... later in your code
100 debug_here() # -> will open up the debugger at that point.
99 debug_here() # -> will open up the debugger at that point.
101
100
102 Once the debugger activates, you can use all of its regular commands to
101 Once the debugger activates, you can use all of its regular commands to
103 step through code, set breakpoints, etc. See the pdb documentation
102 step through code, set breakpoints, etc. See the pdb documentation
104 from the Python standard library for usage details.
103 from the Python standard library for usage details.
105 """
104 """
106
105
107 try:
106 try:
108 ip = ipapi.get()
107 ip = ipapi.get()
109 except:
108 except:
110 # Outside of ipython, we set our own exception hook manually
109 # Outside of ipython, we set our own exception hook manually
111 BdbQuit_excepthook.excepthook_ori = sys.excepthook
110 BdbQuit_excepthook.excepthook_ori = sys.excepthook
112 sys.excepthook = BdbQuit_excepthook
111 sys.excepthook = BdbQuit_excepthook
113 def_colors = 'NoColor'
112 def_colors = 'NoColor'
114 try:
113 try:
115 # Limited tab completion support
114 # Limited tab completion support
116 import readline
115 import readline
117 readline.parse_and_bind('tab: complete')
116 readline.parse_and_bind('tab: complete')
118 except ImportError:
117 except ImportError:
119 pass
118 pass
120 else:
119 else:
121 # In ipython, we use its custom exception handler mechanism
120 # In ipython, we use its custom exception handler mechanism
122 def_colors = ip.colors
121 def_colors = ip.colors
123 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
122 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
124
123
125 if colors is None:
124 if colors is None:
126 colors = def_colors
125 colors = def_colors
127 self.debugger = Pdb(colors)
126 self.debugger = Pdb(colors)
128
127
129 def __call__(self):
128 def __call__(self):
130 """Starts an interactive debugger at the point where called.
129 """Starts an interactive debugger at the point where called.
131
130
132 This is similar to the pdb.set_trace() function from the std lib, but
131 This is similar to the pdb.set_trace() function from the std lib, but
133 using IPython's enhanced debugger."""
132 using IPython's enhanced debugger."""
134
133
135 self.debugger.set_trace(sys._getframe().f_back)
134 self.debugger.set_trace(sys._getframe().f_back)
136
135
137
136
138 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
137 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
138 """Make new_fn have old_fn's doc string. This is particularly useful
140 for the do_... commands that hook into the help system.
139 for the do_... commands that hook into the help system.
141 Adapted from from a comp.lang.python posting
140 Adapted from from a comp.lang.python posting
142 by Duncan Booth."""
141 by Duncan Booth."""
143 def wrapper(*args, **kw):
142 def wrapper(*args, **kw):
144 return new_fn(*args, **kw)
143 return new_fn(*args, **kw)
145 if old_fn.__doc__:
144 if old_fn.__doc__:
146 wrapper.__doc__ = old_fn.__doc__ + additional_text
145 wrapper.__doc__ = old_fn.__doc__ + additional_text
147 return wrapper
146 return wrapper
148
147
149
148
150 def _file_lines(fname):
149 def _file_lines(fname):
151 """Return the contents of a named file as a list of lines.
150 """Return the contents of a named file as a list of lines.
152
151
153 This function never raises an IOError exception: if the file can't be
152 This function never raises an IOError exception: if the file can't be
154 read, it simply returns an empty list."""
153 read, it simply returns an empty list."""
155
154
156 try:
155 try:
157 outfile = open(fname)
156 outfile = open(fname)
158 except IOError:
157 except IOError:
159 return []
158 return []
160 else:
159 else:
161 out = outfile.readlines()
160 out = outfile.readlines()
162 outfile.close()
161 outfile.close()
163 return out
162 return out
164
163
165
164
166 class Pdb(OldPdb):
165 class Pdb(OldPdb):
167 """Modified Pdb class, does not load readline."""
166 """Modified Pdb class, does not load readline."""
168
167
169 def __init__(self,color_scheme='NoColor',completekey=None,
168 def __init__(self,color_scheme='NoColor',completekey=None,
170 stdin=None, stdout=None):
169 stdin=None, stdout=None):
171
170
172 # Parent constructor:
171 # Parent constructor:
173 if has_pydb and completekey is None:
172 if has_pydb and completekey is None:
174 OldPdb.__init__(self,stdin=stdin,stdout=IPython.utils.io.Term.cout)
173 OldPdb.__init__(self,stdin=stdin,stdout=io.stdout)
175 else:
174 else:
176 OldPdb.__init__(self,completekey,stdin,stdout)
175 OldPdb.__init__(self,completekey,stdin,stdout)
177
176
178 self.prompt = prompt # The default prompt is '(Pdb)'
177 self.prompt = prompt # The default prompt is '(Pdb)'
179
178
180 # IPython changes...
179 # IPython changes...
181 self.is_pydb = has_pydb
180 self.is_pydb = has_pydb
182
181
183 self.shell = ipapi.get()
182 self.shell = ipapi.get()
184
183
185 if self.is_pydb:
184 if self.is_pydb:
186
185
187 # interactiveshell.py's ipalias seems to want pdb's checkline
186 # interactiveshell.py's ipalias seems to want pdb's checkline
188 # which located in pydb.fn
187 # which located in pydb.fn
189 import pydb.fns
188 import pydb.fns
190 self.checkline = lambda filename, lineno: \
189 self.checkline = lambda filename, lineno: \
191 pydb.fns.checkline(self, filename, lineno)
190 pydb.fns.checkline(self, filename, lineno)
192
191
193 self.curframe = None
192 self.curframe = None
194 self.do_restart = self.new_do_restart
193 self.do_restart = self.new_do_restart
195
194
196 self.old_all_completions = self.shell.Completer.all_completions
195 self.old_all_completions = self.shell.Completer.all_completions
197 self.shell.Completer.all_completions=self.all_completions
196 self.shell.Completer.all_completions=self.all_completions
198
197
199 self.do_list = decorate_fn_with_doc(self.list_command_pydb,
198 self.do_list = decorate_fn_with_doc(self.list_command_pydb,
200 OldPdb.do_list)
199 OldPdb.do_list)
201 self.do_l = self.do_list
200 self.do_l = self.do_list
202 self.do_frame = decorate_fn_with_doc(self.new_do_frame,
201 self.do_frame = decorate_fn_with_doc(self.new_do_frame,
203 OldPdb.do_frame)
202 OldPdb.do_frame)
204
203
205 self.aliases = {}
204 self.aliases = {}
206
205
207 # Create color table: we copy the default one from the traceback
206 # Create color table: we copy the default one from the traceback
208 # module and add a few attributes needed for debugging
207 # module and add a few attributes needed for debugging
209 self.color_scheme_table = exception_colors()
208 self.color_scheme_table = exception_colors()
210
209
211 # shorthands
210 # shorthands
212 C = coloransi.TermColors
211 C = coloransi.TermColors
213 cst = self.color_scheme_table
212 cst = self.color_scheme_table
214
213
215 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
214 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
216 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
215 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
217
216
218 cst['Linux'].colors.breakpoint_enabled = C.LightRed
217 cst['Linux'].colors.breakpoint_enabled = C.LightRed
219 cst['Linux'].colors.breakpoint_disabled = C.Red
218 cst['Linux'].colors.breakpoint_disabled = C.Red
220
219
221 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
220 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
222 cst['LightBG'].colors.breakpoint_disabled = C.Red
221 cst['LightBG'].colors.breakpoint_disabled = C.Red
223
222
224 self.set_colors(color_scheme)
223 self.set_colors(color_scheme)
225
224
226 # Add a python parser so we can syntax highlight source while
225 # Add a python parser so we can syntax highlight source while
227 # debugging.
226 # debugging.
228 self.parser = PyColorize.Parser()
227 self.parser = PyColorize.Parser()
229
228
230 def set_colors(self, scheme):
229 def set_colors(self, scheme):
231 """Shorthand access to the color table scheme selector method."""
230 """Shorthand access to the color table scheme selector method."""
232 self.color_scheme_table.set_active_scheme(scheme)
231 self.color_scheme_table.set_active_scheme(scheme)
233
232
234 def interaction(self, frame, traceback):
233 def interaction(self, frame, traceback):
235 self.shell.set_completer_frame(frame)
234 self.shell.set_completer_frame(frame)
236 OldPdb.interaction(self, frame, traceback)
235 OldPdb.interaction(self, frame, traceback)
237
236
238 def new_do_up(self, arg):
237 def new_do_up(self, arg):
239 OldPdb.do_up(self, arg)
238 OldPdb.do_up(self, arg)
240 self.shell.set_completer_frame(self.curframe)
239 self.shell.set_completer_frame(self.curframe)
241 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
240 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
242
241
243 def new_do_down(self, arg):
242 def new_do_down(self, arg):
244 OldPdb.do_down(self, arg)
243 OldPdb.do_down(self, arg)
245 self.shell.set_completer_frame(self.curframe)
244 self.shell.set_completer_frame(self.curframe)
246
245
247 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
246 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
248
247
249 def new_do_frame(self, arg):
248 def new_do_frame(self, arg):
250 OldPdb.do_frame(self, arg)
249 OldPdb.do_frame(self, arg)
251 self.shell.set_completer_frame(self.curframe)
250 self.shell.set_completer_frame(self.curframe)
252
251
253 def new_do_quit(self, arg):
252 def new_do_quit(self, arg):
254
253
255 if hasattr(self, 'old_all_completions'):
254 if hasattr(self, 'old_all_completions'):
256 self.shell.Completer.all_completions=self.old_all_completions
255 self.shell.Completer.all_completions=self.old_all_completions
257
256
258
257
259 return OldPdb.do_quit(self, arg)
258 return OldPdb.do_quit(self, arg)
260
259
261 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
260 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
262
261
263 def new_do_restart(self, arg):
262 def new_do_restart(self, arg):
264 """Restart command. In the context of ipython this is exactly the same
263 """Restart command. In the context of ipython this is exactly the same
265 thing as 'quit'."""
264 thing as 'quit'."""
266 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
265 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
267 return self.do_quit(arg)
266 return self.do_quit(arg)
268
267
269 def postloop(self):
268 def postloop(self):
270 self.shell.set_completer_frame(None)
269 self.shell.set_completer_frame(None)
271
270
272 def print_stack_trace(self):
271 def print_stack_trace(self):
273 try:
272 try:
274 for frame_lineno in self.stack:
273 for frame_lineno in self.stack:
275 self.print_stack_entry(frame_lineno, context = 5)
274 self.print_stack_entry(frame_lineno, context = 5)
276 except KeyboardInterrupt:
275 except KeyboardInterrupt:
277 pass
276 pass
278
277
279 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
278 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
280 context = 3):
279 context = 3):
281 #frame, lineno = frame_lineno
280 #frame, lineno = frame_lineno
282 print >>IPython.utils.io.Term.cout, self.format_stack_entry(frame_lineno, '', context)
281 print >>io.stdout, self.format_stack_entry(frame_lineno, '', context)
283
282
284 # vds: >>
283 # vds: >>
285 frame, lineno = frame_lineno
284 frame, lineno = frame_lineno
286 filename = frame.f_code.co_filename
285 filename = frame.f_code.co_filename
287 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
286 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
288 # vds: <<
287 # vds: <<
289
288
290 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
289 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
291 import linecache, repr
290 import linecache, repr
292
291
293 ret = []
292 ret = []
294
293
295 Colors = self.color_scheme_table.active_colors
294 Colors = self.color_scheme_table.active_colors
296 ColorsNormal = Colors.Normal
295 ColorsNormal = Colors.Normal
297 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
296 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
298 tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
297 tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
299 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
298 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
300 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
299 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
301 ColorsNormal)
300 ColorsNormal)
302
301
303 frame, lineno = frame_lineno
302 frame, lineno = frame_lineno
304
303
305 return_value = ''
304 return_value = ''
306 if '__return__' in frame.f_locals:
305 if '__return__' in frame.f_locals:
307 rv = frame.f_locals['__return__']
306 rv = frame.f_locals['__return__']
308 #return_value += '->'
307 #return_value += '->'
309 return_value += repr.repr(rv) + '\n'
308 return_value += repr.repr(rv) + '\n'
310 ret.append(return_value)
309 ret.append(return_value)
311
310
312 #s = filename + '(' + `lineno` + ')'
311 #s = filename + '(' + `lineno` + ')'
313 filename = self.canonic(frame.f_code.co_filename)
312 filename = self.canonic(frame.f_code.co_filename)
314 link = tpl_link % filename
313 link = tpl_link % filename
315
314
316 if frame.f_code.co_name:
315 if frame.f_code.co_name:
317 func = frame.f_code.co_name
316 func = frame.f_code.co_name
318 else:
317 else:
319 func = "<lambda>"
318 func = "<lambda>"
320
319
321 call = ''
320 call = ''
322 if func != '?':
321 if func != '?':
323 if '__args__' in frame.f_locals:
322 if '__args__' in frame.f_locals:
324 args = repr.repr(frame.f_locals['__args__'])
323 args = repr.repr(frame.f_locals['__args__'])
325 else:
324 else:
326 args = '()'
325 args = '()'
327 call = tpl_call % (func, args)
326 call = tpl_call % (func, args)
328
327
329 # The level info should be generated in the same format pdb uses, to
328 # The level info should be generated in the same format pdb uses, to
330 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
329 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
331 if frame is self.curframe:
330 if frame is self.curframe:
332 ret.append('> ')
331 ret.append('> ')
333 else:
332 else:
334 ret.append(' ')
333 ret.append(' ')
335 ret.append('%s(%s)%s\n' % (link,lineno,call))
334 ret.append('%s(%s)%s\n' % (link,lineno,call))
336
335
337 start = lineno - 1 - context//2
336 start = lineno - 1 - context//2
338 lines = linecache.getlines(filename)
337 lines = linecache.getlines(filename)
339 start = max(start, 0)
338 start = max(start, 0)
340 start = min(start, len(lines) - context)
339 start = min(start, len(lines) - context)
341 lines = lines[start : start + context]
340 lines = lines[start : start + context]
342
341
343 for i,line in enumerate(lines):
342 for i,line in enumerate(lines):
344 show_arrow = (start + 1 + i == lineno)
343 show_arrow = (start + 1 + i == lineno)
345 linetpl = (frame is self.curframe or show_arrow) \
344 linetpl = (frame is self.curframe or show_arrow) \
346 and tpl_line_em \
345 and tpl_line_em \
347 or tpl_line
346 or tpl_line
348 ret.append(self.__format_line(linetpl, filename,
347 ret.append(self.__format_line(linetpl, filename,
349 start + 1 + i, line,
348 start + 1 + i, line,
350 arrow = show_arrow) )
349 arrow = show_arrow) )
351
350
352 return ''.join(ret)
351 return ''.join(ret)
353
352
354 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
353 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
355 bp_mark = ""
354 bp_mark = ""
356 bp_mark_color = ""
355 bp_mark_color = ""
357
356
358 scheme = self.color_scheme_table.active_scheme_name
357 scheme = self.color_scheme_table.active_scheme_name
359 new_line, err = self.parser.format2(line, 'str', scheme)
358 new_line, err = self.parser.format2(line, 'str', scheme)
360 if not err: line = new_line
359 if not err: line = new_line
361
360
362 bp = None
361 bp = None
363 if lineno in self.get_file_breaks(filename):
362 if lineno in self.get_file_breaks(filename):
364 bps = self.get_breaks(filename, lineno)
363 bps = self.get_breaks(filename, lineno)
365 bp = bps[-1]
364 bp = bps[-1]
366
365
367 if bp:
366 if bp:
368 Colors = self.color_scheme_table.active_colors
367 Colors = self.color_scheme_table.active_colors
369 bp_mark = str(bp.number)
368 bp_mark = str(bp.number)
370 bp_mark_color = Colors.breakpoint_enabled
369 bp_mark_color = Colors.breakpoint_enabled
371 if not bp.enabled:
370 if not bp.enabled:
372 bp_mark_color = Colors.breakpoint_disabled
371 bp_mark_color = Colors.breakpoint_disabled
373
372
374 numbers_width = 7
373 numbers_width = 7
375 if arrow:
374 if arrow:
376 # This is the line with the error
375 # This is the line with the error
377 pad = numbers_width - len(str(lineno)) - len(bp_mark)
376 pad = numbers_width - len(str(lineno)) - len(bp_mark)
378 if pad >= 3:
377 if pad >= 3:
379 marker = '-'*(pad-3) + '-> '
378 marker = '-'*(pad-3) + '-> '
380 elif pad == 2:
379 elif pad == 2:
381 marker = '> '
380 marker = '> '
382 elif pad == 1:
381 elif pad == 1:
383 marker = '>'
382 marker = '>'
384 else:
383 else:
385 marker = ''
384 marker = ''
386 num = '%s%s' % (marker, str(lineno))
385 num = '%s%s' % (marker, str(lineno))
387 line = tpl_line % (bp_mark_color + bp_mark, num, line)
386 line = tpl_line % (bp_mark_color + bp_mark, num, line)
388 else:
387 else:
389 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
388 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
390 line = tpl_line % (bp_mark_color + bp_mark, num, line)
389 line = tpl_line % (bp_mark_color + bp_mark, num, line)
391
390
392 return line
391 return line
393
392
394 def list_command_pydb(self, arg):
393 def list_command_pydb(self, arg):
395 """List command to use if we have a newer pydb installed"""
394 """List command to use if we have a newer pydb installed"""
396 filename, first, last = OldPdb.parse_list_cmd(self, arg)
395 filename, first, last = OldPdb.parse_list_cmd(self, arg)
397 if filename is not None:
396 if filename is not None:
398 self.print_list_lines(filename, first, last)
397 self.print_list_lines(filename, first, last)
399
398
400 def print_list_lines(self, filename, first, last):
399 def print_list_lines(self, filename, first, last):
401 """The printing (as opposed to the parsing part of a 'list'
400 """The printing (as opposed to the parsing part of a 'list'
402 command."""
401 command."""
403 try:
402 try:
404 Colors = self.color_scheme_table.active_colors
403 Colors = self.color_scheme_table.active_colors
405 ColorsNormal = Colors.Normal
404 ColorsNormal = Colors.Normal
406 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
405 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)
406 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
408 src = []
407 src = []
409 for lineno in range(first, last+1):
408 for lineno in range(first, last+1):
410 line = linecache.getline(filename, lineno)
409 line = linecache.getline(filename, lineno)
411 if not line:
410 if not line:
412 break
411 break
413
412
414 if lineno == self.curframe.f_lineno:
413 if lineno == self.curframe.f_lineno:
415 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
414 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
416 else:
415 else:
417 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
416 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
418
417
419 src.append(line)
418 src.append(line)
420 self.lineno = lineno
419 self.lineno = lineno
421
420
422 print >>IPython.utils.io.Term.cout, ''.join(src)
421 print >>io.stdout, ''.join(src)
423
422
424 except KeyboardInterrupt:
423 except KeyboardInterrupt:
425 pass
424 pass
426
425
427 def do_list(self, arg):
426 def do_list(self, arg):
428 self.lastcmd = 'list'
427 self.lastcmd = 'list'
429 last = None
428 last = None
430 if arg:
429 if arg:
431 try:
430 try:
432 x = eval(arg, {}, {})
431 x = eval(arg, {}, {})
433 if type(x) == type(()):
432 if type(x) == type(()):
434 first, last = x
433 first, last = x
435 first = int(first)
434 first = int(first)
436 last = int(last)
435 last = int(last)
437 if last < first:
436 if last < first:
438 # Assume it's a count
437 # Assume it's a count
439 last = first + last
438 last = first + last
440 else:
439 else:
441 first = max(1, int(x) - 5)
440 first = max(1, int(x) - 5)
442 except:
441 except:
443 print '*** Error in argument:', `arg`
442 print '*** Error in argument:', `arg`
444 return
443 return
445 elif self.lineno is None:
444 elif self.lineno is None:
446 first = max(1, self.curframe.f_lineno - 5)
445 first = max(1, self.curframe.f_lineno - 5)
447 else:
446 else:
448 first = self.lineno + 1
447 first = self.lineno + 1
449 if last is None:
448 if last is None:
450 last = first + 10
449 last = first + 10
451 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
450 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
452
451
453 # vds: >>
452 # vds: >>
454 lineno = first
453 lineno = first
455 filename = self.curframe.f_code.co_filename
454 filename = self.curframe.f_code.co_filename
456 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
455 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
457 # vds: <<
456 # vds: <<
458
457
459 do_l = do_list
458 do_l = do_list
460
459
461 def do_pdef(self, arg):
460 def do_pdef(self, arg):
462 """The debugger interface to magic_pdef"""
461 """The debugger interface to magic_pdef"""
463 namespaces = [('Locals', self.curframe.f_locals),
462 namespaces = [('Locals', self.curframe.f_locals),
464 ('Globals', self.curframe.f_globals)]
463 ('Globals', self.curframe.f_globals)]
465 self.shell.magic_pdef(arg, namespaces=namespaces)
464 self.shell.magic_pdef(arg, namespaces=namespaces)
466
465
467 def do_pdoc(self, arg):
466 def do_pdoc(self, arg):
468 """The debugger interface to magic_pdoc"""
467 """The debugger interface to magic_pdoc"""
469 namespaces = [('Locals', self.curframe.f_locals),
468 namespaces = [('Locals', self.curframe.f_locals),
470 ('Globals', self.curframe.f_globals)]
469 ('Globals', self.curframe.f_globals)]
471 self.shell.magic_pdoc(arg, namespaces=namespaces)
470 self.shell.magic_pdoc(arg, namespaces=namespaces)
472
471
473 def do_pinfo(self, arg):
472 def do_pinfo(self, arg):
474 """The debugger equivalant of ?obj"""
473 """The debugger equivalant of ?obj"""
475 namespaces = [('Locals', self.curframe.f_locals),
474 namespaces = [('Locals', self.curframe.f_locals),
476 ('Globals', self.curframe.f_globals)]
475 ('Globals', self.curframe.f_globals)]
477 self.shell.magic_pinfo("pinfo %s" % arg, namespaces=namespaces)
476 self.shell.magic_pinfo("pinfo %s" % arg, namespaces=namespaces)
478
477
479 def checkline(self, filename, lineno):
478 def checkline(self, filename, lineno):
480 """Check whether specified line seems to be executable.
479 """Check whether specified line seems to be executable.
481
480
482 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
481 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
483 line or EOF). Warning: testing is not comprehensive.
482 line or EOF). Warning: testing is not comprehensive.
484 """
483 """
485 #######################################################################
484 #######################################################################
486 # XXX Hack! Use python-2.5 compatible code for this call, because with
485 # 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,
486 # all of our changes, we've drifted from the pdb api in 2.6. For now,
488 # changing:
487 # changing:
489 #
488 #
490 #line = linecache.getline(filename, lineno, self.curframe.f_globals)
489 #line = linecache.getline(filename, lineno, self.curframe.f_globals)
491 # to:
490 # to:
492 #
491 #
493 line = linecache.getline(filename, lineno)
492 line = linecache.getline(filename, lineno)
494 #
493 #
495 # does the trick. But in reality, we need to fix this by reconciling
494 # 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.
495 # our updates with the new Pdb APIs in Python 2.6.
497 #
496 #
498 # End hack. The rest of this method is copied verbatim from 2.6 pdb.py
497 # End hack. The rest of this method is copied verbatim from 2.6 pdb.py
499 #######################################################################
498 #######################################################################
500
499
501 if not line:
500 if not line:
502 print >>self.stdout, 'End of file'
501 print >>self.stdout, 'End of file'
503 return 0
502 return 0
504 line = line.strip()
503 line = line.strip()
505 # Don't allow setting breakpoint at a blank line
504 # Don't allow setting breakpoint at a blank line
506 if (not line or (line[0] == '#') or
505 if (not line or (line[0] == '#') or
507 (line[:3] == '"""') or line[:3] == "'''"):
506 (line[:3] == '"""') or line[:3] == "'''"):
508 print >>self.stdout, '*** Blank or comment'
507 print >>self.stdout, '*** Blank or comment'
509 return 0
508 return 0
510 return lineno
509 return lineno
@@ -1,330 +1,329 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Displayhook for IPython.
2 """Displayhook for IPython.
3
3
4 This defines a callable class that IPython uses for `sys.displayhook`.
4 This defines a callable class that IPython uses for `sys.displayhook`.
5
5
6 Authors:
6 Authors:
7
7
8 * Fernando Perez
8 * Fernando Perez
9 * Brian Granger
9 * Brian Granger
10 * Robert Kern
10 * Robert Kern
11 """
11 """
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Copyright (C) 2008-2010 The IPython Development Team
14 # Copyright (C) 2008-2010 The IPython Development Team
15 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
15 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
16 #
16 #
17 # Distributed under the terms of the BSD License. The full license is in
17 # Distributed under the terms of the BSD License. The full license is in
18 # the file COPYING, distributed as part of this software.
18 # the file COPYING, distributed as part of this software.
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Imports
22 # Imports
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 import __builtin__
25 import __builtin__
26
26
27 from IPython.config.configurable import Configurable
27 from IPython.config.configurable import Configurable
28 from IPython.core import prompts
28 from IPython.core import prompts
29 import IPython.utils.generics
29 from IPython.utils import io
30 import IPython.utils.io
31 from IPython.utils.traitlets import Instance, List
30 from IPython.utils.traitlets import Instance, List
32 from IPython.utils.warn import warn
31 from IPython.utils.warn import warn
33
32
34 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
35 # Main displayhook class
34 # Main displayhook class
36 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
37
36
38 # TODO: The DisplayHook class should be split into two classes, one that
37 # TODO: The DisplayHook class should be split into two classes, one that
39 # manages the prompts and their synchronization and another that just does the
38 # manages the prompts and their synchronization and another that just does the
40 # displayhook logic and calls into the prompt manager.
39 # displayhook logic and calls into the prompt manager.
41
40
42 # TODO: Move the various attributes (cache_size, colors, input_sep,
41 # TODO: Move the various attributes (cache_size, colors, input_sep,
43 # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also
42 # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also
44 # attributes of InteractiveShell. They should be on ONE object only and the
43 # attributes of InteractiveShell. They should be on ONE object only and the
45 # other objects should ask that one object for their values.
44 # other objects should ask that one object for their values.
46
45
47 class DisplayHook(Configurable):
46 class DisplayHook(Configurable):
48 """The custom IPython displayhook to replace sys.displayhook.
47 """The custom IPython displayhook to replace sys.displayhook.
49
48
50 This class does many things, but the basic idea is that it is a callable
49 This class does many things, but the basic idea is that it is a callable
51 that gets called anytime user code returns a value.
50 that gets called anytime user code returns a value.
52
51
53 Currently this class does more than just the displayhook logic and that
52 Currently this class does more than just the displayhook logic and that
54 extra logic should eventually be moved out of here.
53 extra logic should eventually be moved out of here.
55 """
54 """
56
55
57 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
56 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
58
57
59 def __init__(self, shell=None, cache_size=1000,
58 def __init__(self, shell=None, cache_size=1000,
60 colors='NoColor', input_sep='\n',
59 colors='NoColor', input_sep='\n',
61 output_sep='\n', output_sep2='',
60 output_sep='\n', output_sep2='',
62 ps1 = None, ps2 = None, ps_out = None, pad_left=True,
61 ps1 = None, ps2 = None, ps_out = None, pad_left=True,
63 config=None):
62 config=None):
64 super(DisplayHook, self).__init__(shell=shell, config=config)
63 super(DisplayHook, self).__init__(shell=shell, config=config)
65
64
66 cache_size_min = 3
65 cache_size_min = 3
67 if cache_size <= 0:
66 if cache_size <= 0:
68 self.do_full_cache = 0
67 self.do_full_cache = 0
69 cache_size = 0
68 cache_size = 0
70 elif cache_size < cache_size_min:
69 elif cache_size < cache_size_min:
71 self.do_full_cache = 0
70 self.do_full_cache = 0
72 cache_size = 0
71 cache_size = 0
73 warn('caching was disabled (min value for cache size is %s).' %
72 warn('caching was disabled (min value for cache size is %s).' %
74 cache_size_min,level=3)
73 cache_size_min,level=3)
75 else:
74 else:
76 self.do_full_cache = 1
75 self.do_full_cache = 1
77
76
78 self.cache_size = cache_size
77 self.cache_size = cache_size
79 self.input_sep = input_sep
78 self.input_sep = input_sep
80
79
81 # we need a reference to the user-level namespace
80 # we need a reference to the user-level namespace
82 self.shell = shell
81 self.shell = shell
83
82
84 # Set input prompt strings and colors
83 # Set input prompt strings and colors
85 if cache_size == 0:
84 if cache_size == 0:
86 if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
85 if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
87 or ps1.find(r'\N') > -1:
86 or ps1.find(r'\N') > -1:
88 ps1 = '>>> '
87 ps1 = '>>> '
89 if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
88 if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
90 or ps2.find(r'\N') > -1:
89 or ps2.find(r'\N') > -1:
91 ps2 = '... '
90 ps2 = '... '
92 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
91 self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
93 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
92 self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
94 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
93 self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
95
94
96 self.color_table = prompts.PromptColors
95 self.color_table = prompts.PromptColors
97 self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str,
96 self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str,
98 pad_left=pad_left)
97 pad_left=pad_left)
99 self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
98 self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
100 self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str,
99 self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str,
101 pad_left=pad_left)
100 pad_left=pad_left)
102 self.set_colors(colors)
101 self.set_colors(colors)
103
102
104 # Store the last prompt string each time, we need it for aligning
103 # Store the last prompt string each time, we need it for aligning
105 # continuation and auto-rewrite prompts
104 # continuation and auto-rewrite prompts
106 self.last_prompt = ''
105 self.last_prompt = ''
107 self.output_sep = output_sep
106 self.output_sep = output_sep
108 self.output_sep2 = output_sep2
107 self.output_sep2 = output_sep2
109 self._,self.__,self.___ = '','',''
108 self._,self.__,self.___ = '','',''
110
109
111 # these are deliberately global:
110 # these are deliberately global:
112 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
111 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
113 self.shell.user_ns.update(to_user_ns)
112 self.shell.user_ns.update(to_user_ns)
114
113
115 @property
114 @property
116 def prompt_count(self):
115 def prompt_count(self):
117 return self.shell.execution_count
116 return self.shell.execution_count
118
117
119 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
118 def _set_prompt_str(self,p_str,cache_def,no_cache_def):
120 if p_str is None:
119 if p_str is None:
121 if self.do_full_cache:
120 if self.do_full_cache:
122 return cache_def
121 return cache_def
123 else:
122 else:
124 return no_cache_def
123 return no_cache_def
125 else:
124 else:
126 return p_str
125 return p_str
127
126
128 def set_colors(self, colors):
127 def set_colors(self, colors):
129 """Set the active color scheme and configure colors for the three
128 """Set the active color scheme and configure colors for the three
130 prompt subsystems."""
129 prompt subsystems."""
131
130
132 # FIXME: This modifying of the global prompts.prompt_specials needs
131 # FIXME: This modifying of the global prompts.prompt_specials needs
133 # to be fixed. We need to refactor all of the prompts stuff to use
132 # to be fixed. We need to refactor all of the prompts stuff to use
134 # proper configuration and traits notifications.
133 # proper configuration and traits notifications.
135 if colors.lower()=='nocolor':
134 if colors.lower()=='nocolor':
136 prompts.prompt_specials = prompts.prompt_specials_nocolor
135 prompts.prompt_specials = prompts.prompt_specials_nocolor
137 else:
136 else:
138 prompts.prompt_specials = prompts.prompt_specials_color
137 prompts.prompt_specials = prompts.prompt_specials_color
139
138
140 self.color_table.set_active_scheme(colors)
139 self.color_table.set_active_scheme(colors)
141 self.prompt1.set_colors()
140 self.prompt1.set_colors()
142 self.prompt2.set_colors()
141 self.prompt2.set_colors()
143 self.prompt_out.set_colors()
142 self.prompt_out.set_colors()
144
143
145 #-------------------------------------------------------------------------
144 #-------------------------------------------------------------------------
146 # Methods used in __call__. Override these methods to modify the behavior
145 # Methods used in __call__. Override these methods to modify the behavior
147 # of the displayhook.
146 # of the displayhook.
148 #-------------------------------------------------------------------------
147 #-------------------------------------------------------------------------
149
148
150 def check_for_underscore(self):
149 def check_for_underscore(self):
151 """Check if the user has set the '_' variable by hand."""
150 """Check if the user has set the '_' variable by hand."""
152 # If something injected a '_' variable in __builtin__, delete
151 # If something injected a '_' variable in __builtin__, delete
153 # ipython's automatic one so we don't clobber that. gettext() in
152 # ipython's automatic one so we don't clobber that. gettext() in
154 # particular uses _, so we need to stay away from it.
153 # particular uses _, so we need to stay away from it.
155 if '_' in __builtin__.__dict__:
154 if '_' in __builtin__.__dict__:
156 try:
155 try:
157 del self.shell.user_ns['_']
156 del self.shell.user_ns['_']
158 except KeyError:
157 except KeyError:
159 pass
158 pass
160
159
161 def quiet(self):
160 def quiet(self):
162 """Should we silence the display hook because of ';'?"""
161 """Should we silence the display hook because of ';'?"""
163 # do not print output if input ends in ';'
162 # do not print output if input ends in ';'
164 try:
163 try:
165 cell = self.shell.history_manager.input_hist_parsed[self.prompt_count]
164 cell = self.shell.history_manager.input_hist_parsed[self.prompt_count]
166 if cell.rstrip().endswith(';'):
165 if cell.rstrip().endswith(';'):
167 return True
166 return True
168 except IndexError:
167 except IndexError:
169 # some uses of ipshellembed may fail here
168 # some uses of ipshellembed may fail here
170 pass
169 pass
171 return False
170 return False
172
171
173 def start_displayhook(self):
172 def start_displayhook(self):
174 """Start the displayhook, initializing resources."""
173 """Start the displayhook, initializing resources."""
175 pass
174 pass
176
175
177 def write_output_prompt(self):
176 def write_output_prompt(self):
178 """Write the output prompt.
177 """Write the output prompt.
179
178
180 The default implementation simply writes the prompt to
179 The default implementation simply writes the prompt to
181 ``io.Term.cout``.
180 ``io.stdout``.
182 """
181 """
183 # Use write, not print which adds an extra space.
182 # Use write, not print which adds an extra space.
184 IPython.utils.io.Term.cout.write(self.output_sep)
183 io.stdout.write(self.output_sep)
185 outprompt = str(self.prompt_out)
184 outprompt = str(self.prompt_out)
186 if self.do_full_cache:
185 if self.do_full_cache:
187 IPython.utils.io.Term.cout.write(outprompt)
186 io.stdout.write(outprompt)
188
187
189 def compute_format_data(self, result):
188 def compute_format_data(self, result):
190 """Compute format data of the object to be displayed.
189 """Compute format data of the object to be displayed.
191
190
192 The format data is a generalization of the :func:`repr` of an object.
191 The format data is a generalization of the :func:`repr` of an object.
193 In the default implementation the format data is a :class:`dict` of
192 In the default implementation the format data is a :class:`dict` of
194 key value pair where the keys are valid MIME types and the values
193 key value pair where the keys are valid MIME types and the values
195 are JSON'able data structure containing the raw data for that MIME
194 are JSON'able data structure containing the raw data for that MIME
196 type. It is up to frontends to determine pick a MIME to to use and
195 type. It is up to frontends to determine pick a MIME to to use and
197 display that data in an appropriate manner.
196 display that data in an appropriate manner.
198
197
199 This method only computes the format data for the object and should
198 This method only computes the format data for the object and should
200 NOT actually print or write that to a stream.
199 NOT actually print or write that to a stream.
201
200
202 Parameters
201 Parameters
203 ----------
202 ----------
204 result : object
203 result : object
205 The Python object passed to the display hook, whose format will be
204 The Python object passed to the display hook, whose format will be
206 computed.
205 computed.
207
206
208 Returns
207 Returns
209 -------
208 -------
210 format_data : dict
209 format_data : dict
211 A :class:`dict` whose keys are valid MIME types and values are
210 A :class:`dict` whose keys are valid MIME types and values are
212 JSON'able raw data for that MIME type. It is recommended that
211 JSON'able raw data for that MIME type. It is recommended that
213 all return values of this should always include the "text/plain"
212 all return values of this should always include the "text/plain"
214 MIME type representation of the object.
213 MIME type representation of the object.
215 """
214 """
216 return self.shell.display_formatter.format(result)
215 return self.shell.display_formatter.format(result)
217
216
218 def write_format_data(self, format_dict):
217 def write_format_data(self, format_dict):
219 """Write the format data dict to the frontend.
218 """Write the format data dict to the frontend.
220
219
221 This default version of this method simply writes the plain text
220 This default version of this method simply writes the plain text
222 representation of the object to ``io.Term.cout``. Subclasses should
221 representation of the object to ``io.stdout``. Subclasses should
223 override this method to send the entire `format_dict` to the
222 override this method to send the entire `format_dict` to the
224 frontends.
223 frontends.
225
224
226 Parameters
225 Parameters
227 ----------
226 ----------
228 format_dict : dict
227 format_dict : dict
229 The format dict for the object passed to `sys.displayhook`.
228 The format dict for the object passed to `sys.displayhook`.
230 """
229 """
231 # We want to print because we want to always make sure we have a
230 # We want to print because we want to always make sure we have a
232 # newline, even if all the prompt separators are ''. This is the
231 # newline, even if all the prompt separators are ''. This is the
233 # standard IPython behavior.
232 # standard IPython behavior.
234 result_repr = format_dict['text/plain']
233 result_repr = format_dict['text/plain']
235 if '\n' in result_repr:
234 if '\n' in result_repr:
236 # So that multi-line strings line up with the left column of
235 # So that multi-line strings line up with the left column of
237 # the screen, instead of having the output prompt mess up
236 # the screen, instead of having the output prompt mess up
238 # their first line.
237 # their first line.
239 # We use the ps_out_str template instead of the expanded prompt
238 # We use the ps_out_str template instead of the expanded prompt
240 # because the expansion may add ANSI escapes that will interfere
239 # because the expansion may add ANSI escapes that will interfere
241 # with our ability to determine whether or not we should add
240 # with our ability to determine whether or not we should add
242 # a newline.
241 # a newline.
243 if self.ps_out_str and not self.ps_out_str.endswith('\n'):
242 if self.ps_out_str and not self.ps_out_str.endswith('\n'):
244 # But avoid extraneous empty lines.
243 # But avoid extraneous empty lines.
245 result_repr = '\n' + result_repr
244 result_repr = '\n' + result_repr
246
245
247 print >>IPython.utils.io.Term.cout, result_repr
246 print >>io.stdout, result_repr
248
247
249 def update_user_ns(self, result):
248 def update_user_ns(self, result):
250 """Update user_ns with various things like _, __, _1, etc."""
249 """Update user_ns with various things like _, __, _1, etc."""
251
250
252 # Avoid recursive reference when displaying _oh/Out
251 # Avoid recursive reference when displaying _oh/Out
253 if result is not self.shell.user_ns['_oh']:
252 if result is not self.shell.user_ns['_oh']:
254 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
253 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
255 warn('Output cache limit (currently '+
254 warn('Output cache limit (currently '+
256 `self.cache_size`+' entries) hit.\n'
255 `self.cache_size`+' entries) hit.\n'
257 'Flushing cache and resetting history counter...\n'
256 'Flushing cache and resetting history counter...\n'
258 'The only history variables available will be _,__,___ and _1\n'
257 'The only history variables available will be _,__,___ and _1\n'
259 'with the current result.')
258 'with the current result.')
260
259
261 self.flush()
260 self.flush()
262 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
261 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
263 # we cause buggy behavior for things like gettext).
262 # we cause buggy behavior for things like gettext).
264
263
265 if '_' not in __builtin__.__dict__:
264 if '_' not in __builtin__.__dict__:
266 self.___ = self.__
265 self.___ = self.__
267 self.__ = self._
266 self.__ = self._
268 self._ = result
267 self._ = result
269 self.shell.user_ns.update({'_':self._,
268 self.shell.user_ns.update({'_':self._,
270 '__':self.__,
269 '__':self.__,
271 '___':self.___})
270 '___':self.___})
272
271
273 # hackish access to top-level namespace to create _1,_2... dynamically
272 # hackish access to top-level namespace to create _1,_2... dynamically
274 to_main = {}
273 to_main = {}
275 if self.do_full_cache:
274 if self.do_full_cache:
276 new_result = '_'+`self.prompt_count`
275 new_result = '_'+`self.prompt_count`
277 to_main[new_result] = result
276 to_main[new_result] = result
278 self.shell.user_ns.update(to_main)
277 self.shell.user_ns.update(to_main)
279 self.shell.user_ns['_oh'][self.prompt_count] = result
278 self.shell.user_ns['_oh'][self.prompt_count] = result
280
279
281 def log_output(self, format_dict):
280 def log_output(self, format_dict):
282 """Log the output."""
281 """Log the output."""
283 if self.shell.logger.log_output:
282 if self.shell.logger.log_output:
284 self.shell.logger.log_write(format_dict['text/plain'], 'output')
283 self.shell.logger.log_write(format_dict['text/plain'], 'output')
285 self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
284 self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
286 format_dict['text/plain']
285 format_dict['text/plain']
287
286
288 def finish_displayhook(self):
287 def finish_displayhook(self):
289 """Finish up all displayhook activities."""
288 """Finish up all displayhook activities."""
290 IPython.utils.io.Term.cout.write(self.output_sep2)
289 io.stdout.write(self.output_sep2)
291 IPython.utils.io.Term.cout.flush()
290 io.stdout.flush()
292
291
293 def __call__(self, result=None):
292 def __call__(self, result=None):
294 """Printing with history cache management.
293 """Printing with history cache management.
295
294
296 This is invoked everytime the interpreter needs to print, and is
295 This is invoked everytime the interpreter needs to print, and is
297 activated by setting the variable sys.displayhook to it.
296 activated by setting the variable sys.displayhook to it.
298 """
297 """
299 self.check_for_underscore()
298 self.check_for_underscore()
300 if result is not None and not self.quiet():
299 if result is not None and not self.quiet():
301 self.start_displayhook()
300 self.start_displayhook()
302 self.write_output_prompt()
301 self.write_output_prompt()
303 format_dict = self.compute_format_data(result)
302 format_dict = self.compute_format_data(result)
304 self.write_format_data(format_dict)
303 self.write_format_data(format_dict)
305 self.update_user_ns(result)
304 self.update_user_ns(result)
306 self.log_output(format_dict)
305 self.log_output(format_dict)
307 self.finish_displayhook()
306 self.finish_displayhook()
308
307
309 def flush(self):
308 def flush(self):
310 if not self.do_full_cache:
309 if not self.do_full_cache:
311 raise ValueError,"You shouldn't have reached the cache flush "\
310 raise ValueError,"You shouldn't have reached the cache flush "\
312 "if full caching is not enabled!"
311 "if full caching is not enabled!"
313 # delete auto-generated vars from global namespace
312 # delete auto-generated vars from global namespace
314
313
315 for n in range(1,self.prompt_count + 1):
314 for n in range(1,self.prompt_count + 1):
316 key = '_'+`n`
315 key = '_'+`n`
317 try:
316 try:
318 del self.shell.user_ns[key]
317 del self.shell.user_ns[key]
319 except: pass
318 except: pass
320 self.shell.user_ns['_oh'].clear()
319 self.shell.user_ns['_oh'].clear()
321
320
322 # Release our own references to objects:
321 # Release our own references to objects:
323 self._, self.__, self.___ = '', '', ''
322 self._, self.__, self.___ = '', '', ''
324
323
325 if '_' not in __builtin__.__dict__:
324 if '_' not in __builtin__.__dict__:
326 self.shell.user_ns.update({'_':None,'__':None, '___':None})
325 self.shell.user_ns.update({'_':None,'__':None, '___':None})
327 import gc
326 import gc
328 # TODO: Is this really needed?
327 # TODO: Is this really needed?
329 gc.collect()
328 gc.collect()
330
329
@@ -1,145 +1,145 b''
1 """An interface for publishing rich data to frontends.
1 """An interface for publishing rich data to frontends.
2
2
3 There are two components of the display system:
3 There are two components of the display system:
4
4
5 * Display formatters, which take a Python object and compute the
5 * Display formatters, which take a Python object and compute the
6 representation of the object in various formats (text, HTML, SVg, etc.).
6 representation of the object in various formats (text, HTML, SVg, etc.).
7 * The display publisher that is used to send the representation data to the
7 * The display publisher that is used to send the representation data to the
8 various frontends.
8 various frontends.
9
9
10 This module defines the logic display publishing. The display publisher uses
10 This module defines the logic display publishing. The display publisher uses
11 the ``display_data`` message type that is defined in the IPython messaging
11 the ``display_data`` message type that is defined in the IPython messaging
12 spec.
12 spec.
13
13
14 Authors:
14 Authors:
15
15
16 * Brian Granger
16 * Brian Granger
17 """
17 """
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Copyright (C) 2008-2010 The IPython Development Team
20 # Copyright (C) 2008-2010 The IPython Development Team
21 #
21 #
22 # Distributed under the terms of the BSD License. The full license is in
22 # Distributed under the terms of the BSD License. The full license is in
23 # the file COPYING, distributed as part of this software.
23 # the file COPYING, distributed as part of this software.
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Imports
27 # Imports
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 from __future__ import print_function
30 from __future__ import print_function
31
31
32 from IPython.config.configurable import Configurable
32 from IPython.config.configurable import Configurable
33
33
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35 # Main payload class
35 # Main payload class
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37
37
38 class DisplayPublisher(Configurable):
38 class DisplayPublisher(Configurable):
39 """A traited class that publishes display data to frontends.
39 """A traited class that publishes display data to frontends.
40
40
41 Instances of this class are created by the main IPython object and should
41 Instances of this class are created by the main IPython object and should
42 be accessed there.
42 be accessed there.
43 """
43 """
44
44
45 def _validate_data(self, source, data, metadata=None):
45 def _validate_data(self, source, data, metadata=None):
46 """Validate the display data.
46 """Validate the display data.
47
47
48 Parameters
48 Parameters
49 ----------
49 ----------
50 source : str
50 source : str
51 The fully dotted name of the callable that created the data, like
51 The fully dotted name of the callable that created the data, like
52 :func:`foo.bar.my_formatter`.
52 :func:`foo.bar.my_formatter`.
53 data : dict
53 data : dict
54 The formata data dictionary.
54 The formata data dictionary.
55 metadata : dict
55 metadata : dict
56 Any metadata for the data.
56 Any metadata for the data.
57 """
57 """
58
58
59 if not isinstance(source, str):
59 if not isinstance(source, str):
60 raise TypeError('source must be a str, got: %r' % source)
60 raise TypeError('source must be a str, got: %r' % source)
61 if not isinstance(data, dict):
61 if not isinstance(data, dict):
62 raise TypeError('data must be a dict, got: %r' % data)
62 raise TypeError('data must be a dict, got: %r' % data)
63 if metadata is not None:
63 if metadata is not None:
64 if not isinstance(metadata, dict):
64 if not isinstance(metadata, dict):
65 raise TypeError('metadata must be a dict, got: %r' % data)
65 raise TypeError('metadata must be a dict, got: %r' % data)
66
66
67 def publish(self, source, data, metadata=None):
67 def publish(self, source, data, metadata=None):
68 """Publish data and metadata to all frontends.
68 """Publish data and metadata to all frontends.
69
69
70 See the ``display_data`` message in the messaging documentation for
70 See the ``display_data`` message in the messaging documentation for
71 more details about this message type.
71 more details about this message type.
72
72
73 The following MIME types are currently implemented:
73 The following MIME types are currently implemented:
74
74
75 * text/plain
75 * text/plain
76 * text/html
76 * text/html
77 * text/latex
77 * text/latex
78 * application/json
78 * application/json
79 * image/png
79 * image/png
80 * immage/svg+xml
80 * immage/svg+xml
81
81
82 Parameters
82 Parameters
83 ----------
83 ----------
84 source : str
84 source : str
85 A string that give the function or method that created the data,
85 A string that give the function or method that created the data,
86 such as 'IPython.core.page'.
86 such as 'IPython.core.page'.
87 data : dict
87 data : dict
88 A dictionary having keys that are valid MIME types (like
88 A dictionary having keys that are valid MIME types (like
89 'text/plain' or 'image/svg+xml') and values that are the data for
89 'text/plain' or 'image/svg+xml') and values that are the data for
90 that MIME type. The data itself must be a JSON'able data
90 that MIME type. The data itself must be a JSON'able data
91 structure. Minimally all data should have the 'text/plain' data,
91 structure. Minimally all data should have the 'text/plain' data,
92 which can be displayed by all frontends. If more than the plain
92 which can be displayed by all frontends. If more than the plain
93 text is given, it is up to the frontend to decide which
93 text is given, it is up to the frontend to decide which
94 representation to use.
94 representation to use.
95 metadata : dict
95 metadata : dict
96 A dictionary for metadata related to the data. This can contain
96 A dictionary for metadata related to the data. This can contain
97 arbitrary key, value pairs that frontends can use to interpret
97 arbitrary key, value pairs that frontends can use to interpret
98 the data.
98 the data.
99 """
99 """
100 from IPython.utils import io
100 from IPython.utils import io
101 # The default is to simply write the plain text data using io.Term.
101 # The default is to simply write the plain text data using io.stdout.
102 if data.has_key('text/plain'):
102 if data.has_key('text/plain'):
103 print(data['text/plain'], file=io.Term.cout)
103 print(data['text/plain'], file=io.stdout)
104
104
105
105
106 def publish_display_data(self, source, data, metadata=None):
106 def publish_display_data(self, source, data, metadata=None):
107 """Publish data and metadata to all frontends.
107 """Publish data and metadata to all frontends.
108
108
109 See the ``display_data`` message in the messaging documentation for
109 See the ``display_data`` message in the messaging documentation for
110 more details about this message type.
110 more details about this message type.
111
111
112 The following MIME types are currently implemented:
112 The following MIME types are currently implemented:
113
113
114 * text/plain
114 * text/plain
115 * text/html
115 * text/html
116 * text/latex
116 * text/latex
117 * application/json
117 * application/json
118 * image/png
118 * image/png
119 * immage/svg+xml
119 * immage/svg+xml
120
120
121 Parameters
121 Parameters
122 ----------
122 ----------
123 source : str
123 source : str
124 A string that give the function or method that created the data,
124 A string that give the function or method that created the data,
125 such as 'IPython.core.page'.
125 such as 'IPython.core.page'.
126 data : dict
126 data : dict
127 A dictionary having keys that are valid MIME types (like
127 A dictionary having keys that are valid MIME types (like
128 'text/plain' or 'image/svg+xml') and values that are the data for
128 'text/plain' or 'image/svg+xml') and values that are the data for
129 that MIME type. The data itself must be a JSON'able data
129 that MIME type. The data itself must be a JSON'able data
130 structure. Minimally all data should have the 'text/plain' data,
130 structure. Minimally all data should have the 'text/plain' data,
131 which can be displayed by all frontends. If more than the plain
131 which can be displayed by all frontends. If more than the plain
132 text is given, it is up to the frontend to decide which
132 text is given, it is up to the frontend to decide which
133 representation to use.
133 representation to use.
134 metadata : dict
134 metadata : dict
135 A dictionary for metadata related to the data. This can contain
135 A dictionary for metadata related to the data. This can contain
136 arbitrary key, value pairs that frontends can use to interpret
136 arbitrary key, value pairs that frontends can use to interpret
137 the data.
137 the data.
138 """
138 """
139 from IPython.core.interactiveshell import InteractiveShell
139 from IPython.core.interactiveshell import InteractiveShell
140 InteractiveShell.instance().display_pub.publish(
140 InteractiveShell.instance().display_pub.publish(
141 source,
141 source,
142 data,
142 data,
143 metadata
143 metadata
144 )
144 )
145
145
@@ -1,803 +1,802 b''
1 """ History related magics and functionality """
1 """ History related magics and functionality """
2 #-----------------------------------------------------------------------------
2 #-----------------------------------------------------------------------------
3 # Copyright (C) 2010 The IPython Development Team.
3 # Copyright (C) 2010 The IPython Development Team.
4 #
4 #
5 # Distributed under the terms of the BSD License.
5 # Distributed under the terms of the BSD License.
6 #
6 #
7 # The full license is in the file COPYING.txt, distributed with this software.
7 # The full license is in the file COPYING.txt, distributed with this software.
8 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Imports
11 # Imports
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 from __future__ import print_function
13 from __future__ import print_function
14
14
15 # Stdlib imports
15 # Stdlib imports
16 import atexit
16 import atexit
17 import datetime
17 import datetime
18 import os
18 import os
19 import re
19 import re
20 import sqlite3
20 import sqlite3
21 import threading
21 import threading
22
22
23 # Our own packages
23 # Our own packages
24 from IPython.config.configurable import Configurable
24 from IPython.config.configurable import Configurable
25 import IPython.utils.io
26
25
27 from IPython.testing import decorators as testdec
26 from IPython.testing import decorators as testdec
28 from IPython.utils.io import ask_yes_no
27 from IPython.utils import io
29 from IPython.utils.traitlets import Bool, Dict, Instance, Int, List, Unicode
28 from IPython.utils.traitlets import Bool, Dict, Instance, Int, List, Unicode
30 from IPython.utils.warn import warn
29 from IPython.utils.warn import warn
31
30
32 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
33 # Classes and functions
32 # Classes and functions
34 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
35
34
36 class HistoryManager(Configurable):
35 class HistoryManager(Configurable):
37 """A class to organize all history-related functionality in one place.
36 """A class to organize all history-related functionality in one place.
38 """
37 """
39 # Public interface
38 # Public interface
40
39
41 # An instance of the IPython shell we are attached to
40 # An instance of the IPython shell we are attached to
42 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
41 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
43 # Lists to hold processed and raw history. These start with a blank entry
42 # Lists to hold processed and raw history. These start with a blank entry
44 # so that we can index them starting from 1
43 # so that we can index them starting from 1
45 input_hist_parsed = List([""])
44 input_hist_parsed = List([""])
46 input_hist_raw = List([""])
45 input_hist_raw = List([""])
47 # A list of directories visited during session
46 # A list of directories visited during session
48 dir_hist = List()
47 dir_hist = List()
49 def _dir_hist_default(self):
48 def _dir_hist_default(self):
50 try:
49 try:
51 return [os.getcwd()]
50 return [os.getcwd()]
52 except OSError:
51 except OSError:
53 return []
52 return []
54
53
55 # A dict of output history, keyed with ints from the shell's
54 # A dict of output history, keyed with ints from the shell's
56 # execution count.
55 # execution count.
57 output_hist = Dict()
56 output_hist = Dict()
58 # The text/plain repr of outputs.
57 # The text/plain repr of outputs.
59 output_hist_reprs = Dict()
58 output_hist_reprs = Dict()
60
59
61 # String holding the path to the history file
60 # String holding the path to the history file
62 hist_file = Unicode(config=True)
61 hist_file = Unicode(config=True)
63
62
64 # The SQLite database
63 # The SQLite database
65 db = Instance(sqlite3.Connection)
64 db = Instance(sqlite3.Connection)
66 # The number of the current session in the history database
65 # The number of the current session in the history database
67 session_number = Int()
66 session_number = Int()
68 # Should we log output to the database? (default no)
67 # Should we log output to the database? (default no)
69 db_log_output = Bool(False, config=True)
68 db_log_output = Bool(False, config=True)
70 # Write to database every x commands (higher values save disk access & power)
69 # Write to database every x commands (higher values save disk access & power)
71 # Values of 1 or less effectively disable caching.
70 # Values of 1 or less effectively disable caching.
72 db_cache_size = Int(0, config=True)
71 db_cache_size = Int(0, config=True)
73 # The input and output caches
72 # The input and output caches
74 db_input_cache = List()
73 db_input_cache = List()
75 db_output_cache = List()
74 db_output_cache = List()
76
75
77 # History saving in separate thread
76 # History saving in separate thread
78 save_thread = Instance('IPython.core.history.HistorySavingThread')
77 save_thread = Instance('IPython.core.history.HistorySavingThread')
79 # N.B. Event is a function returning an instance of _Event.
78 # N.B. Event is a function returning an instance of _Event.
80 save_flag = Instance(threading._Event)
79 save_flag = Instance(threading._Event)
81
80
82 # Private interface
81 # Private interface
83 # Variables used to store the three last inputs from the user. On each new
82 # Variables used to store the three last inputs from the user. On each new
84 # history update, we populate the user's namespace with these, shifted as
83 # history update, we populate the user's namespace with these, shifted as
85 # necessary.
84 # necessary.
86 _i00 = Unicode(u'')
85 _i00 = Unicode(u'')
87 _i = Unicode(u'')
86 _i = Unicode(u'')
88 _ii = Unicode(u'')
87 _ii = Unicode(u'')
89 _iii = Unicode(u'')
88 _iii = Unicode(u'')
90
89
91 # A regex matching all forms of the exit command, so that we don't store
90 # A regex matching all forms of the exit command, so that we don't store
92 # them in the history (it's annoying to rewind the first entry and land on
91 # them in the history (it's annoying to rewind the first entry and land on
93 # an exit call).
92 # an exit call).
94 _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
93 _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$")
95
94
96 def __init__(self, shell, config=None, **traits):
95 def __init__(self, shell, config=None, **traits):
97 """Create a new history manager associated with a shell instance.
96 """Create a new history manager associated with a shell instance.
98 """
97 """
99 # We need a pointer back to the shell for various tasks.
98 # We need a pointer back to the shell for various tasks.
100 super(HistoryManager, self).__init__(shell=shell, config=config,
99 super(HistoryManager, self).__init__(shell=shell, config=config,
101 **traits)
100 **traits)
102
101
103 if self.hist_file == u'':
102 if self.hist_file == u'':
104 # No one has set the hist_file, yet.
103 # No one has set the hist_file, yet.
105 if shell.profile:
104 if shell.profile:
106 histfname = 'history-%s' % shell.profile
105 histfname = 'history-%s' % shell.profile
107 else:
106 else:
108 histfname = 'history'
107 histfname = 'history'
109 self.hist_file = os.path.join(shell.ipython_dir, histfname + '.sqlite')
108 self.hist_file = os.path.join(shell.ipython_dir, histfname + '.sqlite')
110
109
111 try:
110 try:
112 self.init_db()
111 self.init_db()
113 except sqlite3.DatabaseError:
112 except sqlite3.DatabaseError:
114 if os.path.isfile(self.hist_file):
113 if os.path.isfile(self.hist_file):
115 # Try to move the file out of the way.
114 # Try to move the file out of the way.
116 newpath = os.path.join(self.shell.ipython_dir, "hist-corrupt.sqlite")
115 newpath = os.path.join(self.shell.ipython_dir, "hist-corrupt.sqlite")
117 os.rename(self.hist_file, newpath)
116 os.rename(self.hist_file, newpath)
118 print("ERROR! History file wasn't a valid SQLite database.",
117 print("ERROR! History file wasn't a valid SQLite database.",
119 "It was moved to %s" % newpath, "and a new file created.")
118 "It was moved to %s" % newpath, "and a new file created.")
120 self.init_db()
119 self.init_db()
121 else:
120 else:
122 # The hist_file is probably :memory: or something else.
121 # The hist_file is probably :memory: or something else.
123 raise
122 raise
124
123
125 self.save_flag = threading.Event()
124 self.save_flag = threading.Event()
126 self.db_input_cache_lock = threading.Lock()
125 self.db_input_cache_lock = threading.Lock()
127 self.db_output_cache_lock = threading.Lock()
126 self.db_output_cache_lock = threading.Lock()
128 self.save_thread = HistorySavingThread(self)
127 self.save_thread = HistorySavingThread(self)
129 self.save_thread.start()
128 self.save_thread.start()
130
129
131 self.new_session()
130 self.new_session()
132
131
133
132
134 def init_db(self):
133 def init_db(self):
135 """Connect to the database, and create tables if necessary."""
134 """Connect to the database, and create tables if necessary."""
136 self.db = sqlite3.connect(self.hist_file)
135 self.db = sqlite3.connect(self.hist_file)
137 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
136 self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
138 primary key autoincrement, start timestamp,
137 primary key autoincrement, start timestamp,
139 end timestamp, num_cmds integer, remark text)""")
138 end timestamp, num_cmds integer, remark text)""")
140 self.db.execute("""CREATE TABLE IF NOT EXISTS history
139 self.db.execute("""CREATE TABLE IF NOT EXISTS history
141 (session integer, line integer, source text, source_raw text,
140 (session integer, line integer, source text, source_raw text,
142 PRIMARY KEY (session, line))""")
141 PRIMARY KEY (session, line))""")
143 # Output history is optional, but ensure the table's there so it can be
142 # Output history is optional, but ensure the table's there so it can be
144 # enabled later.
143 # enabled later.
145 self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
144 self.db.execute("""CREATE TABLE IF NOT EXISTS output_history
146 (session integer, line integer, output text,
145 (session integer, line integer, output text,
147 PRIMARY KEY (session, line))""")
146 PRIMARY KEY (session, line))""")
148 self.db.commit()
147 self.db.commit()
149
148
150 def new_session(self, conn=None):
149 def new_session(self, conn=None):
151 """Get a new session number."""
150 """Get a new session number."""
152 if conn is None:
151 if conn is None:
153 conn = self.db
152 conn = self.db
154
153
155 with conn:
154 with conn:
156 cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
155 cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL,
157 NULL, "") """, (datetime.datetime.now(),))
156 NULL, "") """, (datetime.datetime.now(),))
158 self.session_number = cur.lastrowid
157 self.session_number = cur.lastrowid
159
158
160 def end_session(self):
159 def end_session(self):
161 """Close the database session, filling in the end time and line count."""
160 """Close the database session, filling in the end time and line count."""
162 self.writeout_cache()
161 self.writeout_cache()
163 with self.db:
162 with self.db:
164 self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
163 self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE
165 session==?""", (datetime.datetime.now(),
164 session==?""", (datetime.datetime.now(),
166 len(self.input_hist_parsed)-1, self.session_number))
165 len(self.input_hist_parsed)-1, self.session_number))
167 self.session_number = 0
166 self.session_number = 0
168
167
169 def name_session(self, name):
168 def name_session(self, name):
170 """Give the current session a name in the history database."""
169 """Give the current session a name in the history database."""
171 with self.db:
170 with self.db:
172 self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
171 self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
173 (name, self.session_number))
172 (name, self.session_number))
174
173
175 def reset(self, new_session=True):
174 def reset(self, new_session=True):
176 """Clear the session history, releasing all object references, and
175 """Clear the session history, releasing all object references, and
177 optionally open a new session."""
176 optionally open a new session."""
178 self.output_hist.clear()
177 self.output_hist.clear()
179 # The directory history can't be completely empty
178 # The directory history can't be completely empty
180 self.dir_hist[:] = [os.getcwd()]
179 self.dir_hist[:] = [os.getcwd()]
181
180
182 if new_session:
181 if new_session:
183 if self.session_number:
182 if self.session_number:
184 self.end_session()
183 self.end_session()
185 self.input_hist_parsed[:] = [""]
184 self.input_hist_parsed[:] = [""]
186 self.input_hist_raw[:] = [""]
185 self.input_hist_raw[:] = [""]
187 self.new_session()
186 self.new_session()
188
187
189 ## -------------------------------
188 ## -------------------------------
190 ## Methods for retrieving history:
189 ## Methods for retrieving history:
191 ## -------------------------------
190 ## -------------------------------
192 def _run_sql(self, sql, params, raw=True, output=False):
191 def _run_sql(self, sql, params, raw=True, output=False):
193 """Prepares and runs an SQL query for the history database.
192 """Prepares and runs an SQL query for the history database.
194
193
195 Parameters
194 Parameters
196 ----------
195 ----------
197 sql : str
196 sql : str
198 Any filtering expressions to go after SELECT ... FROM ...
197 Any filtering expressions to go after SELECT ... FROM ...
199 params : tuple
198 params : tuple
200 Parameters passed to the SQL query (to replace "?")
199 Parameters passed to the SQL query (to replace "?")
201 raw, output : bool
200 raw, output : bool
202 See :meth:`get_range`
201 See :meth:`get_range`
203
202
204 Returns
203 Returns
205 -------
204 -------
206 Tuples as :meth:`get_range`
205 Tuples as :meth:`get_range`
207 """
206 """
208 toget = 'source_raw' if raw else 'source'
207 toget = 'source_raw' if raw else 'source'
209 sqlfrom = "history"
208 sqlfrom = "history"
210 if output:
209 if output:
211 sqlfrom = "history LEFT JOIN output_history USING (session, line)"
210 sqlfrom = "history LEFT JOIN output_history USING (session, line)"
212 toget = "history.%s, output_history.output" % toget
211 toget = "history.%s, output_history.output" % toget
213 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
212 cur = self.db.execute("SELECT session, line, %s FROM %s " %\
214 (toget, sqlfrom) + sql, params)
213 (toget, sqlfrom) + sql, params)
215 if output: # Regroup into 3-tuples, and parse JSON
214 if output: # Regroup into 3-tuples, and parse JSON
216 return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)
215 return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur)
217 return cur
216 return cur
218
217
219
218
220 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
219 def get_tail(self, n=10, raw=True, output=False, include_latest=False):
221 """Get the last n lines from the history database.
220 """Get the last n lines from the history database.
222
221
223 Parameters
222 Parameters
224 ----------
223 ----------
225 n : int
224 n : int
226 The number of lines to get
225 The number of lines to get
227 raw, output : bool
226 raw, output : bool
228 See :meth:`get_range`
227 See :meth:`get_range`
229 include_latest : bool
228 include_latest : bool
230 If False (default), n+1 lines are fetched, and the latest one
229 If False (default), n+1 lines are fetched, and the latest one
231 is discarded. This is intended to be used where the function
230 is discarded. This is intended to be used where the function
232 is called by a user command, which it should not return.
231 is called by a user command, which it should not return.
233
232
234 Returns
233 Returns
235 -------
234 -------
236 Tuples as :meth:`get_range`
235 Tuples as :meth:`get_range`
237 """
236 """
238 self.writeout_cache()
237 self.writeout_cache()
239 if not include_latest:
238 if not include_latest:
240 n += 1
239 n += 1
241 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
240 cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?",
242 (n,), raw=raw, output=output)
241 (n,), raw=raw, output=output)
243 if not include_latest:
242 if not include_latest:
244 return reversed(list(cur)[1:])
243 return reversed(list(cur)[1:])
245 return reversed(list(cur))
244 return reversed(list(cur))
246
245
247 def search(self, pattern="*", raw=True, search_raw=True,
246 def search(self, pattern="*", raw=True, search_raw=True,
248 output=False):
247 output=False):
249 """Search the database using unix glob-style matching (wildcards
248 """Search the database using unix glob-style matching (wildcards
250 * and ?).
249 * and ?).
251
250
252 Parameters
251 Parameters
253 ----------
252 ----------
254 pattern : str
253 pattern : str
255 The wildcarded pattern to match when searching
254 The wildcarded pattern to match when searching
256 search_raw : bool
255 search_raw : bool
257 If True, search the raw input, otherwise, the parsed input
256 If True, search the raw input, otherwise, the parsed input
258 raw, output : bool
257 raw, output : bool
259 See :meth:`get_range`
258 See :meth:`get_range`
260
259
261 Returns
260 Returns
262 -------
261 -------
263 Tuples as :meth:`get_range`
262 Tuples as :meth:`get_range`
264 """
263 """
265 tosearch = "source_raw" if search_raw else "source"
264 tosearch = "source_raw" if search_raw else "source"
266 if output:
265 if output:
267 tosearch = "history." + tosearch
266 tosearch = "history." + tosearch
268 self.writeout_cache()
267 self.writeout_cache()
269 return self._run_sql("WHERE %s GLOB ?" % tosearch, (pattern,),
268 return self._run_sql("WHERE %s GLOB ?" % tosearch, (pattern,),
270 raw=raw, output=output)
269 raw=raw, output=output)
271
270
272 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
271 def _get_range_session(self, start=1, stop=None, raw=True, output=False):
273 """Get input and output history from the current session. Called by
272 """Get input and output history from the current session. Called by
274 get_range, and takes similar parameters."""
273 get_range, and takes similar parameters."""
275 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
274 input_hist = self.input_hist_raw if raw else self.input_hist_parsed
276
275
277 n = len(input_hist)
276 n = len(input_hist)
278 if start < 0:
277 if start < 0:
279 start += n
278 start += n
280 if not stop:
279 if not stop:
281 stop = n
280 stop = n
282 elif stop < 0:
281 elif stop < 0:
283 stop += n
282 stop += n
284
283
285 for i in range(start, stop):
284 for i in range(start, stop):
286 if output:
285 if output:
287 line = (input_hist[i], self.output_hist_reprs.get(i))
286 line = (input_hist[i], self.output_hist_reprs.get(i))
288 else:
287 else:
289 line = input_hist[i]
288 line = input_hist[i]
290 yield (0, i, line)
289 yield (0, i, line)
291
290
292 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
291 def get_range(self, session=0, start=1, stop=None, raw=True,output=False):
293 """Retrieve input by session.
292 """Retrieve input by session.
294
293
295 Parameters
294 Parameters
296 ----------
295 ----------
297 session : int
296 session : int
298 Session number to retrieve. The current session is 0, and negative
297 Session number to retrieve. The current session is 0, and negative
299 numbers count back from current session, so -1 is previous session.
298 numbers count back from current session, so -1 is previous session.
300 start : int
299 start : int
301 First line to retrieve.
300 First line to retrieve.
302 stop : int
301 stop : int
303 End of line range (excluded from output itself). If None, retrieve
302 End of line range (excluded from output itself). If None, retrieve
304 to the end of the session.
303 to the end of the session.
305 raw : bool
304 raw : bool
306 If True, return untranslated input
305 If True, return untranslated input
307 output : bool
306 output : bool
308 If True, attempt to include output. This will be 'real' Python
307 If True, attempt to include output. This will be 'real' Python
309 objects for the current session, or text reprs from previous
308 objects for the current session, or text reprs from previous
310 sessions if db_log_output was enabled at the time. Where no output
309 sessions if db_log_output was enabled at the time. Where no output
311 is found, None is used.
310 is found, None is used.
312
311
313 Returns
312 Returns
314 -------
313 -------
315 An iterator over the desired lines. Each line is a 3-tuple, either
314 An iterator over the desired lines. Each line is a 3-tuple, either
316 (session, line, input) if output is False, or
315 (session, line, input) if output is False, or
317 (session, line, (input, output)) if output is True.
316 (session, line, (input, output)) if output is True.
318 """
317 """
319 if session == 0 or session==self.session_number: # Current session
318 if session == 0 or session==self.session_number: # Current session
320 return self._get_range_session(start, stop, raw, output)
319 return self._get_range_session(start, stop, raw, output)
321 if session < 0:
320 if session < 0:
322 session += self.session_number
321 session += self.session_number
323
322
324 if stop:
323 if stop:
325 lineclause = "line >= ? AND line < ?"
324 lineclause = "line >= ? AND line < ?"
326 params = (session, start, stop)
325 params = (session, start, stop)
327 else:
326 else:
328 lineclause = "line>=?"
327 lineclause = "line>=?"
329 params = (session, start)
328 params = (session, start)
330
329
331 return self._run_sql("WHERE session==? AND %s""" % lineclause,
330 return self._run_sql("WHERE session==? AND %s""" % lineclause,
332 params, raw=raw, output=output)
331 params, raw=raw, output=output)
333
332
334 def get_range_by_str(self, rangestr, raw=True, output=False):
333 def get_range_by_str(self, rangestr, raw=True, output=False):
335 """Get lines of history from a string of ranges, as used by magic
334 """Get lines of history from a string of ranges, as used by magic
336 commands %hist, %save, %macro, etc.
335 commands %hist, %save, %macro, etc.
337
336
338 Parameters
337 Parameters
339 ----------
338 ----------
340 rangestr : str
339 rangestr : str
341 A string specifying ranges, e.g. "5 ~2/1-4". See
340 A string specifying ranges, e.g. "5 ~2/1-4". See
342 :func:`magic_history` for full details.
341 :func:`magic_history` for full details.
343 raw, output : bool
342 raw, output : bool
344 As :meth:`get_range`
343 As :meth:`get_range`
345
344
346 Returns
345 Returns
347 -------
346 -------
348 Tuples as :meth:`get_range`
347 Tuples as :meth:`get_range`
349 """
348 """
350 for sess, s, e in extract_hist_ranges(rangestr):
349 for sess, s, e in extract_hist_ranges(rangestr):
351 for line in self.get_range(sess, s, e, raw=raw, output=output):
350 for line in self.get_range(sess, s, e, raw=raw, output=output):
352 yield line
351 yield line
353
352
354 ## ----------------------------
353 ## ----------------------------
355 ## Methods for storing history:
354 ## Methods for storing history:
356 ## ----------------------------
355 ## ----------------------------
357 def store_inputs(self, line_num, source, source_raw=None):
356 def store_inputs(self, line_num, source, source_raw=None):
358 """Store source and raw input in history and create input cache
357 """Store source and raw input in history and create input cache
359 variables _i*.
358 variables _i*.
360
359
361 Parameters
360 Parameters
362 ----------
361 ----------
363 line_num : int
362 line_num : int
364 The prompt number of this input.
363 The prompt number of this input.
365
364
366 source : str
365 source : str
367 Python input.
366 Python input.
368
367
369 source_raw : str, optional
368 source_raw : str, optional
370 If given, this is the raw input without any IPython transformations
369 If given, this is the raw input without any IPython transformations
371 applied to it. If not given, ``source`` is used.
370 applied to it. If not given, ``source`` is used.
372 """
371 """
373 if source_raw is None:
372 if source_raw is None:
374 source_raw = source
373 source_raw = source
375 source = source.rstrip('\n')
374 source = source.rstrip('\n')
376 source_raw = source_raw.rstrip('\n')
375 source_raw = source_raw.rstrip('\n')
377
376
378 # do not store exit/quit commands
377 # do not store exit/quit commands
379 if self._exit_re.match(source_raw.strip()):
378 if self._exit_re.match(source_raw.strip()):
380 return
379 return
381
380
382 self.input_hist_parsed.append(source)
381 self.input_hist_parsed.append(source)
383 self.input_hist_raw.append(source_raw)
382 self.input_hist_raw.append(source_raw)
384
383
385 with self.db_input_cache_lock:
384 with self.db_input_cache_lock:
386 self.db_input_cache.append((line_num, source, source_raw))
385 self.db_input_cache.append((line_num, source, source_raw))
387 # Trigger to flush cache and write to DB.
386 # Trigger to flush cache and write to DB.
388 if len(self.db_input_cache) >= self.db_cache_size:
387 if len(self.db_input_cache) >= self.db_cache_size:
389 self.save_flag.set()
388 self.save_flag.set()
390
389
391 # update the auto _i variables
390 # update the auto _i variables
392 self._iii = self._ii
391 self._iii = self._ii
393 self._ii = self._i
392 self._ii = self._i
394 self._i = self._i00
393 self._i = self._i00
395 self._i00 = source_raw
394 self._i00 = source_raw
396
395
397 # hackish access to user namespace to create _i1,_i2... dynamically
396 # hackish access to user namespace to create _i1,_i2... dynamically
398 new_i = '_i%s' % line_num
397 new_i = '_i%s' % line_num
399 to_main = {'_i': self._i,
398 to_main = {'_i': self._i,
400 '_ii': self._ii,
399 '_ii': self._ii,
401 '_iii': self._iii,
400 '_iii': self._iii,
402 new_i : self._i00 }
401 new_i : self._i00 }
403 self.shell.user_ns.update(to_main)
402 self.shell.user_ns.update(to_main)
404
403
405 def store_output(self, line_num):
404 def store_output(self, line_num):
406 """If database output logging is enabled, this saves all the
405 """If database output logging is enabled, this saves all the
407 outputs from the indicated prompt number to the database. It's
406 outputs from the indicated prompt number to the database. It's
408 called by run_cell after code has been executed.
407 called by run_cell after code has been executed.
409
408
410 Parameters
409 Parameters
411 ----------
410 ----------
412 line_num : int
411 line_num : int
413 The line number from which to save outputs
412 The line number from which to save outputs
414 """
413 """
415 if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
414 if (not self.db_log_output) or (line_num not in self.output_hist_reprs):
416 return
415 return
417 output = self.output_hist_reprs[line_num]
416 output = self.output_hist_reprs[line_num]
418
417
419 with self.db_output_cache_lock:
418 with self.db_output_cache_lock:
420 self.db_output_cache.append((line_num, output))
419 self.db_output_cache.append((line_num, output))
421 if self.db_cache_size <= 1:
420 if self.db_cache_size <= 1:
422 self.save_flag.set()
421 self.save_flag.set()
423
422
424 def _writeout_input_cache(self, conn):
423 def _writeout_input_cache(self, conn):
425 with conn:
424 with conn:
426 for line in self.db_input_cache:
425 for line in self.db_input_cache:
427 conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
426 conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)",
428 (self.session_number,)+line)
427 (self.session_number,)+line)
429
428
430 def _writeout_output_cache(self, conn):
429 def _writeout_output_cache(self, conn):
431 with conn:
430 with conn:
432 for line in self.db_output_cache:
431 for line in self.db_output_cache:
433 conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
432 conn.execute("INSERT INTO output_history VALUES (?, ?, ?)",
434 (self.session_number,)+line)
433 (self.session_number,)+line)
435
434
436 def writeout_cache(self, conn=None):
435 def writeout_cache(self, conn=None):
437 """Write any entries in the cache to the database."""
436 """Write any entries in the cache to the database."""
438 if conn is None:
437 if conn is None:
439 conn = self.db
438 conn = self.db
440
439
441 with self.db_input_cache_lock:
440 with self.db_input_cache_lock:
442 try:
441 try:
443 self._writeout_input_cache(conn)
442 self._writeout_input_cache(conn)
444 except sqlite3.IntegrityError:
443 except sqlite3.IntegrityError:
445 self.new_session(conn)
444 self.new_session(conn)
446 print("ERROR! Session/line number was not unique in",
445 print("ERROR! Session/line number was not unique in",
447 "database. History logging moved to new session",
446 "database. History logging moved to new session",
448 self.session_number)
447 self.session_number)
449 try: # Try writing to the new session. If this fails, don't recurse
448 try: # Try writing to the new session. If this fails, don't recurse
450 self._writeout_input_cache(conn)
449 self._writeout_input_cache(conn)
451 except sqlite3.IntegrityError:
450 except sqlite3.IntegrityError:
452 pass
451 pass
453 finally:
452 finally:
454 self.db_input_cache = []
453 self.db_input_cache = []
455
454
456 with self.db_output_cache_lock:
455 with self.db_output_cache_lock:
457 try:
456 try:
458 self._writeout_output_cache(conn)
457 self._writeout_output_cache(conn)
459 except sqlite3.IntegrityError:
458 except sqlite3.IntegrityError:
460 print("!! Session/line number for output was not unique",
459 print("!! Session/line number for output was not unique",
461 "in database. Output will not be stored.")
460 "in database. Output will not be stored.")
462 finally:
461 finally:
463 self.db_output_cache = []
462 self.db_output_cache = []
464
463
465
464
466 class HistorySavingThread(threading.Thread):
465 class HistorySavingThread(threading.Thread):
467 """This thread takes care of writing history to the database, so that
466 """This thread takes care of writing history to the database, so that
468 the UI isn't held up while that happens.
467 the UI isn't held up while that happens.
469
468
470 It waits for the HistoryManager's save_flag to be set, then writes out
469 It waits for the HistoryManager's save_flag to be set, then writes out
471 the history cache. The main thread is responsible for setting the flag when
470 the history cache. The main thread is responsible for setting the flag when
472 the cache size reaches a defined threshold."""
471 the cache size reaches a defined threshold."""
473 daemon = True
472 daemon = True
474 stop_now = False
473 stop_now = False
475 def __init__(self, history_manager):
474 def __init__(self, history_manager):
476 super(HistorySavingThread, self).__init__()
475 super(HistorySavingThread, self).__init__()
477 self.history_manager = history_manager
476 self.history_manager = history_manager
478 atexit.register(self.stop)
477 atexit.register(self.stop)
479
478
480 def run(self):
479 def run(self):
481 # We need a separate db connection per thread:
480 # We need a separate db connection per thread:
482 try:
481 try:
483 self.db = sqlite3.connect(self.history_manager.hist_file)
482 self.db = sqlite3.connect(self.history_manager.hist_file)
484 while True:
483 while True:
485 self.history_manager.save_flag.wait()
484 self.history_manager.save_flag.wait()
486 if self.stop_now:
485 if self.stop_now:
487 return
486 return
488 self.history_manager.save_flag.clear()
487 self.history_manager.save_flag.clear()
489 self.history_manager.writeout_cache(self.db)
488 self.history_manager.writeout_cache(self.db)
490 except Exception as e:
489 except Exception as e:
491 print(("The history saving thread hit an unexpected error (%s)."
490 print(("The history saving thread hit an unexpected error (%s)."
492 "History will not be written to the database.") % repr(e))
491 "History will not be written to the database.") % repr(e))
493
492
494 def stop(self):
493 def stop(self):
495 """This can be called from the main thread to safely stop this thread.
494 """This can be called from the main thread to safely stop this thread.
496
495
497 Note that it does not attempt to write out remaining history before
496 Note that it does not attempt to write out remaining history before
498 exiting. That should be done by calling the HistoryManager's
497 exiting. That should be done by calling the HistoryManager's
499 end_session method."""
498 end_session method."""
500 self.stop_now = True
499 self.stop_now = True
501 self.history_manager.save_flag.set()
500 self.history_manager.save_flag.set()
502 self.join()
501 self.join()
503
502
504
503
505 # To match, e.g. ~5/8-~2/3
504 # To match, e.g. ~5/8-~2/3
506 range_re = re.compile(r"""
505 range_re = re.compile(r"""
507 ((?P<startsess>~?\d+)/)?
506 ((?P<startsess>~?\d+)/)?
508 (?P<start>\d+) # Only the start line num is compulsory
507 (?P<start>\d+) # Only the start line num is compulsory
509 ((?P<sep>[\-:])
508 ((?P<sep>[\-:])
510 ((?P<endsess>~?\d+)/)?
509 ((?P<endsess>~?\d+)/)?
511 (?P<end>\d+))?
510 (?P<end>\d+))?
512 $""", re.VERBOSE)
511 $""", re.VERBOSE)
513
512
514 def extract_hist_ranges(ranges_str):
513 def extract_hist_ranges(ranges_str):
515 """Turn a string of history ranges into 3-tuples of (session, start, stop).
514 """Turn a string of history ranges into 3-tuples of (session, start, stop).
516
515
517 Examples
516 Examples
518 --------
517 --------
519 list(extract_input_ranges("~8/5-~7/4 2"))
518 list(extract_input_ranges("~8/5-~7/4 2"))
520 [(-8, 5, None), (-7, 1, 4), (0, 2, 3)]
519 [(-8, 5, None), (-7, 1, 4), (0, 2, 3)]
521 """
520 """
522 for range_str in ranges_str.split():
521 for range_str in ranges_str.split():
523 rmatch = range_re.match(range_str)
522 rmatch = range_re.match(range_str)
524 if not rmatch:
523 if not rmatch:
525 continue
524 continue
526 start = int(rmatch.group("start"))
525 start = int(rmatch.group("start"))
527 end = rmatch.group("end")
526 end = rmatch.group("end")
528 end = int(end) if end else start+1 # If no end specified, get (a, a+1)
527 end = int(end) if end else start+1 # If no end specified, get (a, a+1)
529 if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
528 if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3]
530 end += 1
529 end += 1
531 startsess = rmatch.group("startsess") or "0"
530 startsess = rmatch.group("startsess") or "0"
532 endsess = rmatch.group("endsess") or startsess
531 endsess = rmatch.group("endsess") or startsess
533 startsess = int(startsess.replace("~","-"))
532 startsess = int(startsess.replace("~","-"))
534 endsess = int(endsess.replace("~","-"))
533 endsess = int(endsess.replace("~","-"))
535 assert endsess >= startsess
534 assert endsess >= startsess
536
535
537 if endsess == startsess:
536 if endsess == startsess:
538 yield (startsess, start, end)
537 yield (startsess, start, end)
539 continue
538 continue
540 # Multiple sessions in one range:
539 # Multiple sessions in one range:
541 yield (startsess, start, None)
540 yield (startsess, start, None)
542 for sess in range(startsess+1, endsess):
541 for sess in range(startsess+1, endsess):
543 yield (sess, 1, None)
542 yield (sess, 1, None)
544 yield (endsess, 1, end)
543 yield (endsess, 1, end)
545
544
546 def _format_lineno(session, line):
545 def _format_lineno(session, line):
547 """Helper function to format line numbers properly."""
546 """Helper function to format line numbers properly."""
548 if session == 0:
547 if session == 0:
549 return str(line)
548 return str(line)
550 return "%s#%s" % (session, line)
549 return "%s#%s" % (session, line)
551
550
552 @testdec.skip_doctest
551 @testdec.skip_doctest
553 def magic_history(self, parameter_s = ''):
552 def magic_history(self, parameter_s = ''):
554 """Print input history (_i<n> variables), with most recent last.
553 """Print input history (_i<n> variables), with most recent last.
555
554
556 %history -> print at most 40 inputs (some may be multi-line)\\
555 %history -> print at most 40 inputs (some may be multi-line)\\
557 %history n -> print at most n inputs\\
556 %history n -> print at most n inputs\\
558 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
557 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
559
558
560 By default, input history is printed without line numbers so it can be
559 By default, input history is printed without line numbers so it can be
561 directly pasted into an editor. Use -n to show them.
560 directly pasted into an editor. Use -n to show them.
562
561
563 Ranges of history can be indicated using the syntax:
562 Ranges of history can be indicated using the syntax:
564 4 : Line 4, current session
563 4 : Line 4, current session
565 4-6 : Lines 4-6, current session
564 4-6 : Lines 4-6, current session
566 243/1-5: Lines 1-5, session 243
565 243/1-5: Lines 1-5, session 243
567 ~2/7 : Line 7, session 2 before current
566 ~2/7 : Line 7, session 2 before current
568 ~8/1-~6/5 : From the first line of 8 sessions ago, to the fifth line
567 ~8/1-~6/5 : From the first line of 8 sessions ago, to the fifth line
569 of 6 sessions ago.
568 of 6 sessions ago.
570 Multiple ranges can be entered, separated by spaces
569 Multiple ranges can be entered, separated by spaces
571
570
572 The same syntax is used by %macro, %save, %edit, %rerun
571 The same syntax is used by %macro, %save, %edit, %rerun
573
572
574 Options:
573 Options:
575
574
576 -n: print line numbers for each input.
575 -n: print line numbers for each input.
577 This feature is only available if numbered prompts are in use.
576 This feature is only available if numbered prompts are in use.
578
577
579 -o: also print outputs for each input.
578 -o: also print outputs for each input.
580
579
581 -p: print classic '>>>' python prompts before each input. This is useful
580 -p: print classic '>>>' python prompts before each input. This is useful
582 for making documentation, and in conjunction with -o, for producing
581 for making documentation, and in conjunction with -o, for producing
583 doctest-ready output.
582 doctest-ready output.
584
583
585 -r: (default) print the 'raw' history, i.e. the actual commands you typed.
584 -r: (default) print the 'raw' history, i.e. the actual commands you typed.
586
585
587 -t: print the 'translated' history, as IPython understands it. IPython
586 -t: print the 'translated' history, as IPython understands it. IPython
588 filters your input and converts it all into valid Python source before
587 filters your input and converts it all into valid Python source before
589 executing it (things like magics or aliases are turned into function
588 executing it (things like magics or aliases are turned into function
590 calls, for example). With this option, you'll see the native history
589 calls, for example). With this option, you'll see the native history
591 instead of the user-entered version: '%cd /' will be seen as
590 instead of the user-entered version: '%cd /' will be seen as
592 'get_ipython().magic("%cd /")' instead of '%cd /'.
591 'get_ipython().magic("%cd /")' instead of '%cd /'.
593
592
594 -g: treat the arg as a pattern to grep for in (full) history.
593 -g: treat the arg as a pattern to grep for in (full) history.
595 This includes the saved history (almost all commands ever written).
594 This includes the saved history (almost all commands ever written).
596 Use '%hist -g' to show full saved history (may be very long).
595 Use '%hist -g' to show full saved history (may be very long).
597
596
598 -l: get the last n lines from all sessions. Specify n as a single arg, or
597 -l: get the last n lines from all sessions. Specify n as a single arg, or
599 the default is the last 10 lines.
598 the default is the last 10 lines.
600
599
601 -f FILENAME: instead of printing the output to the screen, redirect it to
600 -f FILENAME: instead of printing the output to the screen, redirect it to
602 the given file. The file is always overwritten, though IPython asks for
601 the given file. The file is always overwritten, though IPython asks for
603 confirmation first if it already exists.
602 confirmation first if it already exists.
604
603
605 Examples
604 Examples
606 --------
605 --------
607 ::
606 ::
608
607
609 In [6]: %hist -n 4 6
608 In [6]: %hist -n 4 6
610 4:a = 12
609 4:a = 12
611 5:print a**2
610 5:print a**2
612
611
613 """
612 """
614
613
615 if not self.shell.displayhook.do_full_cache:
614 if not self.shell.displayhook.do_full_cache:
616 print('This feature is only available if numbered prompts are in use.')
615 print('This feature is only available if numbered prompts are in use.')
617 return
616 return
618 opts,args = self.parse_options(parameter_s,'noprtglf:',mode='string')
617 opts,args = self.parse_options(parameter_s,'noprtglf:',mode='string')
619
618
620 # For brevity
619 # For brevity
621 history_manager = self.shell.history_manager
620 history_manager = self.shell.history_manager
622
621
623 def _format_lineno(session, line):
622 def _format_lineno(session, line):
624 """Helper function to format line numbers properly."""
623 """Helper function to format line numbers properly."""
625 if session in (0, history_manager.session_number):
624 if session in (0, history_manager.session_number):
626 return str(line)
625 return str(line)
627 return "%s/%s" % (session, line)
626 return "%s/%s" % (session, line)
628
627
629 # Check if output to specific file was requested.
628 # Check if output to specific file was requested.
630 try:
629 try:
631 outfname = opts['f']
630 outfname = opts['f']
632 except KeyError:
631 except KeyError:
633 outfile = IPython.utils.io.Term.cout # default
632 outfile = io.stdout # default
634 # We don't want to close stdout at the end!
633 # We don't want to close stdout at the end!
635 close_at_end = False
634 close_at_end = False
636 else:
635 else:
637 if os.path.exists(outfname):
636 if os.path.exists(outfname):
638 if not ask_yes_no("File %r exists. Overwrite?" % outfname):
637 if not io.ask_yes_no("File %r exists. Overwrite?" % outfname):
639 print('Aborting.')
638 print('Aborting.')
640 return
639 return
641
640
642 outfile = open(outfname,'w')
641 outfile = open(outfname,'w')
643 close_at_end = True
642 close_at_end = True
644
643
645 print_nums = 'n' in opts
644 print_nums = 'n' in opts
646 get_output = 'o' in opts
645 get_output = 'o' in opts
647 pyprompts = 'p' in opts
646 pyprompts = 'p' in opts
648 # Raw history is the default
647 # Raw history is the default
649 raw = not('t' in opts)
648 raw = not('t' in opts)
650
649
651 default_length = 40
650 default_length = 40
652 pattern = None
651 pattern = None
653
652
654 if 'g' in opts: # Glob search
653 if 'g' in opts: # Glob search
655 pattern = "*" + args + "*" if args else "*"
654 pattern = "*" + args + "*" if args else "*"
656 hist = history_manager.search(pattern, raw=raw, output=get_output)
655 hist = history_manager.search(pattern, raw=raw, output=get_output)
657 elif 'l' in opts: # Get 'tail'
656 elif 'l' in opts: # Get 'tail'
658 try:
657 try:
659 n = int(args)
658 n = int(args)
660 except ValueError, IndexError:
659 except ValueError, IndexError:
661 n = 10
660 n = 10
662 hist = history_manager.get_tail(n, raw=raw, output=get_output)
661 hist = history_manager.get_tail(n, raw=raw, output=get_output)
663 else:
662 else:
664 if args: # Get history by ranges
663 if args: # Get history by ranges
665 hist = history_manager.get_range_by_str(args, raw, get_output)
664 hist = history_manager.get_range_by_str(args, raw, get_output)
666 else: # Just get history for the current session
665 else: # Just get history for the current session
667 hist = history_manager.get_range(raw=raw, output=get_output)
666 hist = history_manager.get_range(raw=raw, output=get_output)
668
667
669 # We could be displaying the entire history, so let's not try to pull it
668 # We could be displaying the entire history, so let's not try to pull it
670 # into a list in memory. Anything that needs more space will just misalign.
669 # into a list in memory. Anything that needs more space will just misalign.
671 width = 4
670 width = 4
672
671
673 for session, lineno, inline in hist:
672 for session, lineno, inline in hist:
674 # Print user history with tabs expanded to 4 spaces. The GUI clients
673 # Print user history with tabs expanded to 4 spaces. The GUI clients
675 # use hard tabs for easier usability in auto-indented code, but we want
674 # use hard tabs for easier usability in auto-indented code, but we want
676 # to produce PEP-8 compliant history for safe pasting into an editor.
675 # to produce PEP-8 compliant history for safe pasting into an editor.
677 if get_output:
676 if get_output:
678 inline, output = inline
677 inline, output = inline
679 inline = inline.expandtabs(4).rstrip()
678 inline = inline.expandtabs(4).rstrip()
680
679
681 multiline = "\n" in inline
680 multiline = "\n" in inline
682 line_sep = '\n' if multiline else ' '
681 line_sep = '\n' if multiline else ' '
683 if print_nums:
682 if print_nums:
684 print('%s:%s' % (_format_lineno(session, lineno).rjust(width),
683 print('%s:%s' % (_format_lineno(session, lineno).rjust(width),
685 line_sep), file=outfile, end='')
684 line_sep), file=outfile, end='')
686 if pyprompts:
685 if pyprompts:
687 print(">>> ", end="", file=outfile)
686 print(">>> ", end="", file=outfile)
688 if multiline:
687 if multiline:
689 inline = "\n... ".join(inline.splitlines()) + "\n..."
688 inline = "\n... ".join(inline.splitlines()) + "\n..."
690 print(inline, file=outfile)
689 print(inline, file=outfile)
691 if get_output and output:
690 if get_output and output:
692 print(output, file=outfile)
691 print(output, file=outfile)
693
692
694 if close_at_end:
693 if close_at_end:
695 outfile.close()
694 outfile.close()
696
695
697
696
698 def magic_rep(self, arg):
697 def magic_rep(self, arg):
699 r""" Repeat a command, or get command to input line for editing
698 r""" Repeat a command, or get command to input line for editing
700
699
701 - %rep (no arguments):
700 - %rep (no arguments):
702
701
703 Place a string version of last computation result (stored in the special '_'
702 Place a string version of last computation result (stored in the special '_'
704 variable) to the next input prompt. Allows you to create elaborate command
703 variable) to the next input prompt. Allows you to create elaborate command
705 lines without using copy-paste::
704 lines without using copy-paste::
706
705
707 In[1]: l = ["hei", "vaan"]
706 In[1]: l = ["hei", "vaan"]
708 In[2]: "".join(l)
707 In[2]: "".join(l)
709 Out[2]: heivaan
708 Out[2]: heivaan
710 In[3]: %rep
709 In[3]: %rep
711 In[4]: heivaan_ <== cursor blinking
710 In[4]: heivaan_ <== cursor blinking
712
711
713 %rep 45
712 %rep 45
714
713
715 Place history line 45 on the next input prompt. Use %hist to find
714 Place history line 45 on the next input prompt. Use %hist to find
716 out the number.
715 out the number.
717
716
718 %rep 1-4
717 %rep 1-4
719
718
720 Combine the specified lines into one cell, and place it on the next
719 Combine the specified lines into one cell, and place it on the next
721 input prompt. See %history for the slice syntax.
720 input prompt. See %history for the slice syntax.
722
721
723 %rep foo+bar
722 %rep foo+bar
724
723
725 If foo+bar can be evaluated in the user namespace, the result is
724 If foo+bar can be evaluated in the user namespace, the result is
726 placed at the next input prompt. Otherwise, the history is searched
725 placed at the next input prompt. Otherwise, the history is searched
727 for lines which contain that substring, and the most recent one is
726 for lines which contain that substring, and the most recent one is
728 placed at the next input prompt.
727 placed at the next input prompt.
729 """
728 """
730 if not arg: # Last output
729 if not arg: # Last output
731 self.set_next_input(str(self.shell.user_ns["_"]))
730 self.set_next_input(str(self.shell.user_ns["_"]))
732 return
731 return
733 # Get history range
732 # Get history range
734 histlines = self.history_manager.get_range_by_str(arg)
733 histlines = self.history_manager.get_range_by_str(arg)
735 cmd = "\n".join(x[2] for x in histlines)
734 cmd = "\n".join(x[2] for x in histlines)
736 if cmd:
735 if cmd:
737 self.set_next_input(cmd.rstrip())
736 self.set_next_input(cmd.rstrip())
738 return
737 return
739
738
740 try: # Variable in user namespace
739 try: # Variable in user namespace
741 cmd = str(eval(arg, self.shell.user_ns))
740 cmd = str(eval(arg, self.shell.user_ns))
742 except Exception: # Search for term in history
741 except Exception: # Search for term in history
743 histlines = self.history_manager.search("*"+arg+"*")
742 histlines = self.history_manager.search("*"+arg+"*")
744 for h in reversed([x[2] for x in histlines]):
743 for h in reversed([x[2] for x in histlines]):
745 if 'rep' in h:
744 if 'rep' in h:
746 continue
745 continue
747 self.set_next_input(h.rstrip())
746 self.set_next_input(h.rstrip())
748 return
747 return
749 else:
748 else:
750 self.set_next_input(cmd.rstrip())
749 self.set_next_input(cmd.rstrip())
751 print("Couldn't evaluate or find in history:", arg)
750 print("Couldn't evaluate or find in history:", arg)
752
751
753 def magic_rerun(self, parameter_s=''):
752 def magic_rerun(self, parameter_s=''):
754 """Re-run previous input
753 """Re-run previous input
755
754
756 By default, you can specify ranges of input history to be repeated
755 By default, you can specify ranges of input history to be repeated
757 (as with %history). With no arguments, it will repeat the last line.
756 (as with %history). With no arguments, it will repeat the last line.
758
757
759 Options:
758 Options:
760
759
761 -l <n> : Repeat the last n lines of input, not including the
760 -l <n> : Repeat the last n lines of input, not including the
762 current command.
761 current command.
763
762
764 -g foo : Repeat the most recent line which contains foo
763 -g foo : Repeat the most recent line which contains foo
765 """
764 """
766 opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
765 opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
767 if "l" in opts: # Last n lines
766 if "l" in opts: # Last n lines
768 n = int(opts['l'])
767 n = int(opts['l'])
769 hist = self.history_manager.get_tail(n)
768 hist = self.history_manager.get_tail(n)
770 elif "g" in opts: # Search
769 elif "g" in opts: # Search
771 p = "*"+opts['g']+"*"
770 p = "*"+opts['g']+"*"
772 hist = list(self.history_manager.search(p))
771 hist = list(self.history_manager.search(p))
773 for l in reversed(hist):
772 for l in reversed(hist):
774 if "rerun" not in l[2]:
773 if "rerun" not in l[2]:
775 hist = [l] # The last match which isn't a %rerun
774 hist = [l] # The last match which isn't a %rerun
776 break
775 break
777 else:
776 else:
778 hist = [] # No matches except %rerun
777 hist = [] # No matches except %rerun
779 elif args: # Specify history ranges
778 elif args: # Specify history ranges
780 hist = self.history_manager.get_range_by_str(args)
779 hist = self.history_manager.get_range_by_str(args)
781 else: # Last line
780 else: # Last line
782 hist = self.history_manager.get_tail(1)
781 hist = self.history_manager.get_tail(1)
783 hist = [x[2] for x in hist]
782 hist = [x[2] for x in hist]
784 if not hist:
783 if not hist:
785 print("No lines in history match specification")
784 print("No lines in history match specification")
786 return
785 return
787 histlines = "\n".join(hist)
786 histlines = "\n".join(hist)
788 print("=== Executing: ===")
787 print("=== Executing: ===")
789 print(histlines)
788 print(histlines)
790 print("=== Output: ===")
789 print("=== Output: ===")
791 self.run_cell("\n".join(hist), store_history=False)
790 self.run_cell("\n".join(hist), store_history=False)
792
791
793
792
794 def init_ipython(ip):
793 def init_ipython(ip):
795 ip.define_magic("rep", magic_rep)
794 ip.define_magic("rep", magic_rep)
796 ip.define_magic("recall", magic_rep)
795 ip.define_magic("recall", magic_rep)
797 ip.define_magic("rerun", magic_rerun)
796 ip.define_magic("rerun", magic_rerun)
798 ip.define_magic("hist",magic_history) # Alternative name
797 ip.define_magic("hist",magic_history) # Alternative name
799 ip.define_magic("history",magic_history)
798 ip.define_magic("history",magic_history)
800
799
801 # XXX - ipy_completers are in quarantine, need to be updated to new apis
800 # XXX - ipy_completers are in quarantine, need to be updated to new apis
802 #import ipy_completers
801 #import ipy_completers
803 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
802 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
@@ -1,236 +1,235 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 IPython.core.error import TryNext
47 from IPython.core.error import TryNext
48 import IPython.utils.io
49
48
50 # List here all the default hooks. For now it's just the editor functions
49 # List here all the default hooks. For now it's just the editor functions
51 # but over time we'll move here all the public API for user-accessible things.
50 # but over time we'll move here all the public API for user-accessible things.
52
51
53 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor',
52 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor',
54 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
53 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
55 'generate_prompt', 'show_in_pager','pre_prompt_hook',
54 'generate_prompt', 'show_in_pager','pre_prompt_hook',
56 'pre_run_code_hook', 'clipboard_get']
55 'pre_run_code_hook', 'clipboard_get']
57
56
58 def editor(self,filename, linenum=None):
57 def editor(self,filename, linenum=None):
59 """Open the default editor at the given filename and linenumber.
58 """Open the default editor at the given filename and linenumber.
60
59
61 This is IPython's default editor hook, you can use it as an example to
60 This is IPython's default editor hook, you can use it as an example to
62 write your own modified one. To set your own editor function as the
61 write your own modified one. To set your own editor function as the
63 new editor hook, call ip.set_hook('editor',yourfunc)."""
62 new editor hook, call ip.set_hook('editor',yourfunc)."""
64
63
65 # IPython configures a default editor at startup by reading $EDITOR from
64 # IPython configures a default editor at startup by reading $EDITOR from
66 # the environment, and falling back on vi (unix) or notepad (win32).
65 # the environment, and falling back on vi (unix) or notepad (win32).
67 editor = self.editor
66 editor = self.editor
68
67
69 # marker for at which line to open the file (for existing objects)
68 # marker for at which line to open the file (for existing objects)
70 if linenum is None or editor=='notepad':
69 if linenum is None or editor=='notepad':
71 linemark = ''
70 linemark = ''
72 else:
71 else:
73 linemark = '+%d' % int(linenum)
72 linemark = '+%d' % int(linenum)
74
73
75 # Enclose in quotes if necessary and legal
74 # Enclose in quotes if necessary and legal
76 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
75 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"':
77 editor = '"%s"' % editor
76 editor = '"%s"' % editor
78
77
79 # Call the actual editor
78 # Call the actual editor
80 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
79 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
81 raise TryNext()
80 raise TryNext()
82
81
83 import tempfile
82 import tempfile
84 def fix_error_editor(self,filename,linenum,column,msg):
83 def fix_error_editor(self,filename,linenum,column,msg):
85 """Open the editor at the given filename, linenumber, column and
84 """Open the editor at the given filename, linenumber, column and
86 show an error message. This is used for correcting syntax errors.
85 show an error message. This is used for correcting syntax errors.
87 The current implementation only has special support for the VIM editor,
86 The current implementation only has special support for the VIM editor,
88 and falls back on the 'editor' hook if VIM is not used.
87 and falls back on the 'editor' hook if VIM is not used.
89
88
90 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
89 Call ip.set_hook('fix_error_editor',youfunc) to use your own function,
91 """
90 """
92 def vim_quickfix_file():
91 def vim_quickfix_file():
93 t = tempfile.NamedTemporaryFile()
92 t = tempfile.NamedTemporaryFile()
94 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
93 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
95 t.flush()
94 t.flush()
96 return t
95 return t
97 if os.path.basename(self.editor) != 'vim':
96 if os.path.basename(self.editor) != 'vim':
98 self.hooks.editor(filename,linenum)
97 self.hooks.editor(filename,linenum)
99 return
98 return
100 t = vim_quickfix_file()
99 t = vim_quickfix_file()
101 try:
100 try:
102 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
101 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
103 raise TryNext()
102 raise TryNext()
104 finally:
103 finally:
105 t.close()
104 t.close()
106
105
107
106
108 def synchronize_with_editor(self, filename, linenum, column):
107 def synchronize_with_editor(self, filename, linenum, column):
109 pass
108 pass
110
109
111
110
112 class CommandChainDispatcher:
111 class CommandChainDispatcher:
113 """ Dispatch calls to a chain of commands until some func can handle it
112 """ Dispatch calls to a chain of commands until some func can handle it
114
113
115 Usage: instantiate, execute "add" to add commands (with optional
114 Usage: instantiate, execute "add" to add commands (with optional
116 priority), execute normally via f() calling mechanism.
115 priority), execute normally via f() calling mechanism.
117
116
118 """
117 """
119 def __init__(self,commands=None):
118 def __init__(self,commands=None):
120 if commands is None:
119 if commands is None:
121 self.chain = []
120 self.chain = []
122 else:
121 else:
123 self.chain = commands
122 self.chain = commands
124
123
125
124
126 def __call__(self,*args, **kw):
125 def __call__(self,*args, **kw):
127 """ Command chain is called just like normal func.
126 """ Command chain is called just like normal func.
128
127
129 This will call all funcs in chain with the same args as were given to this
128 This will call all funcs in chain with the same args as were given to this
130 function, and return the result of first func that didn't raise
129 function, and return the result of first func that didn't raise
131 TryNext """
130 TryNext """
132
131
133 for prio,cmd in self.chain:
132 for prio,cmd in self.chain:
134 #print "prio",prio,"cmd",cmd #dbg
133 #print "prio",prio,"cmd",cmd #dbg
135 try:
134 try:
136 return cmd(*args, **kw)
135 return cmd(*args, **kw)
137 except TryNext, exc:
136 except TryNext, exc:
138 if exc.args or exc.kwargs:
137 if exc.args or exc.kwargs:
139 args = exc.args
138 args = exc.args
140 kw = exc.kwargs
139 kw = exc.kwargs
141 # if no function will accept it, raise TryNext up to the caller
140 # if no function will accept it, raise TryNext up to the caller
142 raise TryNext
141 raise TryNext
143
142
144 def __str__(self):
143 def __str__(self):
145 return str(self.chain)
144 return str(self.chain)
146
145
147 def add(self, func, priority=0):
146 def add(self, func, priority=0):
148 """ Add a func to the cmd chain with given priority """
147 """ Add a func to the cmd chain with given priority """
149 bisect.insort(self.chain,(priority,func))
148 bisect.insort(self.chain,(priority,func))
150
149
151 def __iter__(self):
150 def __iter__(self):
152 """ Return all objects in chain.
151 """ Return all objects in chain.
153
152
154 Handy if the objects are not callable.
153 Handy if the objects are not callable.
155 """
154 """
156 return iter(self.chain)
155 return iter(self.chain)
157
156
158
157
159 def input_prefilter(self,line):
158 def input_prefilter(self,line):
160 """ Default input prefilter
159 """ Default input prefilter
161
160
162 This returns the line as unchanged, so that the interpreter
161 This returns the line as unchanged, so that the interpreter
163 knows that nothing was done and proceeds with "classic" prefiltering
162 knows that nothing was done and proceeds with "classic" prefiltering
164 (%magics, !shell commands etc.).
163 (%magics, !shell commands etc.).
165
164
166 Note that leading whitespace is not passed to this hook. Prefilter
165 Note that leading whitespace is not passed to this hook. Prefilter
167 can't alter indentation.
166 can't alter indentation.
168
167
169 """
168 """
170 #print "attempt to rewrite",line #dbg
169 #print "attempt to rewrite",line #dbg
171 return line
170 return line
172
171
173
172
174 def shutdown_hook(self):
173 def shutdown_hook(self):
175 """ default shutdown hook
174 """ default shutdown hook
176
175
177 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
176 Typically, shotdown hooks should raise TryNext so all shutdown ops are done
178 """
177 """
179
178
180 #print "default shutdown hook ok" # dbg
179 #print "default shutdown hook ok" # dbg
181 return
180 return
182
181
183
182
184 def late_startup_hook(self):
183 def late_startup_hook(self):
185 """ Executed after ipython has been constructed and configured
184 """ Executed after ipython has been constructed and configured
186
185
187 """
186 """
188 #print "default startup hook ok" # dbg
187 #print "default startup hook ok" # dbg
189
188
190
189
191 def generate_prompt(self, is_continuation):
190 def generate_prompt(self, is_continuation):
192 """ calculate and return a string with the prompt to display """
191 """ calculate and return a string with the prompt to display """
193 if is_continuation:
192 if is_continuation:
194 return str(self.displayhook.prompt2)
193 return str(self.displayhook.prompt2)
195 return str(self.displayhook.prompt1)
194 return str(self.displayhook.prompt1)
196
195
197
196
198 def show_in_pager(self,s):
197 def show_in_pager(self,s):
199 """ Run a string through pager """
198 """ Run a string through pager """
200 # raising TryNext here will use the default paging functionality
199 # raising TryNext here will use the default paging functionality
201 raise TryNext
200 raise TryNext
202
201
203
202
204 def pre_prompt_hook(self):
203 def pre_prompt_hook(self):
205 """ Run before displaying the next prompt
204 """ Run before displaying the next prompt
206
205
207 Use this e.g. to display output from asynchronous operations (in order
206 Use this e.g. to display output from asynchronous operations (in order
208 to not mess up text entry)
207 to not mess up text entry)
209 """
208 """
210
209
211 return None
210 return None
212
211
213
212
214 def pre_run_code_hook(self):
213 def pre_run_code_hook(self):
215 """ Executed before running the (prefiltered) code in IPython """
214 """ Executed before running the (prefiltered) code in IPython """
216 return None
215 return None
217
216
218
217
219 def clipboard_get(self):
218 def clipboard_get(self):
220 """ Get text from the clipboard.
219 """ Get text from the clipboard.
221 """
220 """
222 from IPython.lib.clipboard import (
221 from IPython.lib.clipboard import (
223 osx_clipboard_get, tkinter_clipboard_get,
222 osx_clipboard_get, tkinter_clipboard_get,
224 win32_clipboard_get
223 win32_clipboard_get
225 )
224 )
226 if sys.platform == 'win32':
225 if sys.platform == 'win32':
227 chain = [win32_clipboard_get, tkinter_clipboard_get]
226 chain = [win32_clipboard_get, tkinter_clipboard_get]
228 elif sys.platform == 'darwin':
227 elif sys.platform == 'darwin':
229 chain = [osx_clipboard_get, tkinter_clipboard_get]
228 chain = [osx_clipboard_get, tkinter_clipboard_get]
230 else:
229 else:
231 chain = [tkinter_clipboard_get]
230 chain = [tkinter_clipboard_get]
232 dispatcher = CommandChainDispatcher()
231 dispatcher = CommandChainDispatcher()
233 for func in chain:
232 for func in chain:
234 dispatcher.add(func)
233 dispatcher.add(func)
235 text = dispatcher()
234 text = dispatcher()
236 return text
235 return text
@@ -1,2424 +1,2423 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-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 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 __future__
21 import __future__
22 import abc
22 import abc
23 import ast
23 import ast
24 import atexit
24 import atexit
25 import codeop
25 import codeop
26 import inspect
26 import inspect
27 import os
27 import os
28 import re
28 import re
29 import sys
29 import sys
30 import tempfile
30 import tempfile
31 import types
31 import types
32 from contextlib import nested
32 from contextlib import nested
33
33
34 from IPython.config.configurable import Configurable
34 from IPython.config.configurable import Configurable
35 from IPython.core import debugger, oinspect
35 from IPython.core import debugger, oinspect
36 from IPython.core import history as ipcorehist
36 from IPython.core import history as ipcorehist
37 from IPython.core import page
37 from IPython.core import page
38 from IPython.core import prefilter
38 from IPython.core import prefilter
39 from IPython.core import shadowns
39 from IPython.core import shadowns
40 from IPython.core import ultratb
40 from IPython.core import ultratb
41 from IPython.core.alias import AliasManager
41 from IPython.core.alias import AliasManager
42 from IPython.core.autocall import ExitAutocall
42 from IPython.core.autocall import ExitAutocall
43 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.builtin_trap import BuiltinTrap
44 from IPython.core.compilerop import CachingCompiler
44 from IPython.core.compilerop import CachingCompiler
45 from IPython.core.display_trap import DisplayTrap
45 from IPython.core.display_trap import DisplayTrap
46 from IPython.core.displayhook import DisplayHook
46 from IPython.core.displayhook import DisplayHook
47 from IPython.core.displaypub import DisplayPublisher
47 from IPython.core.displaypub import DisplayPublisher
48 from IPython.core.error import TryNext, UsageError
48 from IPython.core.error import TryNext, UsageError
49 from IPython.core.extensions import ExtensionManager
49 from IPython.core.extensions import ExtensionManager
50 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
50 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
51 from IPython.core.formatters import DisplayFormatter
51 from IPython.core.formatters import DisplayFormatter
52 from IPython.core.history import HistoryManager
52 from IPython.core.history import HistoryManager
53 from IPython.core.inputsplitter import IPythonInputSplitter
53 from IPython.core.inputsplitter import IPythonInputSplitter
54 from IPython.core.logger import Logger
54 from IPython.core.logger import Logger
55 from IPython.core.macro import Macro
55 from IPython.core.macro import Macro
56 from IPython.core.magic import Magic
56 from IPython.core.magic import Magic
57 from IPython.core.payload import PayloadManager
57 from IPython.core.payload import PayloadManager
58 from IPython.core.plugin import PluginManager
58 from IPython.core.plugin import PluginManager
59 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
59 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
60 from IPython.external.Itpl import ItplNS
60 from IPython.external.Itpl import ItplNS
61 from IPython.utils import PyColorize
61 from IPython.utils import PyColorize
62 from IPython.utils import io
62 from IPython.utils import io
63 from IPython.utils.doctestreload import doctest_reload
63 from IPython.utils.doctestreload import doctest_reload
64 from IPython.utils.io import ask_yes_no, rprint
64 from IPython.utils.io import ask_yes_no, rprint
65 from IPython.utils.ipstruct import Struct
65 from IPython.utils.ipstruct import Struct
66 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
66 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
67 from IPython.utils.pickleshare import PickleShareDB
67 from IPython.utils.pickleshare import PickleShareDB
68 from IPython.utils.process import system, getoutput
68 from IPython.utils.process import system, getoutput
69 from IPython.utils.strdispatch import StrDispatch
69 from IPython.utils.strdispatch import StrDispatch
70 from IPython.utils.syspathcontext import prepended_to_syspath
70 from IPython.utils.syspathcontext import prepended_to_syspath
71 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
71 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
72 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
72 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
73 List, Unicode, Instance, Type)
73 List, Unicode, Instance, Type)
74 from IPython.utils.warn import warn, error, fatal
74 from IPython.utils.warn import warn, error, fatal
75 import IPython.core.hooks
75 import IPython.core.hooks
76
76
77 #-----------------------------------------------------------------------------
77 #-----------------------------------------------------------------------------
78 # Globals
78 # Globals
79 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
80
80
81 # compiled regexps for autoindent management
81 # compiled regexps for autoindent management
82 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
82 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
83
83
84 #-----------------------------------------------------------------------------
84 #-----------------------------------------------------------------------------
85 # Utilities
85 # Utilities
86 #-----------------------------------------------------------------------------
86 #-----------------------------------------------------------------------------
87
87
88 # store the builtin raw_input globally, and use this always, in case user code
88 # store the builtin raw_input globally, and use this always, in case user code
89 # overwrites it (like wx.py.PyShell does)
89 # overwrites it (like wx.py.PyShell does)
90 raw_input_original = raw_input
90 raw_input_original = raw_input
91
91
92 def softspace(file, newvalue):
92 def softspace(file, newvalue):
93 """Copied from code.py, to remove the dependency"""
93 """Copied from code.py, to remove the dependency"""
94
94
95 oldvalue = 0
95 oldvalue = 0
96 try:
96 try:
97 oldvalue = file.softspace
97 oldvalue = file.softspace
98 except AttributeError:
98 except AttributeError:
99 pass
99 pass
100 try:
100 try:
101 file.softspace = newvalue
101 file.softspace = newvalue
102 except (AttributeError, TypeError):
102 except (AttributeError, TypeError):
103 # "attribute-less object" or "read-only attributes"
103 # "attribute-less object" or "read-only attributes"
104 pass
104 pass
105 return oldvalue
105 return oldvalue
106
106
107
107
108 def no_op(*a, **kw): pass
108 def no_op(*a, **kw): pass
109
109
110 class SpaceInInput(Exception): pass
110 class SpaceInInput(Exception): pass
111
111
112 class Bunch: pass
112 class Bunch: pass
113
113
114
114
115 def get_default_colors():
115 def get_default_colors():
116 if sys.platform=='darwin':
116 if sys.platform=='darwin':
117 return "LightBG"
117 return "LightBG"
118 elif os.name=='nt':
118 elif os.name=='nt':
119 return 'Linux'
119 return 'Linux'
120 else:
120 else:
121 return 'Linux'
121 return 'Linux'
122
122
123
123
124 class SeparateStr(Str):
124 class SeparateStr(Str):
125 """A Str subclass to validate separate_in, separate_out, etc.
125 """A Str subclass to validate separate_in, separate_out, etc.
126
126
127 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
127 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
128 """
128 """
129
129
130 def validate(self, obj, value):
130 def validate(self, obj, value):
131 if value == '0': value = ''
131 if value == '0': value = ''
132 value = value.replace('\\n','\n')
132 value = value.replace('\\n','\n')
133 return super(SeparateStr, self).validate(obj, value)
133 return super(SeparateStr, self).validate(obj, value)
134
134
135 class MultipleInstanceError(Exception):
135 class MultipleInstanceError(Exception):
136 pass
136 pass
137
137
138 class ReadlineNoRecord(object):
138 class ReadlineNoRecord(object):
139 """Context manager to execute some code, then reload readline history
139 """Context manager to execute some code, then reload readline history
140 so that interactive input to the code doesn't appear when pressing up."""
140 so that interactive input to the code doesn't appear when pressing up."""
141 def __init__(self, shell):
141 def __init__(self, shell):
142 self.shell = shell
142 self.shell = shell
143 self._nested_level = 0
143 self._nested_level = 0
144
144
145 def __enter__(self):
145 def __enter__(self):
146 if self._nested_level == 0:
146 if self._nested_level == 0:
147 try:
147 try:
148 self.orig_length = self.current_length()
148 self.orig_length = self.current_length()
149 self.readline_tail = self.get_readline_tail()
149 self.readline_tail = self.get_readline_tail()
150 except (AttributeError, IndexError): # Can fail with pyreadline
150 except (AttributeError, IndexError): # Can fail with pyreadline
151 self.orig_length, self.readline_tail = 999999, []
151 self.orig_length, self.readline_tail = 999999, []
152 self._nested_level += 1
152 self._nested_level += 1
153
153
154 def __exit__(self, type, value, traceback):
154 def __exit__(self, type, value, traceback):
155 self._nested_level -= 1
155 self._nested_level -= 1
156 if self._nested_level == 0:
156 if self._nested_level == 0:
157 # Try clipping the end if it's got longer
157 # Try clipping the end if it's got longer
158 try:
158 try:
159 e = self.current_length() - self.orig_length
159 e = self.current_length() - self.orig_length
160 if e > 0:
160 if e > 0:
161 for _ in range(e):
161 for _ in range(e):
162 self.shell.readline.remove_history_item(self.orig_length)
162 self.shell.readline.remove_history_item(self.orig_length)
163
163
164 # If it still doesn't match, just reload readline history.
164 # If it still doesn't match, just reload readline history.
165 if self.current_length() != self.orig_length \
165 if self.current_length() != self.orig_length \
166 or self.get_readline_tail() != self.readline_tail:
166 or self.get_readline_tail() != self.readline_tail:
167 self.shell.refill_readline_hist()
167 self.shell.refill_readline_hist()
168 except (AttributeError, IndexError):
168 except (AttributeError, IndexError):
169 pass
169 pass
170 # Returning False will cause exceptions to propagate
170 # Returning False will cause exceptions to propagate
171 return False
171 return False
172
172
173 def current_length(self):
173 def current_length(self):
174 return self.shell.readline.get_current_history_length()
174 return self.shell.readline.get_current_history_length()
175
175
176 def get_readline_tail(self, n=10):
176 def get_readline_tail(self, n=10):
177 """Get the last n items in readline history."""
177 """Get the last n items in readline history."""
178 end = self.shell.readline.get_current_history_length() + 1
178 end = self.shell.readline.get_current_history_length() + 1
179 start = max(end-n, 1)
179 start = max(end-n, 1)
180 ghi = self.shell.readline.get_history_item
180 ghi = self.shell.readline.get_history_item
181 return [ghi(x) for x in range(start, end)]
181 return [ghi(x) for x in range(start, end)]
182
182
183
183
184 #-----------------------------------------------------------------------------
184 #-----------------------------------------------------------------------------
185 # Main IPython class
185 # Main IPython class
186 #-----------------------------------------------------------------------------
186 #-----------------------------------------------------------------------------
187
187
188 class InteractiveShell(Configurable, Magic):
188 class InteractiveShell(Configurable, Magic):
189 """An enhanced, interactive shell for Python."""
189 """An enhanced, interactive shell for Python."""
190
190
191 _instance = None
191 _instance = None
192 autocall = Enum((0,1,2), default_value=1, config=True)
192 autocall = Enum((0,1,2), default_value=1, config=True)
193 # TODO: remove all autoindent logic and put into frontends.
193 # TODO: remove all autoindent logic and put into frontends.
194 # We can't do this yet because even runlines uses the autoindent.
194 # We can't do this yet because even runlines uses the autoindent.
195 autoindent = CBool(True, config=True)
195 autoindent = CBool(True, config=True)
196 automagic = CBool(True, config=True)
196 automagic = CBool(True, config=True)
197 cache_size = Int(1000, config=True)
197 cache_size = Int(1000, config=True)
198 color_info = CBool(True, config=True)
198 color_info = CBool(True, config=True)
199 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
199 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
200 default_value=get_default_colors(), config=True)
200 default_value=get_default_colors(), config=True)
201 debug = CBool(False, config=True)
201 debug = CBool(False, config=True)
202 deep_reload = CBool(False, config=True)
202 deep_reload = CBool(False, config=True)
203 display_formatter = Instance(DisplayFormatter)
203 display_formatter = Instance(DisplayFormatter)
204 displayhook_class = Type(DisplayHook)
204 displayhook_class = Type(DisplayHook)
205 display_pub_class = Type(DisplayPublisher)
205 display_pub_class = Type(DisplayPublisher)
206
206
207 exit_now = CBool(False)
207 exit_now = CBool(False)
208 exiter = Instance(ExitAutocall)
208 exiter = Instance(ExitAutocall)
209 def _exiter_default(self):
209 def _exiter_default(self):
210 return ExitAutocall(self)
210 return ExitAutocall(self)
211 # Monotonically increasing execution counter
211 # Monotonically increasing execution counter
212 execution_count = Int(1)
212 execution_count = Int(1)
213 filename = Unicode("<ipython console>")
213 filename = Unicode("<ipython console>")
214 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
214 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
215
215
216 # Input splitter, to split entire cells of input into either individual
216 # Input splitter, to split entire cells of input into either individual
217 # interactive statements or whole blocks.
217 # interactive statements or whole blocks.
218 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
218 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
219 (), {})
219 (), {})
220 logstart = CBool(False, config=True)
220 logstart = CBool(False, config=True)
221 logfile = Unicode('', config=True)
221 logfile = Unicode('', config=True)
222 logappend = Unicode('', config=True)
222 logappend = Unicode('', config=True)
223 object_info_string_level = Enum((0,1,2), default_value=0,
223 object_info_string_level = Enum((0,1,2), default_value=0,
224 config=True)
224 config=True)
225 pdb = CBool(False, config=True)
225 pdb = CBool(False, config=True)
226
226
227 profile = Unicode('', config=True)
227 profile = Unicode('', config=True)
228 prompt_in1 = Str('In [\\#]: ', config=True)
228 prompt_in1 = Str('In [\\#]: ', config=True)
229 prompt_in2 = Str(' .\\D.: ', config=True)
229 prompt_in2 = Str(' .\\D.: ', config=True)
230 prompt_out = Str('Out[\\#]: ', config=True)
230 prompt_out = Str('Out[\\#]: ', config=True)
231 prompts_pad_left = CBool(True, config=True)
231 prompts_pad_left = CBool(True, config=True)
232 quiet = CBool(False, config=True)
232 quiet = CBool(False, config=True)
233
233
234 history_length = Int(10000, config=True)
234 history_length = Int(10000, config=True)
235
235
236 # The readline stuff will eventually be moved to the terminal subclass
236 # The readline stuff will eventually be moved to the terminal subclass
237 # but for now, we can't do that as readline is welded in everywhere.
237 # but for now, we can't do that as readline is welded in everywhere.
238 readline_use = CBool(True, config=True)
238 readline_use = CBool(True, config=True)
239 readline_merge_completions = CBool(True, config=True)
239 readline_merge_completions = CBool(True, config=True)
240 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
240 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
241 readline_remove_delims = Str('-/~', config=True)
241 readline_remove_delims = Str('-/~', config=True)
242 readline_parse_and_bind = List([
242 readline_parse_and_bind = List([
243 'tab: complete',
243 'tab: complete',
244 '"\C-l": clear-screen',
244 '"\C-l": clear-screen',
245 'set show-all-if-ambiguous on',
245 'set show-all-if-ambiguous on',
246 '"\C-o": tab-insert',
246 '"\C-o": tab-insert',
247 # See bug gh-58 - with \M-i enabled, chars 0x9000-0x9fff
247 # See bug gh-58 - with \M-i enabled, chars 0x9000-0x9fff
248 # crash IPython.
248 # crash IPython.
249 '"\M-o": "\d\d\d\d"',
249 '"\M-o": "\d\d\d\d"',
250 '"\M-I": "\d\d\d\d"',
250 '"\M-I": "\d\d\d\d"',
251 '"\C-r": reverse-search-history',
251 '"\C-r": reverse-search-history',
252 '"\C-s": forward-search-history',
252 '"\C-s": forward-search-history',
253 '"\C-p": history-search-backward',
253 '"\C-p": history-search-backward',
254 '"\C-n": history-search-forward',
254 '"\C-n": history-search-forward',
255 '"\e[A": history-search-backward',
255 '"\e[A": history-search-backward',
256 '"\e[B": history-search-forward',
256 '"\e[B": history-search-forward',
257 '"\C-k": kill-line',
257 '"\C-k": kill-line',
258 '"\C-u": unix-line-discard',
258 '"\C-u": unix-line-discard',
259 ], allow_none=False, config=True)
259 ], allow_none=False, config=True)
260
260
261 # TODO: this part of prompt management should be moved to the frontends.
261 # TODO: this part of prompt management should be moved to the frontends.
262 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
262 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
263 separate_in = SeparateStr('\n', config=True)
263 separate_in = SeparateStr('\n', config=True)
264 separate_out = SeparateStr('', config=True)
264 separate_out = SeparateStr('', config=True)
265 separate_out2 = SeparateStr('', config=True)
265 separate_out2 = SeparateStr('', config=True)
266 wildcards_case_sensitive = CBool(True, config=True)
266 wildcards_case_sensitive = CBool(True, config=True)
267 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
267 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
268 default_value='Context', config=True)
268 default_value='Context', config=True)
269
269
270 # Subcomponents of InteractiveShell
270 # Subcomponents of InteractiveShell
271 alias_manager = Instance('IPython.core.alias.AliasManager')
271 alias_manager = Instance('IPython.core.alias.AliasManager')
272 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
272 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
273 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
273 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
274 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
274 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
275 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
275 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
276 plugin_manager = Instance('IPython.core.plugin.PluginManager')
276 plugin_manager = Instance('IPython.core.plugin.PluginManager')
277 payload_manager = Instance('IPython.core.payload.PayloadManager')
277 payload_manager = Instance('IPython.core.payload.PayloadManager')
278 history_manager = Instance('IPython.core.history.HistoryManager')
278 history_manager = Instance('IPython.core.history.HistoryManager')
279
279
280 # Private interface
280 # Private interface
281 _post_execute = Instance(dict)
281 _post_execute = Instance(dict)
282
282
283 def __init__(self, config=None, ipython_dir=None,
283 def __init__(self, config=None, ipython_dir=None,
284 user_ns=None, user_global_ns=None,
284 user_ns=None, user_global_ns=None,
285 custom_exceptions=((), None)):
285 custom_exceptions=((), None)):
286
286
287 # This is where traits with a config_key argument are updated
287 # This is where traits with a config_key argument are updated
288 # from the values on config.
288 # from the values on config.
289 super(InteractiveShell, self).__init__(config=config)
289 super(InteractiveShell, self).__init__(config=config)
290
290
291 # These are relatively independent and stateless
291 # These are relatively independent and stateless
292 self.init_ipython_dir(ipython_dir)
292 self.init_ipython_dir(ipython_dir)
293 self.init_instance_attrs()
293 self.init_instance_attrs()
294 self.init_environment()
294 self.init_environment()
295
295
296 # Create namespaces (user_ns, user_global_ns, etc.)
296 # Create namespaces (user_ns, user_global_ns, etc.)
297 self.init_create_namespaces(user_ns, user_global_ns)
297 self.init_create_namespaces(user_ns, user_global_ns)
298 # This has to be done after init_create_namespaces because it uses
298 # This has to be done after init_create_namespaces because it uses
299 # something in self.user_ns, but before init_sys_modules, which
299 # something in self.user_ns, but before init_sys_modules, which
300 # is the first thing to modify sys.
300 # is the first thing to modify sys.
301 # TODO: When we override sys.stdout and sys.stderr before this class
301 # TODO: When we override sys.stdout and sys.stderr before this class
302 # is created, we are saving the overridden ones here. Not sure if this
302 # is created, we are saving the overridden ones here. Not sure if this
303 # is what we want to do.
303 # is what we want to do.
304 self.save_sys_module_state()
304 self.save_sys_module_state()
305 self.init_sys_modules()
305 self.init_sys_modules()
306
306
307 # While we're trying to have each part of the code directly access what
307 # While we're trying to have each part of the code directly access what
308 # it needs without keeping redundant references to objects, we have too
308 # it needs without keeping redundant references to objects, we have too
309 # much legacy code that expects ip.db to exist.
309 # much legacy code that expects ip.db to exist.
310 self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db'))
310 self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db'))
311
311
312 self.init_history()
312 self.init_history()
313 self.init_encoding()
313 self.init_encoding()
314 self.init_prefilter()
314 self.init_prefilter()
315
315
316 Magic.__init__(self, self)
316 Magic.__init__(self, self)
317
317
318 self.init_syntax_highlighting()
318 self.init_syntax_highlighting()
319 self.init_hooks()
319 self.init_hooks()
320 self.init_pushd_popd_magic()
320 self.init_pushd_popd_magic()
321 # self.init_traceback_handlers use to be here, but we moved it below
321 # self.init_traceback_handlers use to be here, but we moved it below
322 # because it and init_io have to come after init_readline.
322 # because it and init_io have to come after init_readline.
323 self.init_user_ns()
323 self.init_user_ns()
324 self.init_logger()
324 self.init_logger()
325 self.init_alias()
325 self.init_alias()
326 self.init_builtins()
326 self.init_builtins()
327
327
328 # pre_config_initialization
328 # pre_config_initialization
329
329
330 # The next section should contain everything that was in ipmaker.
330 # The next section should contain everything that was in ipmaker.
331 self.init_logstart()
331 self.init_logstart()
332
332
333 # The following was in post_config_initialization
333 # The following was in post_config_initialization
334 self.init_inspector()
334 self.init_inspector()
335 # init_readline() must come before init_io(), because init_io uses
335 # init_readline() must come before init_io(), because init_io uses
336 # readline related things.
336 # readline related things.
337 self.init_readline()
337 self.init_readline()
338 # init_completer must come after init_readline, because it needs to
338 # init_completer must come after init_readline, because it needs to
339 # know whether readline is present or not system-wide to configure the
339 # know whether readline is present or not system-wide to configure the
340 # completers, since the completion machinery can now operate
340 # completers, since the completion machinery can now operate
341 # independently of readline (e.g. over the network)
341 # independently of readline (e.g. over the network)
342 self.init_completer()
342 self.init_completer()
343 # TODO: init_io() needs to happen before init_traceback handlers
343 # TODO: init_io() needs to happen before init_traceback handlers
344 # because the traceback handlers hardcode the stdout/stderr streams.
344 # because the traceback handlers hardcode the stdout/stderr streams.
345 # This logic in in debugger.Pdb and should eventually be changed.
345 # This logic in in debugger.Pdb and should eventually be changed.
346 self.init_io()
346 self.init_io()
347 self.init_traceback_handlers(custom_exceptions)
347 self.init_traceback_handlers(custom_exceptions)
348 self.init_prompts()
348 self.init_prompts()
349 self.init_display_formatter()
349 self.init_display_formatter()
350 self.init_display_pub()
350 self.init_display_pub()
351 self.init_displayhook()
351 self.init_displayhook()
352 self.init_reload_doctest()
352 self.init_reload_doctest()
353 self.init_magics()
353 self.init_magics()
354 self.init_pdb()
354 self.init_pdb()
355 self.init_extension_manager()
355 self.init_extension_manager()
356 self.init_plugin_manager()
356 self.init_plugin_manager()
357 self.init_payload()
357 self.init_payload()
358 self.hooks.late_startup_hook()
358 self.hooks.late_startup_hook()
359 atexit.register(self.atexit_operations)
359 atexit.register(self.atexit_operations)
360
360
361 @classmethod
361 @classmethod
362 def instance(cls, *args, **kwargs):
362 def instance(cls, *args, **kwargs):
363 """Returns a global InteractiveShell instance."""
363 """Returns a global InteractiveShell instance."""
364 if cls._instance is None:
364 if cls._instance is None:
365 inst = cls(*args, **kwargs)
365 inst = cls(*args, **kwargs)
366 # Now make sure that the instance will also be returned by
366 # Now make sure that the instance will also be returned by
367 # the subclasses instance attribute.
367 # the subclasses instance attribute.
368 for subclass in cls.mro():
368 for subclass in cls.mro():
369 if issubclass(cls, subclass) and \
369 if issubclass(cls, subclass) and \
370 issubclass(subclass, InteractiveShell):
370 issubclass(subclass, InteractiveShell):
371 subclass._instance = inst
371 subclass._instance = inst
372 else:
372 else:
373 break
373 break
374 if isinstance(cls._instance, cls):
374 if isinstance(cls._instance, cls):
375 return cls._instance
375 return cls._instance
376 else:
376 else:
377 raise MultipleInstanceError(
377 raise MultipleInstanceError(
378 'Multiple incompatible subclass instances of '
378 'Multiple incompatible subclass instances of '
379 'InteractiveShell are being created.'
379 'InteractiveShell are being created.'
380 )
380 )
381
381
382 @classmethod
382 @classmethod
383 def initialized(cls):
383 def initialized(cls):
384 return hasattr(cls, "_instance")
384 return hasattr(cls, "_instance")
385
385
386 def get_ipython(self):
386 def get_ipython(self):
387 """Return the currently running IPython instance."""
387 """Return the currently running IPython instance."""
388 return self
388 return self
389
389
390 #-------------------------------------------------------------------------
390 #-------------------------------------------------------------------------
391 # Trait changed handlers
391 # Trait changed handlers
392 #-------------------------------------------------------------------------
392 #-------------------------------------------------------------------------
393
393
394 def _ipython_dir_changed(self, name, new):
394 def _ipython_dir_changed(self, name, new):
395 if not os.path.isdir(new):
395 if not os.path.isdir(new):
396 os.makedirs(new, mode = 0777)
396 os.makedirs(new, mode = 0777)
397
397
398 def set_autoindent(self,value=None):
398 def set_autoindent(self,value=None):
399 """Set the autoindent flag, checking for readline support.
399 """Set the autoindent flag, checking for readline support.
400
400
401 If called with no arguments, it acts as a toggle."""
401 If called with no arguments, it acts as a toggle."""
402
402
403 if not self.has_readline:
403 if not self.has_readline:
404 if os.name == 'posix':
404 if os.name == 'posix':
405 warn("The auto-indent feature requires the readline library")
405 warn("The auto-indent feature requires the readline library")
406 self.autoindent = 0
406 self.autoindent = 0
407 return
407 return
408 if value is None:
408 if value is None:
409 self.autoindent = not self.autoindent
409 self.autoindent = not self.autoindent
410 else:
410 else:
411 self.autoindent = value
411 self.autoindent = value
412
412
413 #-------------------------------------------------------------------------
413 #-------------------------------------------------------------------------
414 # init_* methods called by __init__
414 # init_* methods called by __init__
415 #-------------------------------------------------------------------------
415 #-------------------------------------------------------------------------
416
416
417 def init_ipython_dir(self, ipython_dir):
417 def init_ipython_dir(self, ipython_dir):
418 if ipython_dir is not None:
418 if ipython_dir is not None:
419 self.ipython_dir = ipython_dir
419 self.ipython_dir = ipython_dir
420 self.config.Global.ipython_dir = self.ipython_dir
420 self.config.Global.ipython_dir = self.ipython_dir
421 return
421 return
422
422
423 if hasattr(self.config.Global, 'ipython_dir'):
423 if hasattr(self.config.Global, 'ipython_dir'):
424 self.ipython_dir = self.config.Global.ipython_dir
424 self.ipython_dir = self.config.Global.ipython_dir
425 else:
425 else:
426 self.ipython_dir = get_ipython_dir()
426 self.ipython_dir = get_ipython_dir()
427
427
428 # All children can just read this
428 # All children can just read this
429 self.config.Global.ipython_dir = self.ipython_dir
429 self.config.Global.ipython_dir = self.ipython_dir
430
430
431 def init_instance_attrs(self):
431 def init_instance_attrs(self):
432 self.more = False
432 self.more = False
433
433
434 # command compiler
434 # command compiler
435 self.compile = CachingCompiler()
435 self.compile = CachingCompiler()
436
436
437 # Make an empty namespace, which extension writers can rely on both
437 # Make an empty namespace, which extension writers can rely on both
438 # existing and NEVER being used by ipython itself. This gives them a
438 # existing and NEVER being used by ipython itself. This gives them a
439 # convenient location for storing additional information and state
439 # convenient location for storing additional information and state
440 # their extensions may require, without fear of collisions with other
440 # their extensions may require, without fear of collisions with other
441 # ipython names that may develop later.
441 # ipython names that may develop later.
442 self.meta = Struct()
442 self.meta = Struct()
443
443
444 # Temporary files used for various purposes. Deleted at exit.
444 # Temporary files used for various purposes. Deleted at exit.
445 self.tempfiles = []
445 self.tempfiles = []
446
446
447 # Keep track of readline usage (later set by init_readline)
447 # Keep track of readline usage (later set by init_readline)
448 self.has_readline = False
448 self.has_readline = False
449
449
450 # keep track of where we started running (mainly for crash post-mortem)
450 # keep track of where we started running (mainly for crash post-mortem)
451 # This is not being used anywhere currently.
451 # This is not being used anywhere currently.
452 self.starting_dir = os.getcwd()
452 self.starting_dir = os.getcwd()
453
453
454 # Indentation management
454 # Indentation management
455 self.indent_current_nsp = 0
455 self.indent_current_nsp = 0
456
456
457 # Dict to track post-execution functions that have been registered
457 # Dict to track post-execution functions that have been registered
458 self._post_execute = {}
458 self._post_execute = {}
459
459
460 def init_environment(self):
460 def init_environment(self):
461 """Any changes we need to make to the user's environment."""
461 """Any changes we need to make to the user's environment."""
462 pass
462 pass
463
463
464 def init_encoding(self):
464 def init_encoding(self):
465 # Get system encoding at startup time. Certain terminals (like Emacs
465 # Get system encoding at startup time. Certain terminals (like Emacs
466 # under Win32 have it set to None, and we need to have a known valid
466 # under Win32 have it set to None, and we need to have a known valid
467 # encoding to use in the raw_input() method
467 # encoding to use in the raw_input() method
468 try:
468 try:
469 self.stdin_encoding = sys.stdin.encoding or 'ascii'
469 self.stdin_encoding = sys.stdin.encoding or 'ascii'
470 except AttributeError:
470 except AttributeError:
471 self.stdin_encoding = 'ascii'
471 self.stdin_encoding = 'ascii'
472
472
473 def init_syntax_highlighting(self):
473 def init_syntax_highlighting(self):
474 # Python source parser/formatter for syntax highlighting
474 # Python source parser/formatter for syntax highlighting
475 pyformat = PyColorize.Parser().format
475 pyformat = PyColorize.Parser().format
476 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
476 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
477
477
478 def init_pushd_popd_magic(self):
478 def init_pushd_popd_magic(self):
479 # for pushd/popd management
479 # for pushd/popd management
480 try:
480 try:
481 self.home_dir = get_home_dir()
481 self.home_dir = get_home_dir()
482 except HomeDirError, msg:
482 except HomeDirError, msg:
483 fatal(msg)
483 fatal(msg)
484
484
485 self.dir_stack = []
485 self.dir_stack = []
486
486
487 def init_logger(self):
487 def init_logger(self):
488 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
488 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
489 logmode='rotate')
489 logmode='rotate')
490
490
491 def init_logstart(self):
491 def init_logstart(self):
492 """Initialize logging in case it was requested at the command line.
492 """Initialize logging in case it was requested at the command line.
493 """
493 """
494 if self.logappend:
494 if self.logappend:
495 self.magic_logstart(self.logappend + ' append')
495 self.magic_logstart(self.logappend + ' append')
496 elif self.logfile:
496 elif self.logfile:
497 self.magic_logstart(self.logfile)
497 self.magic_logstart(self.logfile)
498 elif self.logstart:
498 elif self.logstart:
499 self.magic_logstart()
499 self.magic_logstart()
500
500
501 def init_builtins(self):
501 def init_builtins(self):
502 self.builtin_trap = BuiltinTrap(shell=self)
502 self.builtin_trap = BuiltinTrap(shell=self)
503
503
504 def init_inspector(self):
504 def init_inspector(self):
505 # Object inspector
505 # Object inspector
506 self.inspector = oinspect.Inspector(oinspect.InspectColors,
506 self.inspector = oinspect.Inspector(oinspect.InspectColors,
507 PyColorize.ANSICodeColors,
507 PyColorize.ANSICodeColors,
508 'NoColor',
508 'NoColor',
509 self.object_info_string_level)
509 self.object_info_string_level)
510
510
511 def init_io(self):
511 def init_io(self):
512 # This will just use sys.stdout and sys.stderr. If you want to
512 # This will just use sys.stdout and sys.stderr. If you want to
513 # override sys.stdout and sys.stderr themselves, you need to do that
513 # override sys.stdout and sys.stderr themselves, you need to do that
514 # *before* instantiating this class, because Term holds onto
514 # *before* instantiating this class, because io holds onto
515 # references to the underlying streams.
515 # references to the underlying streams.
516 if sys.platform == 'win32' and self.has_readline:
516 if sys.platform == 'win32' and self.has_readline:
517 Term = io.IOTerm(cout=self.readline._outputfile,
517 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
518 cerr=self.readline._outputfile)
519 else:
518 else:
520 Term = io.IOTerm()
519 io.stdout = io.IOStream(sys.stdout)
521 io.Term = Term
520 io.stderr = io.IOStream(sys.stderr)
522
521
523 def init_prompts(self):
522 def init_prompts(self):
524 # TODO: This is a pass for now because the prompts are managed inside
523 # TODO: This is a pass for now because the prompts are managed inside
525 # the DisplayHook. Once there is a separate prompt manager, this
524 # the DisplayHook. Once there is a separate prompt manager, this
526 # will initialize that object and all prompt related information.
525 # will initialize that object and all prompt related information.
527 pass
526 pass
528
527
529 def init_display_formatter(self):
528 def init_display_formatter(self):
530 self.display_formatter = DisplayFormatter(config=self.config)
529 self.display_formatter = DisplayFormatter(config=self.config)
531
530
532 def init_display_pub(self):
531 def init_display_pub(self):
533 self.display_pub = self.display_pub_class(config=self.config)
532 self.display_pub = self.display_pub_class(config=self.config)
534
533
535 def init_displayhook(self):
534 def init_displayhook(self):
536 # Initialize displayhook, set in/out prompts and printing system
535 # Initialize displayhook, set in/out prompts and printing system
537 self.displayhook = self.displayhook_class(
536 self.displayhook = self.displayhook_class(
538 config=self.config,
537 config=self.config,
539 shell=self,
538 shell=self,
540 cache_size=self.cache_size,
539 cache_size=self.cache_size,
541 input_sep = self.separate_in,
540 input_sep = self.separate_in,
542 output_sep = self.separate_out,
541 output_sep = self.separate_out,
543 output_sep2 = self.separate_out2,
542 output_sep2 = self.separate_out2,
544 ps1 = self.prompt_in1,
543 ps1 = self.prompt_in1,
545 ps2 = self.prompt_in2,
544 ps2 = self.prompt_in2,
546 ps_out = self.prompt_out,
545 ps_out = self.prompt_out,
547 pad_left = self.prompts_pad_left
546 pad_left = self.prompts_pad_left
548 )
547 )
549 # This is a context manager that installs/revmoes the displayhook at
548 # This is a context manager that installs/revmoes the displayhook at
550 # the appropriate time.
549 # the appropriate time.
551 self.display_trap = DisplayTrap(hook=self.displayhook)
550 self.display_trap = DisplayTrap(hook=self.displayhook)
552
551
553 def init_reload_doctest(self):
552 def init_reload_doctest(self):
554 # Do a proper resetting of doctest, including the necessary displayhook
553 # Do a proper resetting of doctest, including the necessary displayhook
555 # monkeypatching
554 # monkeypatching
556 try:
555 try:
557 doctest_reload()
556 doctest_reload()
558 except ImportError:
557 except ImportError:
559 warn("doctest module does not exist.")
558 warn("doctest module does not exist.")
560
559
561 #-------------------------------------------------------------------------
560 #-------------------------------------------------------------------------
562 # Things related to injections into the sys module
561 # Things related to injections into the sys module
563 #-------------------------------------------------------------------------
562 #-------------------------------------------------------------------------
564
563
565 def save_sys_module_state(self):
564 def save_sys_module_state(self):
566 """Save the state of hooks in the sys module.
565 """Save the state of hooks in the sys module.
567
566
568 This has to be called after self.user_ns is created.
567 This has to be called after self.user_ns is created.
569 """
568 """
570 self._orig_sys_module_state = {}
569 self._orig_sys_module_state = {}
571 self._orig_sys_module_state['stdin'] = sys.stdin
570 self._orig_sys_module_state['stdin'] = sys.stdin
572 self._orig_sys_module_state['stdout'] = sys.stdout
571 self._orig_sys_module_state['stdout'] = sys.stdout
573 self._orig_sys_module_state['stderr'] = sys.stderr
572 self._orig_sys_module_state['stderr'] = sys.stderr
574 self._orig_sys_module_state['excepthook'] = sys.excepthook
573 self._orig_sys_module_state['excepthook'] = sys.excepthook
575 try:
574 try:
576 self._orig_sys_modules_main_name = self.user_ns['__name__']
575 self._orig_sys_modules_main_name = self.user_ns['__name__']
577 except KeyError:
576 except KeyError:
578 pass
577 pass
579
578
580 def restore_sys_module_state(self):
579 def restore_sys_module_state(self):
581 """Restore the state of the sys module."""
580 """Restore the state of the sys module."""
582 try:
581 try:
583 for k, v in self._orig_sys_module_state.iteritems():
582 for k, v in self._orig_sys_module_state.iteritems():
584 setattr(sys, k, v)
583 setattr(sys, k, v)
585 except AttributeError:
584 except AttributeError:
586 pass
585 pass
587 # Reset what what done in self.init_sys_modules
586 # Reset what what done in self.init_sys_modules
588 try:
587 try:
589 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
588 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
590 except (AttributeError, KeyError):
589 except (AttributeError, KeyError):
591 pass
590 pass
592
591
593 #-------------------------------------------------------------------------
592 #-------------------------------------------------------------------------
594 # Things related to hooks
593 # Things related to hooks
595 #-------------------------------------------------------------------------
594 #-------------------------------------------------------------------------
596
595
597 def init_hooks(self):
596 def init_hooks(self):
598 # hooks holds pointers used for user-side customizations
597 # hooks holds pointers used for user-side customizations
599 self.hooks = Struct()
598 self.hooks = Struct()
600
599
601 self.strdispatchers = {}
600 self.strdispatchers = {}
602
601
603 # Set all default hooks, defined in the IPython.hooks module.
602 # Set all default hooks, defined in the IPython.hooks module.
604 hooks = IPython.core.hooks
603 hooks = IPython.core.hooks
605 for hook_name in hooks.__all__:
604 for hook_name in hooks.__all__:
606 # default hooks have priority 100, i.e. low; user hooks should have
605 # default hooks have priority 100, i.e. low; user hooks should have
607 # 0-100 priority
606 # 0-100 priority
608 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
607 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
609
608
610 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
609 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
611 """set_hook(name,hook) -> sets an internal IPython hook.
610 """set_hook(name,hook) -> sets an internal IPython hook.
612
611
613 IPython exposes some of its internal API as user-modifiable hooks. By
612 IPython exposes some of its internal API as user-modifiable hooks. By
614 adding your function to one of these hooks, you can modify IPython's
613 adding your function to one of these hooks, you can modify IPython's
615 behavior to call at runtime your own routines."""
614 behavior to call at runtime your own routines."""
616
615
617 # At some point in the future, this should validate the hook before it
616 # At some point in the future, this should validate the hook before it
618 # accepts it. Probably at least check that the hook takes the number
617 # accepts it. Probably at least check that the hook takes the number
619 # of args it's supposed to.
618 # of args it's supposed to.
620
619
621 f = types.MethodType(hook,self)
620 f = types.MethodType(hook,self)
622
621
623 # check if the hook is for strdispatcher first
622 # check if the hook is for strdispatcher first
624 if str_key is not None:
623 if str_key is not None:
625 sdp = self.strdispatchers.get(name, StrDispatch())
624 sdp = self.strdispatchers.get(name, StrDispatch())
626 sdp.add_s(str_key, f, priority )
625 sdp.add_s(str_key, f, priority )
627 self.strdispatchers[name] = sdp
626 self.strdispatchers[name] = sdp
628 return
627 return
629 if re_key is not None:
628 if re_key is not None:
630 sdp = self.strdispatchers.get(name, StrDispatch())
629 sdp = self.strdispatchers.get(name, StrDispatch())
631 sdp.add_re(re.compile(re_key), f, priority )
630 sdp.add_re(re.compile(re_key), f, priority )
632 self.strdispatchers[name] = sdp
631 self.strdispatchers[name] = sdp
633 return
632 return
634
633
635 dp = getattr(self.hooks, name, None)
634 dp = getattr(self.hooks, name, None)
636 if name not in IPython.core.hooks.__all__:
635 if name not in IPython.core.hooks.__all__:
637 print "Warning! Hook '%s' is not one of %s" % \
636 print "Warning! Hook '%s' is not one of %s" % \
638 (name, IPython.core.hooks.__all__ )
637 (name, IPython.core.hooks.__all__ )
639 if not dp:
638 if not dp:
640 dp = IPython.core.hooks.CommandChainDispatcher()
639 dp = IPython.core.hooks.CommandChainDispatcher()
641
640
642 try:
641 try:
643 dp.add(f,priority)
642 dp.add(f,priority)
644 except AttributeError:
643 except AttributeError:
645 # it was not commandchain, plain old func - replace
644 # it was not commandchain, plain old func - replace
646 dp = f
645 dp = f
647
646
648 setattr(self.hooks,name, dp)
647 setattr(self.hooks,name, dp)
649
648
650 def register_post_execute(self, func):
649 def register_post_execute(self, func):
651 """Register a function for calling after code execution.
650 """Register a function for calling after code execution.
652 """
651 """
653 if not callable(func):
652 if not callable(func):
654 raise ValueError('argument %s must be callable' % func)
653 raise ValueError('argument %s must be callable' % func)
655 self._post_execute[func] = True
654 self._post_execute[func] = True
656
655
657 #-------------------------------------------------------------------------
656 #-------------------------------------------------------------------------
658 # Things related to the "main" module
657 # Things related to the "main" module
659 #-------------------------------------------------------------------------
658 #-------------------------------------------------------------------------
660
659
661 def new_main_mod(self,ns=None):
660 def new_main_mod(self,ns=None):
662 """Return a new 'main' module object for user code execution.
661 """Return a new 'main' module object for user code execution.
663 """
662 """
664 main_mod = self._user_main_module
663 main_mod = self._user_main_module
665 init_fakemod_dict(main_mod,ns)
664 init_fakemod_dict(main_mod,ns)
666 return main_mod
665 return main_mod
667
666
668 def cache_main_mod(self,ns,fname):
667 def cache_main_mod(self,ns,fname):
669 """Cache a main module's namespace.
668 """Cache a main module's namespace.
670
669
671 When scripts are executed via %run, we must keep a reference to the
670 When scripts are executed via %run, we must keep a reference to the
672 namespace of their __main__ module (a FakeModule instance) around so
671 namespace of their __main__ module (a FakeModule instance) around so
673 that Python doesn't clear it, rendering objects defined therein
672 that Python doesn't clear it, rendering objects defined therein
674 useless.
673 useless.
675
674
676 This method keeps said reference in a private dict, keyed by the
675 This method keeps said reference in a private dict, keyed by the
677 absolute path of the module object (which corresponds to the script
676 absolute path of the module object (which corresponds to the script
678 path). This way, for multiple executions of the same script we only
677 path). This way, for multiple executions of the same script we only
679 keep one copy of the namespace (the last one), thus preventing memory
678 keep one copy of the namespace (the last one), thus preventing memory
680 leaks from old references while allowing the objects from the last
679 leaks from old references while allowing the objects from the last
681 execution to be accessible.
680 execution to be accessible.
682
681
683 Note: we can not allow the actual FakeModule instances to be deleted,
682 Note: we can not allow the actual FakeModule instances to be deleted,
684 because of how Python tears down modules (it hard-sets all their
683 because of how Python tears down modules (it hard-sets all their
685 references to None without regard for reference counts). This method
684 references to None without regard for reference counts). This method
686 must therefore make a *copy* of the given namespace, to allow the
685 must therefore make a *copy* of the given namespace, to allow the
687 original module's __dict__ to be cleared and reused.
686 original module's __dict__ to be cleared and reused.
688
687
689
688
690 Parameters
689 Parameters
691 ----------
690 ----------
692 ns : a namespace (a dict, typically)
691 ns : a namespace (a dict, typically)
693
692
694 fname : str
693 fname : str
695 Filename associated with the namespace.
694 Filename associated with the namespace.
696
695
697 Examples
696 Examples
698 --------
697 --------
699
698
700 In [10]: import IPython
699 In [10]: import IPython
701
700
702 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
701 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
703
702
704 In [12]: IPython.__file__ in _ip._main_ns_cache
703 In [12]: IPython.__file__ in _ip._main_ns_cache
705 Out[12]: True
704 Out[12]: True
706 """
705 """
707 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
706 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
708
707
709 def clear_main_mod_cache(self):
708 def clear_main_mod_cache(self):
710 """Clear the cache of main modules.
709 """Clear the cache of main modules.
711
710
712 Mainly for use by utilities like %reset.
711 Mainly for use by utilities like %reset.
713
712
714 Examples
713 Examples
715 --------
714 --------
716
715
717 In [15]: import IPython
716 In [15]: import IPython
718
717
719 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
718 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
720
719
721 In [17]: len(_ip._main_ns_cache) > 0
720 In [17]: len(_ip._main_ns_cache) > 0
722 Out[17]: True
721 Out[17]: True
723
722
724 In [18]: _ip.clear_main_mod_cache()
723 In [18]: _ip.clear_main_mod_cache()
725
724
726 In [19]: len(_ip._main_ns_cache) == 0
725 In [19]: len(_ip._main_ns_cache) == 0
727 Out[19]: True
726 Out[19]: True
728 """
727 """
729 self._main_ns_cache.clear()
728 self._main_ns_cache.clear()
730
729
731 #-------------------------------------------------------------------------
730 #-------------------------------------------------------------------------
732 # Things related to debugging
731 # Things related to debugging
733 #-------------------------------------------------------------------------
732 #-------------------------------------------------------------------------
734
733
735 def init_pdb(self):
734 def init_pdb(self):
736 # Set calling of pdb on exceptions
735 # Set calling of pdb on exceptions
737 # self.call_pdb is a property
736 # self.call_pdb is a property
738 self.call_pdb = self.pdb
737 self.call_pdb = self.pdb
739
738
740 def _get_call_pdb(self):
739 def _get_call_pdb(self):
741 return self._call_pdb
740 return self._call_pdb
742
741
743 def _set_call_pdb(self,val):
742 def _set_call_pdb(self,val):
744
743
745 if val not in (0,1,False,True):
744 if val not in (0,1,False,True):
746 raise ValueError,'new call_pdb value must be boolean'
745 raise ValueError,'new call_pdb value must be boolean'
747
746
748 # store value in instance
747 # store value in instance
749 self._call_pdb = val
748 self._call_pdb = val
750
749
751 # notify the actual exception handlers
750 # notify the actual exception handlers
752 self.InteractiveTB.call_pdb = val
751 self.InteractiveTB.call_pdb = val
753
752
754 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
753 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
755 'Control auto-activation of pdb at exceptions')
754 'Control auto-activation of pdb at exceptions')
756
755
757 def debugger(self,force=False):
756 def debugger(self,force=False):
758 """Call the pydb/pdb debugger.
757 """Call the pydb/pdb debugger.
759
758
760 Keywords:
759 Keywords:
761
760
762 - force(False): by default, this routine checks the instance call_pdb
761 - force(False): by default, this routine checks the instance call_pdb
763 flag and does not actually invoke the debugger if the flag is false.
762 flag and does not actually invoke the debugger if the flag is false.
764 The 'force' option forces the debugger to activate even if the flag
763 The 'force' option forces the debugger to activate even if the flag
765 is false.
764 is false.
766 """
765 """
767
766
768 if not (force or self.call_pdb):
767 if not (force or self.call_pdb):
769 return
768 return
770
769
771 if not hasattr(sys,'last_traceback'):
770 if not hasattr(sys,'last_traceback'):
772 error('No traceback has been produced, nothing to debug.')
771 error('No traceback has been produced, nothing to debug.')
773 return
772 return
774
773
775 # use pydb if available
774 # use pydb if available
776 if debugger.has_pydb:
775 if debugger.has_pydb:
777 from pydb import pm
776 from pydb import pm
778 else:
777 else:
779 # fallback to our internal debugger
778 # fallback to our internal debugger
780 pm = lambda : self.InteractiveTB.debugger(force=True)
779 pm = lambda : self.InteractiveTB.debugger(force=True)
781
780
782 with self.readline_no_record:
781 with self.readline_no_record:
783 pm()
782 pm()
784
783
785 #-------------------------------------------------------------------------
784 #-------------------------------------------------------------------------
786 # Things related to IPython's various namespaces
785 # Things related to IPython's various namespaces
787 #-------------------------------------------------------------------------
786 #-------------------------------------------------------------------------
788
787
789 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
788 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
790 # Create the namespace where the user will operate. user_ns is
789 # Create the namespace where the user will operate. user_ns is
791 # normally the only one used, and it is passed to the exec calls as
790 # normally the only one used, and it is passed to the exec calls as
792 # the locals argument. But we do carry a user_global_ns namespace
791 # the locals argument. But we do carry a user_global_ns namespace
793 # given as the exec 'globals' argument, This is useful in embedding
792 # given as the exec 'globals' argument, This is useful in embedding
794 # situations where the ipython shell opens in a context where the
793 # situations where the ipython shell opens in a context where the
795 # distinction between locals and globals is meaningful. For
794 # distinction between locals and globals is meaningful. For
796 # non-embedded contexts, it is just the same object as the user_ns dict.
795 # non-embedded contexts, it is just the same object as the user_ns dict.
797
796
798 # FIXME. For some strange reason, __builtins__ is showing up at user
797 # FIXME. For some strange reason, __builtins__ is showing up at user
799 # level as a dict instead of a module. This is a manual fix, but I
798 # level as a dict instead of a module. This is a manual fix, but I
800 # should really track down where the problem is coming from. Alex
799 # should really track down where the problem is coming from. Alex
801 # Schmolck reported this problem first.
800 # Schmolck reported this problem first.
802
801
803 # A useful post by Alex Martelli on this topic:
802 # A useful post by Alex Martelli on this topic:
804 # Re: inconsistent value from __builtins__
803 # Re: inconsistent value from __builtins__
805 # Von: Alex Martelli <aleaxit@yahoo.com>
804 # Von: Alex Martelli <aleaxit@yahoo.com>
806 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
805 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
807 # Gruppen: comp.lang.python
806 # Gruppen: comp.lang.python
808
807
809 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
808 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
810 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
809 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
811 # > <type 'dict'>
810 # > <type 'dict'>
812 # > >>> print type(__builtins__)
811 # > >>> print type(__builtins__)
813 # > <type 'module'>
812 # > <type 'module'>
814 # > Is this difference in return value intentional?
813 # > Is this difference in return value intentional?
815
814
816 # Well, it's documented that '__builtins__' can be either a dictionary
815 # Well, it's documented that '__builtins__' can be either a dictionary
817 # or a module, and it's been that way for a long time. Whether it's
816 # or a module, and it's been that way for a long time. Whether it's
818 # intentional (or sensible), I don't know. In any case, the idea is
817 # intentional (or sensible), I don't know. In any case, the idea is
819 # that if you need to access the built-in namespace directly, you
818 # that if you need to access the built-in namespace directly, you
820 # should start with "import __builtin__" (note, no 's') which will
819 # should start with "import __builtin__" (note, no 's') which will
821 # definitely give you a module. Yeah, it's somewhat confusing:-(.
820 # definitely give you a module. Yeah, it's somewhat confusing:-(.
822
821
823 # These routines return properly built dicts as needed by the rest of
822 # These routines return properly built dicts as needed by the rest of
824 # the code, and can also be used by extension writers to generate
823 # the code, and can also be used by extension writers to generate
825 # properly initialized namespaces.
824 # properly initialized namespaces.
826 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
825 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
827 user_global_ns)
826 user_global_ns)
828
827
829 # Assign namespaces
828 # Assign namespaces
830 # This is the namespace where all normal user variables live
829 # This is the namespace where all normal user variables live
831 self.user_ns = user_ns
830 self.user_ns = user_ns
832 self.user_global_ns = user_global_ns
831 self.user_global_ns = user_global_ns
833
832
834 # An auxiliary namespace that checks what parts of the user_ns were
833 # An auxiliary namespace that checks what parts of the user_ns were
835 # loaded at startup, so we can list later only variables defined in
834 # loaded at startup, so we can list later only variables defined in
836 # actual interactive use. Since it is always a subset of user_ns, it
835 # actual interactive use. Since it is always a subset of user_ns, it
837 # doesn't need to be separately tracked in the ns_table.
836 # doesn't need to be separately tracked in the ns_table.
838 self.user_ns_hidden = {}
837 self.user_ns_hidden = {}
839
838
840 # A namespace to keep track of internal data structures to prevent
839 # A namespace to keep track of internal data structures to prevent
841 # them from cluttering user-visible stuff. Will be updated later
840 # them from cluttering user-visible stuff. Will be updated later
842 self.internal_ns = {}
841 self.internal_ns = {}
843
842
844 # Now that FakeModule produces a real module, we've run into a nasty
843 # Now that FakeModule produces a real module, we've run into a nasty
845 # problem: after script execution (via %run), the module where the user
844 # problem: after script execution (via %run), the module where the user
846 # code ran is deleted. Now that this object is a true module (needed
845 # code ran is deleted. Now that this object is a true module (needed
847 # so docetst and other tools work correctly), the Python module
846 # so docetst and other tools work correctly), the Python module
848 # teardown mechanism runs over it, and sets to None every variable
847 # teardown mechanism runs over it, and sets to None every variable
849 # present in that module. Top-level references to objects from the
848 # present in that module. Top-level references to objects from the
850 # script survive, because the user_ns is updated with them. However,
849 # script survive, because the user_ns is updated with them. However,
851 # calling functions defined in the script that use other things from
850 # calling functions defined in the script that use other things from
852 # the script will fail, because the function's closure had references
851 # the script will fail, because the function's closure had references
853 # to the original objects, which are now all None. So we must protect
852 # to the original objects, which are now all None. So we must protect
854 # these modules from deletion by keeping a cache.
853 # these modules from deletion by keeping a cache.
855 #
854 #
856 # To avoid keeping stale modules around (we only need the one from the
855 # To avoid keeping stale modules around (we only need the one from the
857 # last run), we use a dict keyed with the full path to the script, so
856 # last run), we use a dict keyed with the full path to the script, so
858 # only the last version of the module is held in the cache. Note,
857 # only the last version of the module is held in the cache. Note,
859 # however, that we must cache the module *namespace contents* (their
858 # however, that we must cache the module *namespace contents* (their
860 # __dict__). Because if we try to cache the actual modules, old ones
859 # __dict__). Because if we try to cache the actual modules, old ones
861 # (uncached) could be destroyed while still holding references (such as
860 # (uncached) could be destroyed while still holding references (such as
862 # those held by GUI objects that tend to be long-lived)>
861 # those held by GUI objects that tend to be long-lived)>
863 #
862 #
864 # The %reset command will flush this cache. See the cache_main_mod()
863 # The %reset command will flush this cache. See the cache_main_mod()
865 # and clear_main_mod_cache() methods for details on use.
864 # and clear_main_mod_cache() methods for details on use.
866
865
867 # This is the cache used for 'main' namespaces
866 # This is the cache used for 'main' namespaces
868 self._main_ns_cache = {}
867 self._main_ns_cache = {}
869 # And this is the single instance of FakeModule whose __dict__ we keep
868 # And this is the single instance of FakeModule whose __dict__ we keep
870 # copying and clearing for reuse on each %run
869 # copying and clearing for reuse on each %run
871 self._user_main_module = FakeModule()
870 self._user_main_module = FakeModule()
872
871
873 # A table holding all the namespaces IPython deals with, so that
872 # A table holding all the namespaces IPython deals with, so that
874 # introspection facilities can search easily.
873 # introspection facilities can search easily.
875 self.ns_table = {'user':user_ns,
874 self.ns_table = {'user':user_ns,
876 'user_global':user_global_ns,
875 'user_global':user_global_ns,
877 'internal':self.internal_ns,
876 'internal':self.internal_ns,
878 'builtin':__builtin__.__dict__
877 'builtin':__builtin__.__dict__
879 }
878 }
880
879
881 # Similarly, track all namespaces where references can be held and that
880 # Similarly, track all namespaces where references can be held and that
882 # we can safely clear (so it can NOT include builtin). This one can be
881 # we can safely clear (so it can NOT include builtin). This one can be
883 # a simple list. Note that the main execution namespaces, user_ns and
882 # a simple list. Note that the main execution namespaces, user_ns and
884 # user_global_ns, can NOT be listed here, as clearing them blindly
883 # user_global_ns, can NOT be listed here, as clearing them blindly
885 # causes errors in object __del__ methods. Instead, the reset() method
884 # causes errors in object __del__ methods. Instead, the reset() method
886 # clears them manually and carefully.
885 # clears them manually and carefully.
887 self.ns_refs_table = [ self.user_ns_hidden,
886 self.ns_refs_table = [ self.user_ns_hidden,
888 self.internal_ns, self._main_ns_cache ]
887 self.internal_ns, self._main_ns_cache ]
889
888
890 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
889 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
891 """Return a valid local and global user interactive namespaces.
890 """Return a valid local and global user interactive namespaces.
892
891
893 This builds a dict with the minimal information needed to operate as a
892 This builds a dict with the minimal information needed to operate as a
894 valid IPython user namespace, which you can pass to the various
893 valid IPython user namespace, which you can pass to the various
895 embedding classes in ipython. The default implementation returns the
894 embedding classes in ipython. The default implementation returns the
896 same dict for both the locals and the globals to allow functions to
895 same dict for both the locals and the globals to allow functions to
897 refer to variables in the namespace. Customized implementations can
896 refer to variables in the namespace. Customized implementations can
898 return different dicts. The locals dictionary can actually be anything
897 return different dicts. The locals dictionary can actually be anything
899 following the basic mapping protocol of a dict, but the globals dict
898 following the basic mapping protocol of a dict, but the globals dict
900 must be a true dict, not even a subclass. It is recommended that any
899 must be a true dict, not even a subclass. It is recommended that any
901 custom object for the locals namespace synchronize with the globals
900 custom object for the locals namespace synchronize with the globals
902 dict somehow.
901 dict somehow.
903
902
904 Raises TypeError if the provided globals namespace is not a true dict.
903 Raises TypeError if the provided globals namespace is not a true dict.
905
904
906 Parameters
905 Parameters
907 ----------
906 ----------
908 user_ns : dict-like, optional
907 user_ns : dict-like, optional
909 The current user namespace. The items in this namespace should
908 The current user namespace. The items in this namespace should
910 be included in the output. If None, an appropriate blank
909 be included in the output. If None, an appropriate blank
911 namespace should be created.
910 namespace should be created.
912 user_global_ns : dict, optional
911 user_global_ns : dict, optional
913 The current user global namespace. The items in this namespace
912 The current user global namespace. The items in this namespace
914 should be included in the output. If None, an appropriate
913 should be included in the output. If None, an appropriate
915 blank namespace should be created.
914 blank namespace should be created.
916
915
917 Returns
916 Returns
918 -------
917 -------
919 A pair of dictionary-like object to be used as the local namespace
918 A pair of dictionary-like object to be used as the local namespace
920 of the interpreter and a dict to be used as the global namespace.
919 of the interpreter and a dict to be used as the global namespace.
921 """
920 """
922
921
923
922
924 # We must ensure that __builtin__ (without the final 's') is always
923 # We must ensure that __builtin__ (without the final 's') is always
925 # available and pointing to the __builtin__ *module*. For more details:
924 # available and pointing to the __builtin__ *module*. For more details:
926 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
925 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
927
926
928 if user_ns is None:
927 if user_ns is None:
929 # Set __name__ to __main__ to better match the behavior of the
928 # Set __name__ to __main__ to better match the behavior of the
930 # normal interpreter.
929 # normal interpreter.
931 user_ns = {'__name__' :'__main__',
930 user_ns = {'__name__' :'__main__',
932 '__builtin__' : __builtin__,
931 '__builtin__' : __builtin__,
933 '__builtins__' : __builtin__,
932 '__builtins__' : __builtin__,
934 }
933 }
935 else:
934 else:
936 user_ns.setdefault('__name__','__main__')
935 user_ns.setdefault('__name__','__main__')
937 user_ns.setdefault('__builtin__',__builtin__)
936 user_ns.setdefault('__builtin__',__builtin__)
938 user_ns.setdefault('__builtins__',__builtin__)
937 user_ns.setdefault('__builtins__',__builtin__)
939
938
940 if user_global_ns is None:
939 if user_global_ns is None:
941 user_global_ns = user_ns
940 user_global_ns = user_ns
942 if type(user_global_ns) is not dict:
941 if type(user_global_ns) is not dict:
943 raise TypeError("user_global_ns must be a true dict; got %r"
942 raise TypeError("user_global_ns must be a true dict; got %r"
944 % type(user_global_ns))
943 % type(user_global_ns))
945
944
946 return user_ns, user_global_ns
945 return user_ns, user_global_ns
947
946
948 def init_sys_modules(self):
947 def init_sys_modules(self):
949 # We need to insert into sys.modules something that looks like a
948 # We need to insert into sys.modules something that looks like a
950 # module but which accesses the IPython namespace, for shelve and
949 # module but which accesses the IPython namespace, for shelve and
951 # pickle to work interactively. Normally they rely on getting
950 # pickle to work interactively. Normally they rely on getting
952 # everything out of __main__, but for embedding purposes each IPython
951 # everything out of __main__, but for embedding purposes each IPython
953 # instance has its own private namespace, so we can't go shoving
952 # instance has its own private namespace, so we can't go shoving
954 # everything into __main__.
953 # everything into __main__.
955
954
956 # note, however, that we should only do this for non-embedded
955 # note, however, that we should only do this for non-embedded
957 # ipythons, which really mimic the __main__.__dict__ with their own
956 # ipythons, which really mimic the __main__.__dict__ with their own
958 # namespace. Embedded instances, on the other hand, should not do
957 # namespace. Embedded instances, on the other hand, should not do
959 # this because they need to manage the user local/global namespaces
958 # this because they need to manage the user local/global namespaces
960 # only, but they live within a 'normal' __main__ (meaning, they
959 # only, but they live within a 'normal' __main__ (meaning, they
961 # shouldn't overtake the execution environment of the script they're
960 # shouldn't overtake the execution environment of the script they're
962 # embedded in).
961 # embedded in).
963
962
964 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
963 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
965
964
966 try:
965 try:
967 main_name = self.user_ns['__name__']
966 main_name = self.user_ns['__name__']
968 except KeyError:
967 except KeyError:
969 raise KeyError('user_ns dictionary MUST have a "__name__" key')
968 raise KeyError('user_ns dictionary MUST have a "__name__" key')
970 else:
969 else:
971 sys.modules[main_name] = FakeModule(self.user_ns)
970 sys.modules[main_name] = FakeModule(self.user_ns)
972
971
973 def init_user_ns(self):
972 def init_user_ns(self):
974 """Initialize all user-visible namespaces to their minimum defaults.
973 """Initialize all user-visible namespaces to their minimum defaults.
975
974
976 Certain history lists are also initialized here, as they effectively
975 Certain history lists are also initialized here, as they effectively
977 act as user namespaces.
976 act as user namespaces.
978
977
979 Notes
978 Notes
980 -----
979 -----
981 All data structures here are only filled in, they are NOT reset by this
980 All data structures here are only filled in, they are NOT reset by this
982 method. If they were not empty before, data will simply be added to
981 method. If they were not empty before, data will simply be added to
983 therm.
982 therm.
984 """
983 """
985 # This function works in two parts: first we put a few things in
984 # This function works in two parts: first we put a few things in
986 # user_ns, and we sync that contents into user_ns_hidden so that these
985 # user_ns, and we sync that contents into user_ns_hidden so that these
987 # initial variables aren't shown by %who. After the sync, we add the
986 # initial variables aren't shown by %who. After the sync, we add the
988 # rest of what we *do* want the user to see with %who even on a new
987 # rest of what we *do* want the user to see with %who even on a new
989 # session (probably nothing, so theye really only see their own stuff)
988 # session (probably nothing, so theye really only see their own stuff)
990
989
991 # The user dict must *always* have a __builtin__ reference to the
990 # The user dict must *always* have a __builtin__ reference to the
992 # Python standard __builtin__ namespace, which must be imported.
991 # Python standard __builtin__ namespace, which must be imported.
993 # This is so that certain operations in prompt evaluation can be
992 # This is so that certain operations in prompt evaluation can be
994 # reliably executed with builtins. Note that we can NOT use
993 # reliably executed with builtins. Note that we can NOT use
995 # __builtins__ (note the 's'), because that can either be a dict or a
994 # __builtins__ (note the 's'), because that can either be a dict or a
996 # module, and can even mutate at runtime, depending on the context
995 # module, and can even mutate at runtime, depending on the context
997 # (Python makes no guarantees on it). In contrast, __builtin__ is
996 # (Python makes no guarantees on it). In contrast, __builtin__ is
998 # always a module object, though it must be explicitly imported.
997 # always a module object, though it must be explicitly imported.
999
998
1000 # For more details:
999 # For more details:
1001 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1000 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1002 ns = dict(__builtin__ = __builtin__)
1001 ns = dict(__builtin__ = __builtin__)
1003
1002
1004 # Put 'help' in the user namespace
1003 # Put 'help' in the user namespace
1005 try:
1004 try:
1006 from site import _Helper
1005 from site import _Helper
1007 ns['help'] = _Helper()
1006 ns['help'] = _Helper()
1008 except ImportError:
1007 except ImportError:
1009 warn('help() not available - check site.py')
1008 warn('help() not available - check site.py')
1010
1009
1011 # make global variables for user access to the histories
1010 # make global variables for user access to the histories
1012 ns['_ih'] = self.history_manager.input_hist_parsed
1011 ns['_ih'] = self.history_manager.input_hist_parsed
1013 ns['_oh'] = self.history_manager.output_hist
1012 ns['_oh'] = self.history_manager.output_hist
1014 ns['_dh'] = self.history_manager.dir_hist
1013 ns['_dh'] = self.history_manager.dir_hist
1015
1014
1016 ns['_sh'] = shadowns
1015 ns['_sh'] = shadowns
1017
1016
1018 # user aliases to input and output histories. These shouldn't show up
1017 # user aliases to input and output histories. These shouldn't show up
1019 # in %who, as they can have very large reprs.
1018 # in %who, as they can have very large reprs.
1020 ns['In'] = self.history_manager.input_hist_parsed
1019 ns['In'] = self.history_manager.input_hist_parsed
1021 ns['Out'] = self.history_manager.output_hist
1020 ns['Out'] = self.history_manager.output_hist
1022
1021
1023 # Store myself as the public api!!!
1022 # Store myself as the public api!!!
1024 ns['get_ipython'] = self.get_ipython
1023 ns['get_ipython'] = self.get_ipython
1025
1024
1026 ns['exit'] = self.exiter
1025 ns['exit'] = self.exiter
1027 ns['quit'] = self.exiter
1026 ns['quit'] = self.exiter
1028
1027
1029 # Sync what we've added so far to user_ns_hidden so these aren't seen
1028 # Sync what we've added so far to user_ns_hidden so these aren't seen
1030 # by %who
1029 # by %who
1031 self.user_ns_hidden.update(ns)
1030 self.user_ns_hidden.update(ns)
1032
1031
1033 # Anything put into ns now would show up in %who. Think twice before
1032 # Anything put into ns now would show up in %who. Think twice before
1034 # putting anything here, as we really want %who to show the user their
1033 # putting anything here, as we really want %who to show the user their
1035 # stuff, not our variables.
1034 # stuff, not our variables.
1036
1035
1037 # Finally, update the real user's namespace
1036 # Finally, update the real user's namespace
1038 self.user_ns.update(ns)
1037 self.user_ns.update(ns)
1039
1038
1040 def reset(self, new_session=True):
1039 def reset(self, new_session=True):
1041 """Clear all internal namespaces, and attempt to release references to
1040 """Clear all internal namespaces, and attempt to release references to
1042 user objects.
1041 user objects.
1043
1042
1044 If new_session is True, a new history session will be opened.
1043 If new_session is True, a new history session will be opened.
1045 """
1044 """
1046 # Clear histories
1045 # Clear histories
1047 self.history_manager.reset(new_session)
1046 self.history_manager.reset(new_session)
1048 # Reset counter used to index all histories
1047 # Reset counter used to index all histories
1049 if new_session:
1048 if new_session:
1050 self.execution_count = 1
1049 self.execution_count = 1
1051
1050
1052 # Flush cached output items
1051 # Flush cached output items
1053 self.displayhook.flush()
1052 self.displayhook.flush()
1054
1053
1055 # Restore the user namespaces to minimal usability
1054 # Restore the user namespaces to minimal usability
1056 for ns in self.ns_refs_table:
1055 for ns in self.ns_refs_table:
1057 ns.clear()
1056 ns.clear()
1058
1057
1059 # The main execution namespaces must be cleared very carefully,
1058 # The main execution namespaces must be cleared very carefully,
1060 # skipping the deletion of the builtin-related keys, because doing so
1059 # skipping the deletion of the builtin-related keys, because doing so
1061 # would cause errors in many object's __del__ methods.
1060 # would cause errors in many object's __del__ methods.
1062 for ns in [self.user_ns, self.user_global_ns]:
1061 for ns in [self.user_ns, self.user_global_ns]:
1063 drop_keys = set(ns.keys())
1062 drop_keys = set(ns.keys())
1064 drop_keys.discard('__builtin__')
1063 drop_keys.discard('__builtin__')
1065 drop_keys.discard('__builtins__')
1064 drop_keys.discard('__builtins__')
1066 for k in drop_keys:
1065 for k in drop_keys:
1067 del ns[k]
1066 del ns[k]
1068
1067
1069 # Restore the user namespaces to minimal usability
1068 # Restore the user namespaces to minimal usability
1070 self.init_user_ns()
1069 self.init_user_ns()
1071
1070
1072 # Restore the default and user aliases
1071 # Restore the default and user aliases
1073 self.alias_manager.clear_aliases()
1072 self.alias_manager.clear_aliases()
1074 self.alias_manager.init_aliases()
1073 self.alias_manager.init_aliases()
1075
1074
1076 # Flush the private list of module references kept for script
1075 # Flush the private list of module references kept for script
1077 # execution protection
1076 # execution protection
1078 self.clear_main_mod_cache()
1077 self.clear_main_mod_cache()
1079
1078
1080 # Clear out the namespace from the last %run
1079 # Clear out the namespace from the last %run
1081 self.new_main_mod()
1080 self.new_main_mod()
1082
1081
1083 def reset_selective(self, regex=None):
1082 def reset_selective(self, regex=None):
1084 """Clear selective variables from internal namespaces based on a
1083 """Clear selective variables from internal namespaces based on a
1085 specified regular expression.
1084 specified regular expression.
1086
1085
1087 Parameters
1086 Parameters
1088 ----------
1087 ----------
1089 regex : string or compiled pattern, optional
1088 regex : string or compiled pattern, optional
1090 A regular expression pattern that will be used in searching
1089 A regular expression pattern that will be used in searching
1091 variable names in the users namespaces.
1090 variable names in the users namespaces.
1092 """
1091 """
1093 if regex is not None:
1092 if regex is not None:
1094 try:
1093 try:
1095 m = re.compile(regex)
1094 m = re.compile(regex)
1096 except TypeError:
1095 except TypeError:
1097 raise TypeError('regex must be a string or compiled pattern')
1096 raise TypeError('regex must be a string or compiled pattern')
1098 # Search for keys in each namespace that match the given regex
1097 # Search for keys in each namespace that match the given regex
1099 # If a match is found, delete the key/value pair.
1098 # If a match is found, delete the key/value pair.
1100 for ns in self.ns_refs_table:
1099 for ns in self.ns_refs_table:
1101 for var in ns:
1100 for var in ns:
1102 if m.search(var):
1101 if m.search(var):
1103 del ns[var]
1102 del ns[var]
1104
1103
1105 def push(self, variables, interactive=True):
1104 def push(self, variables, interactive=True):
1106 """Inject a group of variables into the IPython user namespace.
1105 """Inject a group of variables into the IPython user namespace.
1107
1106
1108 Parameters
1107 Parameters
1109 ----------
1108 ----------
1110 variables : dict, str or list/tuple of str
1109 variables : dict, str or list/tuple of str
1111 The variables to inject into the user's namespace. If a dict, a
1110 The variables to inject into the user's namespace. If a dict, a
1112 simple update is done. If a str, the string is assumed to have
1111 simple update is done. If a str, the string is assumed to have
1113 variable names separated by spaces. A list/tuple of str can also
1112 variable names separated by spaces. A list/tuple of str can also
1114 be used to give the variable names. If just the variable names are
1113 be used to give the variable names. If just the variable names are
1115 give (list/tuple/str) then the variable values looked up in the
1114 give (list/tuple/str) then the variable values looked up in the
1116 callers frame.
1115 callers frame.
1117 interactive : bool
1116 interactive : bool
1118 If True (default), the variables will be listed with the ``who``
1117 If True (default), the variables will be listed with the ``who``
1119 magic.
1118 magic.
1120 """
1119 """
1121 vdict = None
1120 vdict = None
1122
1121
1123 # We need a dict of name/value pairs to do namespace updates.
1122 # We need a dict of name/value pairs to do namespace updates.
1124 if isinstance(variables, dict):
1123 if isinstance(variables, dict):
1125 vdict = variables
1124 vdict = variables
1126 elif isinstance(variables, (basestring, list, tuple)):
1125 elif isinstance(variables, (basestring, list, tuple)):
1127 if isinstance(variables, basestring):
1126 if isinstance(variables, basestring):
1128 vlist = variables.split()
1127 vlist = variables.split()
1129 else:
1128 else:
1130 vlist = variables
1129 vlist = variables
1131 vdict = {}
1130 vdict = {}
1132 cf = sys._getframe(1)
1131 cf = sys._getframe(1)
1133 for name in vlist:
1132 for name in vlist:
1134 try:
1133 try:
1135 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1134 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1136 except:
1135 except:
1137 print ('Could not get variable %s from %s' %
1136 print ('Could not get variable %s from %s' %
1138 (name,cf.f_code.co_name))
1137 (name,cf.f_code.co_name))
1139 else:
1138 else:
1140 raise ValueError('variables must be a dict/str/list/tuple')
1139 raise ValueError('variables must be a dict/str/list/tuple')
1141
1140
1142 # Propagate variables to user namespace
1141 # Propagate variables to user namespace
1143 self.user_ns.update(vdict)
1142 self.user_ns.update(vdict)
1144
1143
1145 # And configure interactive visibility
1144 # And configure interactive visibility
1146 config_ns = self.user_ns_hidden
1145 config_ns = self.user_ns_hidden
1147 if interactive:
1146 if interactive:
1148 for name, val in vdict.iteritems():
1147 for name, val in vdict.iteritems():
1149 config_ns.pop(name, None)
1148 config_ns.pop(name, None)
1150 else:
1149 else:
1151 for name,val in vdict.iteritems():
1150 for name,val in vdict.iteritems():
1152 config_ns[name] = val
1151 config_ns[name] = val
1153
1152
1154 #-------------------------------------------------------------------------
1153 #-------------------------------------------------------------------------
1155 # Things related to object introspection
1154 # Things related to object introspection
1156 #-------------------------------------------------------------------------
1155 #-------------------------------------------------------------------------
1157
1156
1158 def _ofind(self, oname, namespaces=None):
1157 def _ofind(self, oname, namespaces=None):
1159 """Find an object in the available namespaces.
1158 """Find an object in the available namespaces.
1160
1159
1161 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1160 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1162
1161
1163 Has special code to detect magic functions.
1162 Has special code to detect magic functions.
1164 """
1163 """
1165 #oname = oname.strip()
1164 #oname = oname.strip()
1166 #print '1- oname: <%r>' % oname # dbg
1165 #print '1- oname: <%r>' % oname # dbg
1167 try:
1166 try:
1168 oname = oname.strip().encode('ascii')
1167 oname = oname.strip().encode('ascii')
1169 #print '2- oname: <%r>' % oname # dbg
1168 #print '2- oname: <%r>' % oname # dbg
1170 except UnicodeEncodeError:
1169 except UnicodeEncodeError:
1171 print 'Python identifiers can only contain ascii characters.'
1170 print 'Python identifiers can only contain ascii characters.'
1172 return dict(found=False)
1171 return dict(found=False)
1173
1172
1174 alias_ns = None
1173 alias_ns = None
1175 if namespaces is None:
1174 if namespaces is None:
1176 # Namespaces to search in:
1175 # Namespaces to search in:
1177 # Put them in a list. The order is important so that we
1176 # Put them in a list. The order is important so that we
1178 # find things in the same order that Python finds them.
1177 # find things in the same order that Python finds them.
1179 namespaces = [ ('Interactive', self.user_ns),
1178 namespaces = [ ('Interactive', self.user_ns),
1180 ('IPython internal', self.internal_ns),
1179 ('IPython internal', self.internal_ns),
1181 ('Python builtin', __builtin__.__dict__),
1180 ('Python builtin', __builtin__.__dict__),
1182 ('Alias', self.alias_manager.alias_table),
1181 ('Alias', self.alias_manager.alias_table),
1183 ]
1182 ]
1184 alias_ns = self.alias_manager.alias_table
1183 alias_ns = self.alias_manager.alias_table
1185
1184
1186 # initialize results to 'null'
1185 # initialize results to 'null'
1187 found = False; obj = None; ospace = None; ds = None;
1186 found = False; obj = None; ospace = None; ds = None;
1188 ismagic = False; isalias = False; parent = None
1187 ismagic = False; isalias = False; parent = None
1189
1188
1190 # We need to special-case 'print', which as of python2.6 registers as a
1189 # We need to special-case 'print', which as of python2.6 registers as a
1191 # function but should only be treated as one if print_function was
1190 # function but should only be treated as one if print_function was
1192 # loaded with a future import. In this case, just bail.
1191 # loaded with a future import. In this case, just bail.
1193 if (oname == 'print' and not (self.compile.compiler_flags &
1192 if (oname == 'print' and not (self.compile.compiler_flags &
1194 __future__.CO_FUTURE_PRINT_FUNCTION)):
1193 __future__.CO_FUTURE_PRINT_FUNCTION)):
1195 return {'found':found, 'obj':obj, 'namespace':ospace,
1194 return {'found':found, 'obj':obj, 'namespace':ospace,
1196 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1195 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1197
1196
1198 # Look for the given name by splitting it in parts. If the head is
1197 # Look for the given name by splitting it in parts. If the head is
1199 # found, then we look for all the remaining parts as members, and only
1198 # found, then we look for all the remaining parts as members, and only
1200 # declare success if we can find them all.
1199 # declare success if we can find them all.
1201 oname_parts = oname.split('.')
1200 oname_parts = oname.split('.')
1202 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1201 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1203 for nsname,ns in namespaces:
1202 for nsname,ns in namespaces:
1204 try:
1203 try:
1205 obj = ns[oname_head]
1204 obj = ns[oname_head]
1206 except KeyError:
1205 except KeyError:
1207 continue
1206 continue
1208 else:
1207 else:
1209 #print 'oname_rest:', oname_rest # dbg
1208 #print 'oname_rest:', oname_rest # dbg
1210 for part in oname_rest:
1209 for part in oname_rest:
1211 try:
1210 try:
1212 parent = obj
1211 parent = obj
1213 obj = getattr(obj,part)
1212 obj = getattr(obj,part)
1214 except:
1213 except:
1215 # Blanket except b/c some badly implemented objects
1214 # Blanket except b/c some badly implemented objects
1216 # allow __getattr__ to raise exceptions other than
1215 # allow __getattr__ to raise exceptions other than
1217 # AttributeError, which then crashes IPython.
1216 # AttributeError, which then crashes IPython.
1218 break
1217 break
1219 else:
1218 else:
1220 # If we finish the for loop (no break), we got all members
1219 # If we finish the for loop (no break), we got all members
1221 found = True
1220 found = True
1222 ospace = nsname
1221 ospace = nsname
1223 if ns == alias_ns:
1222 if ns == alias_ns:
1224 isalias = True
1223 isalias = True
1225 break # namespace loop
1224 break # namespace loop
1226
1225
1227 # Try to see if it's magic
1226 # Try to see if it's magic
1228 if not found:
1227 if not found:
1229 if oname.startswith(ESC_MAGIC):
1228 if oname.startswith(ESC_MAGIC):
1230 oname = oname[1:]
1229 oname = oname[1:]
1231 obj = getattr(self,'magic_'+oname,None)
1230 obj = getattr(self,'magic_'+oname,None)
1232 if obj is not None:
1231 if obj is not None:
1233 found = True
1232 found = True
1234 ospace = 'IPython internal'
1233 ospace = 'IPython internal'
1235 ismagic = True
1234 ismagic = True
1236
1235
1237 # Last try: special-case some literals like '', [], {}, etc:
1236 # Last try: special-case some literals like '', [], {}, etc:
1238 if not found and oname_head in ["''",'""','[]','{}','()']:
1237 if not found and oname_head in ["''",'""','[]','{}','()']:
1239 obj = eval(oname_head)
1238 obj = eval(oname_head)
1240 found = True
1239 found = True
1241 ospace = 'Interactive'
1240 ospace = 'Interactive'
1242
1241
1243 return {'found':found, 'obj':obj, 'namespace':ospace,
1242 return {'found':found, 'obj':obj, 'namespace':ospace,
1244 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1243 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1245
1244
1246 def _ofind_property(self, oname, info):
1245 def _ofind_property(self, oname, info):
1247 """Second part of object finding, to look for property details."""
1246 """Second part of object finding, to look for property details."""
1248 if info.found:
1247 if info.found:
1249 # Get the docstring of the class property if it exists.
1248 # Get the docstring of the class property if it exists.
1250 path = oname.split('.')
1249 path = oname.split('.')
1251 root = '.'.join(path[:-1])
1250 root = '.'.join(path[:-1])
1252 if info.parent is not None:
1251 if info.parent is not None:
1253 try:
1252 try:
1254 target = getattr(info.parent, '__class__')
1253 target = getattr(info.parent, '__class__')
1255 # The object belongs to a class instance.
1254 # The object belongs to a class instance.
1256 try:
1255 try:
1257 target = getattr(target, path[-1])
1256 target = getattr(target, path[-1])
1258 # The class defines the object.
1257 # The class defines the object.
1259 if isinstance(target, property):
1258 if isinstance(target, property):
1260 oname = root + '.__class__.' + path[-1]
1259 oname = root + '.__class__.' + path[-1]
1261 info = Struct(self._ofind(oname))
1260 info = Struct(self._ofind(oname))
1262 except AttributeError: pass
1261 except AttributeError: pass
1263 except AttributeError: pass
1262 except AttributeError: pass
1264
1263
1265 # We return either the new info or the unmodified input if the object
1264 # We return either the new info or the unmodified input if the object
1266 # hadn't been found
1265 # hadn't been found
1267 return info
1266 return info
1268
1267
1269 def _object_find(self, oname, namespaces=None):
1268 def _object_find(self, oname, namespaces=None):
1270 """Find an object and return a struct with info about it."""
1269 """Find an object and return a struct with info about it."""
1271 inf = Struct(self._ofind(oname, namespaces))
1270 inf = Struct(self._ofind(oname, namespaces))
1272 return Struct(self._ofind_property(oname, inf))
1271 return Struct(self._ofind_property(oname, inf))
1273
1272
1274 def _inspect(self, meth, oname, namespaces=None, **kw):
1273 def _inspect(self, meth, oname, namespaces=None, **kw):
1275 """Generic interface to the inspector system.
1274 """Generic interface to the inspector system.
1276
1275
1277 This function is meant to be called by pdef, pdoc & friends."""
1276 This function is meant to be called by pdef, pdoc & friends."""
1278 info = self._object_find(oname)
1277 info = self._object_find(oname)
1279 if info.found:
1278 if info.found:
1280 pmethod = getattr(self.inspector, meth)
1279 pmethod = getattr(self.inspector, meth)
1281 formatter = format_screen if info.ismagic else None
1280 formatter = format_screen if info.ismagic else None
1282 if meth == 'pdoc':
1281 if meth == 'pdoc':
1283 pmethod(info.obj, oname, formatter)
1282 pmethod(info.obj, oname, formatter)
1284 elif meth == 'pinfo':
1283 elif meth == 'pinfo':
1285 pmethod(info.obj, oname, formatter, info, **kw)
1284 pmethod(info.obj, oname, formatter, info, **kw)
1286 else:
1285 else:
1287 pmethod(info.obj, oname)
1286 pmethod(info.obj, oname)
1288 else:
1287 else:
1289 print 'Object `%s` not found.' % oname
1288 print 'Object `%s` not found.' % oname
1290 return 'not found' # so callers can take other action
1289 return 'not found' # so callers can take other action
1291
1290
1292 def object_inspect(self, oname):
1291 def object_inspect(self, oname):
1293 with self.builtin_trap:
1292 with self.builtin_trap:
1294 info = self._object_find(oname)
1293 info = self._object_find(oname)
1295 if info.found:
1294 if info.found:
1296 return self.inspector.info(info.obj, oname, info=info)
1295 return self.inspector.info(info.obj, oname, info=info)
1297 else:
1296 else:
1298 return oinspect.object_info(name=oname, found=False)
1297 return oinspect.object_info(name=oname, found=False)
1299
1298
1300 #-------------------------------------------------------------------------
1299 #-------------------------------------------------------------------------
1301 # Things related to history management
1300 # Things related to history management
1302 #-------------------------------------------------------------------------
1301 #-------------------------------------------------------------------------
1303
1302
1304 def init_history(self):
1303 def init_history(self):
1305 """Sets up the command history, and starts regular autosaves."""
1304 """Sets up the command history, and starts regular autosaves."""
1306 self.history_manager = HistoryManager(shell=self, config=self.config)
1305 self.history_manager = HistoryManager(shell=self, config=self.config)
1307
1306
1308 #-------------------------------------------------------------------------
1307 #-------------------------------------------------------------------------
1309 # Things related to exception handling and tracebacks (not debugging)
1308 # Things related to exception handling and tracebacks (not debugging)
1310 #-------------------------------------------------------------------------
1309 #-------------------------------------------------------------------------
1311
1310
1312 def init_traceback_handlers(self, custom_exceptions):
1311 def init_traceback_handlers(self, custom_exceptions):
1313 # Syntax error handler.
1312 # Syntax error handler.
1314 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1313 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1315
1314
1316 # The interactive one is initialized with an offset, meaning we always
1315 # The interactive one is initialized with an offset, meaning we always
1317 # want to remove the topmost item in the traceback, which is our own
1316 # want to remove the topmost item in the traceback, which is our own
1318 # internal code. Valid modes: ['Plain','Context','Verbose']
1317 # internal code. Valid modes: ['Plain','Context','Verbose']
1319 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1318 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1320 color_scheme='NoColor',
1319 color_scheme='NoColor',
1321 tb_offset = 1,
1320 tb_offset = 1,
1322 check_cache=self.compile.check_cache)
1321 check_cache=self.compile.check_cache)
1323
1322
1324 # The instance will store a pointer to the system-wide exception hook,
1323 # The instance will store a pointer to the system-wide exception hook,
1325 # so that runtime code (such as magics) can access it. This is because
1324 # so that runtime code (such as magics) can access it. This is because
1326 # during the read-eval loop, it may get temporarily overwritten.
1325 # during the read-eval loop, it may get temporarily overwritten.
1327 self.sys_excepthook = sys.excepthook
1326 self.sys_excepthook = sys.excepthook
1328
1327
1329 # and add any custom exception handlers the user may have specified
1328 # and add any custom exception handlers the user may have specified
1330 self.set_custom_exc(*custom_exceptions)
1329 self.set_custom_exc(*custom_exceptions)
1331
1330
1332 # Set the exception mode
1331 # Set the exception mode
1333 self.InteractiveTB.set_mode(mode=self.xmode)
1332 self.InteractiveTB.set_mode(mode=self.xmode)
1334
1333
1335 def set_custom_exc(self, exc_tuple, handler):
1334 def set_custom_exc(self, exc_tuple, handler):
1336 """set_custom_exc(exc_tuple,handler)
1335 """set_custom_exc(exc_tuple,handler)
1337
1336
1338 Set a custom exception handler, which will be called if any of the
1337 Set a custom exception handler, which will be called if any of the
1339 exceptions in exc_tuple occur in the mainloop (specifically, in the
1338 exceptions in exc_tuple occur in the mainloop (specifically, in the
1340 run_code() method.
1339 run_code() method.
1341
1340
1342 Inputs:
1341 Inputs:
1343
1342
1344 - exc_tuple: a *tuple* of valid exceptions to call the defined
1343 - exc_tuple: a *tuple* of valid exceptions to call the defined
1345 handler for. It is very important that you use a tuple, and NOT A
1344 handler for. It is very important that you use a tuple, and NOT A
1346 LIST here, because of the way Python's except statement works. If
1345 LIST here, because of the way Python's except statement works. If
1347 you only want to trap a single exception, use a singleton tuple:
1346 you only want to trap a single exception, use a singleton tuple:
1348
1347
1349 exc_tuple == (MyCustomException,)
1348 exc_tuple == (MyCustomException,)
1350
1349
1351 - handler: this must be defined as a function with the following
1350 - handler: this must be defined as a function with the following
1352 basic interface::
1351 basic interface::
1353
1352
1354 def my_handler(self, etype, value, tb, tb_offset=None)
1353 def my_handler(self, etype, value, tb, tb_offset=None)
1355 ...
1354 ...
1356 # The return value must be
1355 # The return value must be
1357 return structured_traceback
1356 return structured_traceback
1358
1357
1359 This will be made into an instance method (via types.MethodType)
1358 This will be made into an instance method (via types.MethodType)
1360 of IPython itself, and it will be called if any of the exceptions
1359 of IPython itself, and it will be called if any of the exceptions
1361 listed in the exc_tuple are caught. If the handler is None, an
1360 listed in the exc_tuple are caught. If the handler is None, an
1362 internal basic one is used, which just prints basic info.
1361 internal basic one is used, which just prints basic info.
1363
1362
1364 WARNING: by putting in your own exception handler into IPython's main
1363 WARNING: by putting in your own exception handler into IPython's main
1365 execution loop, you run a very good chance of nasty crashes. This
1364 execution loop, you run a very good chance of nasty crashes. This
1366 facility should only be used if you really know what you are doing."""
1365 facility should only be used if you really know what you are doing."""
1367
1366
1368 assert type(exc_tuple)==type(()) , \
1367 assert type(exc_tuple)==type(()) , \
1369 "The custom exceptions must be given AS A TUPLE."
1368 "The custom exceptions must be given AS A TUPLE."
1370
1369
1371 def dummy_handler(self,etype,value,tb):
1370 def dummy_handler(self,etype,value,tb):
1372 print '*** Simple custom exception handler ***'
1371 print '*** Simple custom exception handler ***'
1373 print 'Exception type :',etype
1372 print 'Exception type :',etype
1374 print 'Exception value:',value
1373 print 'Exception value:',value
1375 print 'Traceback :',tb
1374 print 'Traceback :',tb
1376 #print 'Source code :','\n'.join(self.buffer)
1375 #print 'Source code :','\n'.join(self.buffer)
1377
1376
1378 if handler is None: handler = dummy_handler
1377 if handler is None: handler = dummy_handler
1379
1378
1380 self.CustomTB = types.MethodType(handler,self)
1379 self.CustomTB = types.MethodType(handler,self)
1381 self.custom_exceptions = exc_tuple
1380 self.custom_exceptions = exc_tuple
1382
1381
1383 def excepthook(self, etype, value, tb):
1382 def excepthook(self, etype, value, tb):
1384 """One more defense for GUI apps that call sys.excepthook.
1383 """One more defense for GUI apps that call sys.excepthook.
1385
1384
1386 GUI frameworks like wxPython trap exceptions and call
1385 GUI frameworks like wxPython trap exceptions and call
1387 sys.excepthook themselves. I guess this is a feature that
1386 sys.excepthook themselves. I guess this is a feature that
1388 enables them to keep running after exceptions that would
1387 enables them to keep running after exceptions that would
1389 otherwise kill their mainloop. This is a bother for IPython
1388 otherwise kill their mainloop. This is a bother for IPython
1390 which excepts to catch all of the program exceptions with a try:
1389 which excepts to catch all of the program exceptions with a try:
1391 except: statement.
1390 except: statement.
1392
1391
1393 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1392 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1394 any app directly invokes sys.excepthook, it will look to the user like
1393 any app directly invokes sys.excepthook, it will look to the user like
1395 IPython crashed. In order to work around this, we can disable the
1394 IPython crashed. In order to work around this, we can disable the
1396 CrashHandler and replace it with this excepthook instead, which prints a
1395 CrashHandler and replace it with this excepthook instead, which prints a
1397 regular traceback using our InteractiveTB. In this fashion, apps which
1396 regular traceback using our InteractiveTB. In this fashion, apps which
1398 call sys.excepthook will generate a regular-looking exception from
1397 call sys.excepthook will generate a regular-looking exception from
1399 IPython, and the CrashHandler will only be triggered by real IPython
1398 IPython, and the CrashHandler will only be triggered by real IPython
1400 crashes.
1399 crashes.
1401
1400
1402 This hook should be used sparingly, only in places which are not likely
1401 This hook should be used sparingly, only in places which are not likely
1403 to be true IPython errors.
1402 to be true IPython errors.
1404 """
1403 """
1405 self.showtraceback((etype,value,tb),tb_offset=0)
1404 self.showtraceback((etype,value,tb),tb_offset=0)
1406
1405
1407 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1406 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1408 exception_only=False):
1407 exception_only=False):
1409 """Display the exception that just occurred.
1408 """Display the exception that just occurred.
1410
1409
1411 If nothing is known about the exception, this is the method which
1410 If nothing is known about the exception, this is the method which
1412 should be used throughout the code for presenting user tracebacks,
1411 should be used throughout the code for presenting user tracebacks,
1413 rather than directly invoking the InteractiveTB object.
1412 rather than directly invoking the InteractiveTB object.
1414
1413
1415 A specific showsyntaxerror() also exists, but this method can take
1414 A specific showsyntaxerror() also exists, but this method can take
1416 care of calling it if needed, so unless you are explicitly catching a
1415 care of calling it if needed, so unless you are explicitly catching a
1417 SyntaxError exception, don't try to analyze the stack manually and
1416 SyntaxError exception, don't try to analyze the stack manually and
1418 simply call this method."""
1417 simply call this method."""
1419
1418
1420 try:
1419 try:
1421 if exc_tuple is None:
1420 if exc_tuple is None:
1422 etype, value, tb = sys.exc_info()
1421 etype, value, tb = sys.exc_info()
1423 else:
1422 else:
1424 etype, value, tb = exc_tuple
1423 etype, value, tb = exc_tuple
1425
1424
1426 if etype is None:
1425 if etype is None:
1427 if hasattr(sys, 'last_type'):
1426 if hasattr(sys, 'last_type'):
1428 etype, value, tb = sys.last_type, sys.last_value, \
1427 etype, value, tb = sys.last_type, sys.last_value, \
1429 sys.last_traceback
1428 sys.last_traceback
1430 else:
1429 else:
1431 self.write_err('No traceback available to show.\n')
1430 self.write_err('No traceback available to show.\n')
1432 return
1431 return
1433
1432
1434 if etype is SyntaxError:
1433 if etype is SyntaxError:
1435 # Though this won't be called by syntax errors in the input
1434 # Though this won't be called by syntax errors in the input
1436 # line, there may be SyntaxError cases whith imported code.
1435 # line, there may be SyntaxError cases whith imported code.
1437 self.showsyntaxerror(filename)
1436 self.showsyntaxerror(filename)
1438 elif etype is UsageError:
1437 elif etype is UsageError:
1439 print "UsageError:", value
1438 print "UsageError:", value
1440 else:
1439 else:
1441 # WARNING: these variables are somewhat deprecated and not
1440 # WARNING: these variables are somewhat deprecated and not
1442 # necessarily safe to use in a threaded environment, but tools
1441 # necessarily safe to use in a threaded environment, but tools
1443 # like pdb depend on their existence, so let's set them. If we
1442 # like pdb depend on their existence, so let's set them. If we
1444 # find problems in the field, we'll need to revisit their use.
1443 # find problems in the field, we'll need to revisit their use.
1445 sys.last_type = etype
1444 sys.last_type = etype
1446 sys.last_value = value
1445 sys.last_value = value
1447 sys.last_traceback = tb
1446 sys.last_traceback = tb
1448 if etype in self.custom_exceptions:
1447 if etype in self.custom_exceptions:
1449 # FIXME: Old custom traceback objects may just return a
1448 # FIXME: Old custom traceback objects may just return a
1450 # string, in that case we just put it into a list
1449 # string, in that case we just put it into a list
1451 stb = self.CustomTB(etype, value, tb, tb_offset)
1450 stb = self.CustomTB(etype, value, tb, tb_offset)
1452 if isinstance(ctb, basestring):
1451 if isinstance(ctb, basestring):
1453 stb = [stb]
1452 stb = [stb]
1454 else:
1453 else:
1455 if exception_only:
1454 if exception_only:
1456 stb = ['An exception has occurred, use %tb to see '
1455 stb = ['An exception has occurred, use %tb to see '
1457 'the full traceback.\n']
1456 'the full traceback.\n']
1458 stb.extend(self.InteractiveTB.get_exception_only(etype,
1457 stb.extend(self.InteractiveTB.get_exception_only(etype,
1459 value))
1458 value))
1460 else:
1459 else:
1461 stb = self.InteractiveTB.structured_traceback(etype,
1460 stb = self.InteractiveTB.structured_traceback(etype,
1462 value, tb, tb_offset=tb_offset)
1461 value, tb, tb_offset=tb_offset)
1463
1462
1464 if self.call_pdb:
1463 if self.call_pdb:
1465 # drop into debugger
1464 # drop into debugger
1466 self.debugger(force=True)
1465 self.debugger(force=True)
1467
1466
1468 # Actually show the traceback
1467 # Actually show the traceback
1469 self._showtraceback(etype, value, stb)
1468 self._showtraceback(etype, value, stb)
1470
1469
1471 except KeyboardInterrupt:
1470 except KeyboardInterrupt:
1472 self.write_err("\nKeyboardInterrupt\n")
1471 self.write_err("\nKeyboardInterrupt\n")
1473
1472
1474 def _showtraceback(self, etype, evalue, stb):
1473 def _showtraceback(self, etype, evalue, stb):
1475 """Actually show a traceback.
1474 """Actually show a traceback.
1476
1475
1477 Subclasses may override this method to put the traceback on a different
1476 Subclasses may override this method to put the traceback on a different
1478 place, like a side channel.
1477 place, like a side channel.
1479 """
1478 """
1480 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
1479 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1481
1480
1482 def showsyntaxerror(self, filename=None):
1481 def showsyntaxerror(self, filename=None):
1483 """Display the syntax error that just occurred.
1482 """Display the syntax error that just occurred.
1484
1483
1485 This doesn't display a stack trace because there isn't one.
1484 This doesn't display a stack trace because there isn't one.
1486
1485
1487 If a filename is given, it is stuffed in the exception instead
1486 If a filename is given, it is stuffed in the exception instead
1488 of what was there before (because Python's parser always uses
1487 of what was there before (because Python's parser always uses
1489 "<string>" when reading from a string).
1488 "<string>" when reading from a string).
1490 """
1489 """
1491 etype, value, last_traceback = sys.exc_info()
1490 etype, value, last_traceback = sys.exc_info()
1492
1491
1493 # See note about these variables in showtraceback() above
1492 # See note about these variables in showtraceback() above
1494 sys.last_type = etype
1493 sys.last_type = etype
1495 sys.last_value = value
1494 sys.last_value = value
1496 sys.last_traceback = last_traceback
1495 sys.last_traceback = last_traceback
1497
1496
1498 if filename and etype is SyntaxError:
1497 if filename and etype is SyntaxError:
1499 # Work hard to stuff the correct filename in the exception
1498 # Work hard to stuff the correct filename in the exception
1500 try:
1499 try:
1501 msg, (dummy_filename, lineno, offset, line) = value
1500 msg, (dummy_filename, lineno, offset, line) = value
1502 except:
1501 except:
1503 # Not the format we expect; leave it alone
1502 # Not the format we expect; leave it alone
1504 pass
1503 pass
1505 else:
1504 else:
1506 # Stuff in the right filename
1505 # Stuff in the right filename
1507 try:
1506 try:
1508 # Assume SyntaxError is a class exception
1507 # Assume SyntaxError is a class exception
1509 value = SyntaxError(msg, (filename, lineno, offset, line))
1508 value = SyntaxError(msg, (filename, lineno, offset, line))
1510 except:
1509 except:
1511 # If that failed, assume SyntaxError is a string
1510 # If that failed, assume SyntaxError is a string
1512 value = msg, (filename, lineno, offset, line)
1511 value = msg, (filename, lineno, offset, line)
1513 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1512 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1514 self._showtraceback(etype, value, stb)
1513 self._showtraceback(etype, value, stb)
1515
1514
1516 #-------------------------------------------------------------------------
1515 #-------------------------------------------------------------------------
1517 # Things related to readline
1516 # Things related to readline
1518 #-------------------------------------------------------------------------
1517 #-------------------------------------------------------------------------
1519
1518
1520 def init_readline(self):
1519 def init_readline(self):
1521 """Command history completion/saving/reloading."""
1520 """Command history completion/saving/reloading."""
1522
1521
1523 if self.readline_use:
1522 if self.readline_use:
1524 import IPython.utils.rlineimpl as readline
1523 import IPython.utils.rlineimpl as readline
1525
1524
1526 self.rl_next_input = None
1525 self.rl_next_input = None
1527 self.rl_do_indent = False
1526 self.rl_do_indent = False
1528
1527
1529 if not self.readline_use or not readline.have_readline:
1528 if not self.readline_use or not readline.have_readline:
1530 self.has_readline = False
1529 self.has_readline = False
1531 self.readline = None
1530 self.readline = None
1532 # Set a number of methods that depend on readline to be no-op
1531 # Set a number of methods that depend on readline to be no-op
1533 self.set_readline_completer = no_op
1532 self.set_readline_completer = no_op
1534 self.set_custom_completer = no_op
1533 self.set_custom_completer = no_op
1535 self.set_completer_frame = no_op
1534 self.set_completer_frame = no_op
1536 warn('Readline services not available or not loaded.')
1535 warn('Readline services not available or not loaded.')
1537 else:
1536 else:
1538 self.has_readline = True
1537 self.has_readline = True
1539 self.readline = readline
1538 self.readline = readline
1540 sys.modules['readline'] = readline
1539 sys.modules['readline'] = readline
1541
1540
1542 # Platform-specific configuration
1541 # Platform-specific configuration
1543 if os.name == 'nt':
1542 if os.name == 'nt':
1544 # FIXME - check with Frederick to see if we can harmonize
1543 # FIXME - check with Frederick to see if we can harmonize
1545 # naming conventions with pyreadline to avoid this
1544 # naming conventions with pyreadline to avoid this
1546 # platform-dependent check
1545 # platform-dependent check
1547 self.readline_startup_hook = readline.set_pre_input_hook
1546 self.readline_startup_hook = readline.set_pre_input_hook
1548 else:
1547 else:
1549 self.readline_startup_hook = readline.set_startup_hook
1548 self.readline_startup_hook = readline.set_startup_hook
1550
1549
1551 # Load user's initrc file (readline config)
1550 # Load user's initrc file (readline config)
1552 # Or if libedit is used, load editrc.
1551 # Or if libedit is used, load editrc.
1553 inputrc_name = os.environ.get('INPUTRC')
1552 inputrc_name = os.environ.get('INPUTRC')
1554 if inputrc_name is None:
1553 if inputrc_name is None:
1555 home_dir = get_home_dir()
1554 home_dir = get_home_dir()
1556 if home_dir is not None:
1555 if home_dir is not None:
1557 inputrc_name = '.inputrc'
1556 inputrc_name = '.inputrc'
1558 if readline.uses_libedit:
1557 if readline.uses_libedit:
1559 inputrc_name = '.editrc'
1558 inputrc_name = '.editrc'
1560 inputrc_name = os.path.join(home_dir, inputrc_name)
1559 inputrc_name = os.path.join(home_dir, inputrc_name)
1561 if os.path.isfile(inputrc_name):
1560 if os.path.isfile(inputrc_name):
1562 try:
1561 try:
1563 readline.read_init_file(inputrc_name)
1562 readline.read_init_file(inputrc_name)
1564 except:
1563 except:
1565 warn('Problems reading readline initialization file <%s>'
1564 warn('Problems reading readline initialization file <%s>'
1566 % inputrc_name)
1565 % inputrc_name)
1567
1566
1568 # Configure readline according to user's prefs
1567 # Configure readline according to user's prefs
1569 # This is only done if GNU readline is being used. If libedit
1568 # This is only done if GNU readline is being used. If libedit
1570 # is being used (as on Leopard) the readline config is
1569 # is being used (as on Leopard) the readline config is
1571 # not run as the syntax for libedit is different.
1570 # not run as the syntax for libedit is different.
1572 if not readline.uses_libedit:
1571 if not readline.uses_libedit:
1573 for rlcommand in self.readline_parse_and_bind:
1572 for rlcommand in self.readline_parse_and_bind:
1574 #print "loading rl:",rlcommand # dbg
1573 #print "loading rl:",rlcommand # dbg
1575 readline.parse_and_bind(rlcommand)
1574 readline.parse_and_bind(rlcommand)
1576
1575
1577 # Remove some chars from the delimiters list. If we encounter
1576 # Remove some chars from the delimiters list. If we encounter
1578 # unicode chars, discard them.
1577 # unicode chars, discard them.
1579 delims = readline.get_completer_delims().encode("ascii", "ignore")
1578 delims = readline.get_completer_delims().encode("ascii", "ignore")
1580 delims = delims.translate(None, self.readline_remove_delims)
1579 delims = delims.translate(None, self.readline_remove_delims)
1581 delims = delims.replace(ESC_MAGIC, '')
1580 delims = delims.replace(ESC_MAGIC, '')
1582 readline.set_completer_delims(delims)
1581 readline.set_completer_delims(delims)
1583 # otherwise we end up with a monster history after a while:
1582 # otherwise we end up with a monster history after a while:
1584 readline.set_history_length(self.history_length)
1583 readline.set_history_length(self.history_length)
1585
1584
1586 self.refill_readline_hist()
1585 self.refill_readline_hist()
1587 self.readline_no_record = ReadlineNoRecord(self)
1586 self.readline_no_record = ReadlineNoRecord(self)
1588
1587
1589 # Configure auto-indent for all platforms
1588 # Configure auto-indent for all platforms
1590 self.set_autoindent(self.autoindent)
1589 self.set_autoindent(self.autoindent)
1591
1590
1592 def refill_readline_hist(self):
1591 def refill_readline_hist(self):
1593 # Load the last 1000 lines from history
1592 # Load the last 1000 lines from history
1594 self.readline.clear_history()
1593 self.readline.clear_history()
1595 stdin_encoding = sys.stdin.encoding or "utf-8"
1594 stdin_encoding = sys.stdin.encoding or "utf-8"
1596 for _, _, cell in self.history_manager.get_tail(1000,
1595 for _, _, cell in self.history_manager.get_tail(1000,
1597 include_latest=True):
1596 include_latest=True):
1598 if cell.strip(): # Ignore blank lines
1597 if cell.strip(): # Ignore blank lines
1599 for line in cell.splitlines():
1598 for line in cell.splitlines():
1600 self.readline.add_history(line.encode(stdin_encoding))
1599 self.readline.add_history(line.encode(stdin_encoding))
1601
1600
1602 def set_next_input(self, s):
1601 def set_next_input(self, s):
1603 """ Sets the 'default' input string for the next command line.
1602 """ Sets the 'default' input string for the next command line.
1604
1603
1605 Requires readline.
1604 Requires readline.
1606
1605
1607 Example:
1606 Example:
1608
1607
1609 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1608 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1610 [D:\ipython]|2> Hello Word_ # cursor is here
1609 [D:\ipython]|2> Hello Word_ # cursor is here
1611 """
1610 """
1612
1611
1613 self.rl_next_input = s
1612 self.rl_next_input = s
1614
1613
1615 # Maybe move this to the terminal subclass?
1614 # Maybe move this to the terminal subclass?
1616 def pre_readline(self):
1615 def pre_readline(self):
1617 """readline hook to be used at the start of each line.
1616 """readline hook to be used at the start of each line.
1618
1617
1619 Currently it handles auto-indent only."""
1618 Currently it handles auto-indent only."""
1620
1619
1621 if self.rl_do_indent:
1620 if self.rl_do_indent:
1622 self.readline.insert_text(self._indent_current_str())
1621 self.readline.insert_text(self._indent_current_str())
1623 if self.rl_next_input is not None:
1622 if self.rl_next_input is not None:
1624 self.readline.insert_text(self.rl_next_input)
1623 self.readline.insert_text(self.rl_next_input)
1625 self.rl_next_input = None
1624 self.rl_next_input = None
1626
1625
1627 def _indent_current_str(self):
1626 def _indent_current_str(self):
1628 """return the current level of indentation as a string"""
1627 """return the current level of indentation as a string"""
1629 return self.input_splitter.indent_spaces * ' '
1628 return self.input_splitter.indent_spaces * ' '
1630
1629
1631 #-------------------------------------------------------------------------
1630 #-------------------------------------------------------------------------
1632 # Things related to text completion
1631 # Things related to text completion
1633 #-------------------------------------------------------------------------
1632 #-------------------------------------------------------------------------
1634
1633
1635 def init_completer(self):
1634 def init_completer(self):
1636 """Initialize the completion machinery.
1635 """Initialize the completion machinery.
1637
1636
1638 This creates completion machinery that can be used by client code,
1637 This creates completion machinery that can be used by client code,
1639 either interactively in-process (typically triggered by the readline
1638 either interactively in-process (typically triggered by the readline
1640 library), programatically (such as in test suites) or out-of-prcess
1639 library), programatically (such as in test suites) or out-of-prcess
1641 (typically over the network by remote frontends).
1640 (typically over the network by remote frontends).
1642 """
1641 """
1643 from IPython.core.completer import IPCompleter
1642 from IPython.core.completer import IPCompleter
1644 from IPython.core.completerlib import (module_completer,
1643 from IPython.core.completerlib import (module_completer,
1645 magic_run_completer, cd_completer)
1644 magic_run_completer, cd_completer)
1646
1645
1647 self.Completer = IPCompleter(self,
1646 self.Completer = IPCompleter(self,
1648 self.user_ns,
1647 self.user_ns,
1649 self.user_global_ns,
1648 self.user_global_ns,
1650 self.readline_omit__names,
1649 self.readline_omit__names,
1651 self.alias_manager.alias_table,
1650 self.alias_manager.alias_table,
1652 self.has_readline)
1651 self.has_readline)
1653
1652
1654 # Add custom completers to the basic ones built into IPCompleter
1653 # Add custom completers to the basic ones built into IPCompleter
1655 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1654 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1656 self.strdispatchers['complete_command'] = sdisp
1655 self.strdispatchers['complete_command'] = sdisp
1657 self.Completer.custom_completers = sdisp
1656 self.Completer.custom_completers = sdisp
1658
1657
1659 self.set_hook('complete_command', module_completer, str_key = 'import')
1658 self.set_hook('complete_command', module_completer, str_key = 'import')
1660 self.set_hook('complete_command', module_completer, str_key = 'from')
1659 self.set_hook('complete_command', module_completer, str_key = 'from')
1661 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1660 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1662 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1661 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1663
1662
1664 # Only configure readline if we truly are using readline. IPython can
1663 # Only configure readline if we truly are using readline. IPython can
1665 # do tab-completion over the network, in GUIs, etc, where readline
1664 # do tab-completion over the network, in GUIs, etc, where readline
1666 # itself may be absent
1665 # itself may be absent
1667 if self.has_readline:
1666 if self.has_readline:
1668 self.set_readline_completer()
1667 self.set_readline_completer()
1669
1668
1670 def complete(self, text, line=None, cursor_pos=None):
1669 def complete(self, text, line=None, cursor_pos=None):
1671 """Return the completed text and a list of completions.
1670 """Return the completed text and a list of completions.
1672
1671
1673 Parameters
1672 Parameters
1674 ----------
1673 ----------
1675
1674
1676 text : string
1675 text : string
1677 A string of text to be completed on. It can be given as empty and
1676 A string of text to be completed on. It can be given as empty and
1678 instead a line/position pair are given. In this case, the
1677 instead a line/position pair are given. In this case, the
1679 completer itself will split the line like readline does.
1678 completer itself will split the line like readline does.
1680
1679
1681 line : string, optional
1680 line : string, optional
1682 The complete line that text is part of.
1681 The complete line that text is part of.
1683
1682
1684 cursor_pos : int, optional
1683 cursor_pos : int, optional
1685 The position of the cursor on the input line.
1684 The position of the cursor on the input line.
1686
1685
1687 Returns
1686 Returns
1688 -------
1687 -------
1689 text : string
1688 text : string
1690 The actual text that was completed.
1689 The actual text that was completed.
1691
1690
1692 matches : list
1691 matches : list
1693 A sorted list with all possible completions.
1692 A sorted list with all possible completions.
1694
1693
1695 The optional arguments allow the completion to take more context into
1694 The optional arguments allow the completion to take more context into
1696 account, and are part of the low-level completion API.
1695 account, and are part of the low-level completion API.
1697
1696
1698 This is a wrapper around the completion mechanism, similar to what
1697 This is a wrapper around the completion mechanism, similar to what
1699 readline does at the command line when the TAB key is hit. By
1698 readline does at the command line when the TAB key is hit. By
1700 exposing it as a method, it can be used by other non-readline
1699 exposing it as a method, it can be used by other non-readline
1701 environments (such as GUIs) for text completion.
1700 environments (such as GUIs) for text completion.
1702
1701
1703 Simple usage example:
1702 Simple usage example:
1704
1703
1705 In [1]: x = 'hello'
1704 In [1]: x = 'hello'
1706
1705
1707 In [2]: _ip.complete('x.l')
1706 In [2]: _ip.complete('x.l')
1708 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1707 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1709 """
1708 """
1710
1709
1711 # Inject names into __builtin__ so we can complete on the added names.
1710 # Inject names into __builtin__ so we can complete on the added names.
1712 with self.builtin_trap:
1711 with self.builtin_trap:
1713 return self.Completer.complete(text, line, cursor_pos)
1712 return self.Completer.complete(text, line, cursor_pos)
1714
1713
1715 def set_custom_completer(self, completer, pos=0):
1714 def set_custom_completer(self, completer, pos=0):
1716 """Adds a new custom completer function.
1715 """Adds a new custom completer function.
1717
1716
1718 The position argument (defaults to 0) is the index in the completers
1717 The position argument (defaults to 0) is the index in the completers
1719 list where you want the completer to be inserted."""
1718 list where you want the completer to be inserted."""
1720
1719
1721 newcomp = types.MethodType(completer,self.Completer)
1720 newcomp = types.MethodType(completer,self.Completer)
1722 self.Completer.matchers.insert(pos,newcomp)
1721 self.Completer.matchers.insert(pos,newcomp)
1723
1722
1724 def set_readline_completer(self):
1723 def set_readline_completer(self):
1725 """Reset readline's completer to be our own."""
1724 """Reset readline's completer to be our own."""
1726 self.readline.set_completer(self.Completer.rlcomplete)
1725 self.readline.set_completer(self.Completer.rlcomplete)
1727
1726
1728 def set_completer_frame(self, frame=None):
1727 def set_completer_frame(self, frame=None):
1729 """Set the frame of the completer."""
1728 """Set the frame of the completer."""
1730 if frame:
1729 if frame:
1731 self.Completer.namespace = frame.f_locals
1730 self.Completer.namespace = frame.f_locals
1732 self.Completer.global_namespace = frame.f_globals
1731 self.Completer.global_namespace = frame.f_globals
1733 else:
1732 else:
1734 self.Completer.namespace = self.user_ns
1733 self.Completer.namespace = self.user_ns
1735 self.Completer.global_namespace = self.user_global_ns
1734 self.Completer.global_namespace = self.user_global_ns
1736
1735
1737 #-------------------------------------------------------------------------
1736 #-------------------------------------------------------------------------
1738 # Things related to magics
1737 # Things related to magics
1739 #-------------------------------------------------------------------------
1738 #-------------------------------------------------------------------------
1740
1739
1741 def init_magics(self):
1740 def init_magics(self):
1742 # FIXME: Move the color initialization to the DisplayHook, which
1741 # FIXME: Move the color initialization to the DisplayHook, which
1743 # should be split into a prompt manager and displayhook. We probably
1742 # should be split into a prompt manager and displayhook. We probably
1744 # even need a centralize colors management object.
1743 # even need a centralize colors management object.
1745 self.magic_colors(self.colors)
1744 self.magic_colors(self.colors)
1746 # History was moved to a separate module
1745 # History was moved to a separate module
1747 from . import history
1746 from . import history
1748 history.init_ipython(self)
1747 history.init_ipython(self)
1749
1748
1750 def magic(self,arg_s):
1749 def magic(self,arg_s):
1751 """Call a magic function by name.
1750 """Call a magic function by name.
1752
1751
1753 Input: a string containing the name of the magic function to call and
1752 Input: a string containing the name of the magic function to call and
1754 any additional arguments to be passed to the magic.
1753 any additional arguments to be passed to the magic.
1755
1754
1756 magic('name -opt foo bar') is equivalent to typing at the ipython
1755 magic('name -opt foo bar') is equivalent to typing at the ipython
1757 prompt:
1756 prompt:
1758
1757
1759 In[1]: %name -opt foo bar
1758 In[1]: %name -opt foo bar
1760
1759
1761 To call a magic without arguments, simply use magic('name').
1760 To call a magic without arguments, simply use magic('name').
1762
1761
1763 This provides a proper Python function to call IPython's magics in any
1762 This provides a proper Python function to call IPython's magics in any
1764 valid Python code you can type at the interpreter, including loops and
1763 valid Python code you can type at the interpreter, including loops and
1765 compound statements.
1764 compound statements.
1766 """
1765 """
1767 args = arg_s.split(' ',1)
1766 args = arg_s.split(' ',1)
1768 magic_name = args[0]
1767 magic_name = args[0]
1769 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1768 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1770
1769
1771 try:
1770 try:
1772 magic_args = args[1]
1771 magic_args = args[1]
1773 except IndexError:
1772 except IndexError:
1774 magic_args = ''
1773 magic_args = ''
1775 fn = getattr(self,'magic_'+magic_name,None)
1774 fn = getattr(self,'magic_'+magic_name,None)
1776 if fn is None:
1775 if fn is None:
1777 error("Magic function `%s` not found." % magic_name)
1776 error("Magic function `%s` not found." % magic_name)
1778 else:
1777 else:
1779 magic_args = self.var_expand(magic_args,1)
1778 magic_args = self.var_expand(magic_args,1)
1780 # Grab local namespace if we need it:
1779 # Grab local namespace if we need it:
1781 if getattr(fn, "needs_local_scope", False):
1780 if getattr(fn, "needs_local_scope", False):
1782 self._magic_locals = sys._getframe(1).f_locals
1781 self._magic_locals = sys._getframe(1).f_locals
1783 with self.builtin_trap:
1782 with self.builtin_trap:
1784 result = fn(magic_args)
1783 result = fn(magic_args)
1785 # Ensure we're not keeping object references around:
1784 # Ensure we're not keeping object references around:
1786 self._magic_locals = {}
1785 self._magic_locals = {}
1787 return result
1786 return result
1788
1787
1789 def define_magic(self, magicname, func):
1788 def define_magic(self, magicname, func):
1790 """Expose own function as magic function for ipython
1789 """Expose own function as magic function for ipython
1791
1790
1792 def foo_impl(self,parameter_s=''):
1791 def foo_impl(self,parameter_s=''):
1793 'My very own magic!. (Use docstrings, IPython reads them).'
1792 'My very own magic!. (Use docstrings, IPython reads them).'
1794 print 'Magic function. Passed parameter is between < >:'
1793 print 'Magic function. Passed parameter is between < >:'
1795 print '<%s>' % parameter_s
1794 print '<%s>' % parameter_s
1796 print 'The self object is:',self
1795 print 'The self object is:',self
1797
1796
1798 self.define_magic('foo',foo_impl)
1797 self.define_magic('foo',foo_impl)
1799 """
1798 """
1800
1799
1801 import new
1800 import new
1802 im = types.MethodType(func,self)
1801 im = types.MethodType(func,self)
1803 old = getattr(self, "magic_" + magicname, None)
1802 old = getattr(self, "magic_" + magicname, None)
1804 setattr(self, "magic_" + magicname, im)
1803 setattr(self, "magic_" + magicname, im)
1805 return old
1804 return old
1806
1805
1807 #-------------------------------------------------------------------------
1806 #-------------------------------------------------------------------------
1808 # Things related to macros
1807 # Things related to macros
1809 #-------------------------------------------------------------------------
1808 #-------------------------------------------------------------------------
1810
1809
1811 def define_macro(self, name, themacro):
1810 def define_macro(self, name, themacro):
1812 """Define a new macro
1811 """Define a new macro
1813
1812
1814 Parameters
1813 Parameters
1815 ----------
1814 ----------
1816 name : str
1815 name : str
1817 The name of the macro.
1816 The name of the macro.
1818 themacro : str or Macro
1817 themacro : str or Macro
1819 The action to do upon invoking the macro. If a string, a new
1818 The action to do upon invoking the macro. If a string, a new
1820 Macro object is created by passing the string to it.
1819 Macro object is created by passing the string to it.
1821 """
1820 """
1822
1821
1823 from IPython.core import macro
1822 from IPython.core import macro
1824
1823
1825 if isinstance(themacro, basestring):
1824 if isinstance(themacro, basestring):
1826 themacro = macro.Macro(themacro)
1825 themacro = macro.Macro(themacro)
1827 if not isinstance(themacro, macro.Macro):
1826 if not isinstance(themacro, macro.Macro):
1828 raise ValueError('A macro must be a string or a Macro instance.')
1827 raise ValueError('A macro must be a string or a Macro instance.')
1829 self.user_ns[name] = themacro
1828 self.user_ns[name] = themacro
1830
1829
1831 #-------------------------------------------------------------------------
1830 #-------------------------------------------------------------------------
1832 # Things related to the running of system commands
1831 # Things related to the running of system commands
1833 #-------------------------------------------------------------------------
1832 #-------------------------------------------------------------------------
1834
1833
1835 def system(self, cmd):
1834 def system(self, cmd):
1836 """Call the given cmd in a subprocess.
1835 """Call the given cmd in a subprocess.
1837
1836
1838 Parameters
1837 Parameters
1839 ----------
1838 ----------
1840 cmd : str
1839 cmd : str
1841 Command to execute (can not end in '&', as bacground processes are
1840 Command to execute (can not end in '&', as bacground processes are
1842 not supported.
1841 not supported.
1843 """
1842 """
1844 # We do not support backgrounding processes because we either use
1843 # We do not support backgrounding processes because we either use
1845 # pexpect or pipes to read from. Users can always just call
1844 # pexpect or pipes to read from. Users can always just call
1846 # os.system() if they really want a background process.
1845 # os.system() if they really want a background process.
1847 if cmd.endswith('&'):
1846 if cmd.endswith('&'):
1848 raise OSError("Background processes not supported.")
1847 raise OSError("Background processes not supported.")
1849
1848
1850 return system(self.var_expand(cmd, depth=2))
1849 return system(self.var_expand(cmd, depth=2))
1851
1850
1852 def getoutput(self, cmd, split=True):
1851 def getoutput(self, cmd, split=True):
1853 """Get output (possibly including stderr) from a subprocess.
1852 """Get output (possibly including stderr) from a subprocess.
1854
1853
1855 Parameters
1854 Parameters
1856 ----------
1855 ----------
1857 cmd : str
1856 cmd : str
1858 Command to execute (can not end in '&', as background processes are
1857 Command to execute (can not end in '&', as background processes are
1859 not supported.
1858 not supported.
1860 split : bool, optional
1859 split : bool, optional
1861
1860
1862 If True, split the output into an IPython SList. Otherwise, an
1861 If True, split the output into an IPython SList. Otherwise, an
1863 IPython LSString is returned. These are objects similar to normal
1862 IPython LSString is returned. These are objects similar to normal
1864 lists and strings, with a few convenience attributes for easier
1863 lists and strings, with a few convenience attributes for easier
1865 manipulation of line-based output. You can use '?' on them for
1864 manipulation of line-based output. You can use '?' on them for
1866 details.
1865 details.
1867 """
1866 """
1868 if cmd.endswith('&'):
1867 if cmd.endswith('&'):
1869 raise OSError("Background processes not supported.")
1868 raise OSError("Background processes not supported.")
1870 out = getoutput(self.var_expand(cmd, depth=2))
1869 out = getoutput(self.var_expand(cmd, depth=2))
1871 if split:
1870 if split:
1872 out = SList(out.splitlines())
1871 out = SList(out.splitlines())
1873 else:
1872 else:
1874 out = LSString(out)
1873 out = LSString(out)
1875 return out
1874 return out
1876
1875
1877 #-------------------------------------------------------------------------
1876 #-------------------------------------------------------------------------
1878 # Things related to aliases
1877 # Things related to aliases
1879 #-------------------------------------------------------------------------
1878 #-------------------------------------------------------------------------
1880
1879
1881 def init_alias(self):
1880 def init_alias(self):
1882 self.alias_manager = AliasManager(shell=self, config=self.config)
1881 self.alias_manager = AliasManager(shell=self, config=self.config)
1883 self.ns_table['alias'] = self.alias_manager.alias_table,
1882 self.ns_table['alias'] = self.alias_manager.alias_table,
1884
1883
1885 #-------------------------------------------------------------------------
1884 #-------------------------------------------------------------------------
1886 # Things related to extensions and plugins
1885 # Things related to extensions and plugins
1887 #-------------------------------------------------------------------------
1886 #-------------------------------------------------------------------------
1888
1887
1889 def init_extension_manager(self):
1888 def init_extension_manager(self):
1890 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1889 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1891
1890
1892 def init_plugin_manager(self):
1891 def init_plugin_manager(self):
1893 self.plugin_manager = PluginManager(config=self.config)
1892 self.plugin_manager = PluginManager(config=self.config)
1894
1893
1895 #-------------------------------------------------------------------------
1894 #-------------------------------------------------------------------------
1896 # Things related to payloads
1895 # Things related to payloads
1897 #-------------------------------------------------------------------------
1896 #-------------------------------------------------------------------------
1898
1897
1899 def init_payload(self):
1898 def init_payload(self):
1900 self.payload_manager = PayloadManager(config=self.config)
1899 self.payload_manager = PayloadManager(config=self.config)
1901
1900
1902 #-------------------------------------------------------------------------
1901 #-------------------------------------------------------------------------
1903 # Things related to the prefilter
1902 # Things related to the prefilter
1904 #-------------------------------------------------------------------------
1903 #-------------------------------------------------------------------------
1905
1904
1906 def init_prefilter(self):
1905 def init_prefilter(self):
1907 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1906 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1908 # Ultimately this will be refactored in the new interpreter code, but
1907 # Ultimately this will be refactored in the new interpreter code, but
1909 # for now, we should expose the main prefilter method (there's legacy
1908 # for now, we should expose the main prefilter method (there's legacy
1910 # code out there that may rely on this).
1909 # code out there that may rely on this).
1911 self.prefilter = self.prefilter_manager.prefilter_lines
1910 self.prefilter = self.prefilter_manager.prefilter_lines
1912
1911
1913 def auto_rewrite_input(self, cmd):
1912 def auto_rewrite_input(self, cmd):
1914 """Print to the screen the rewritten form of the user's command.
1913 """Print to the screen the rewritten form of the user's command.
1915
1914
1916 This shows visual feedback by rewriting input lines that cause
1915 This shows visual feedback by rewriting input lines that cause
1917 automatic calling to kick in, like::
1916 automatic calling to kick in, like::
1918
1917
1919 /f x
1918 /f x
1920
1919
1921 into::
1920 into::
1922
1921
1923 ------> f(x)
1922 ------> f(x)
1924
1923
1925 after the user's input prompt. This helps the user understand that the
1924 after the user's input prompt. This helps the user understand that the
1926 input line was transformed automatically by IPython.
1925 input line was transformed automatically by IPython.
1927 """
1926 """
1928 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1927 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1929
1928
1930 try:
1929 try:
1931 # plain ascii works better w/ pyreadline, on some machines, so
1930 # plain ascii works better w/ pyreadline, on some machines, so
1932 # we use it and only print uncolored rewrite if we have unicode
1931 # we use it and only print uncolored rewrite if we have unicode
1933 rw = str(rw)
1932 rw = str(rw)
1934 print >> IPython.utils.io.Term.cout, rw
1933 print >> io.stdout, rw
1935 except UnicodeEncodeError:
1934 except UnicodeEncodeError:
1936 print "------> " + cmd
1935 print "------> " + cmd
1937
1936
1938 #-------------------------------------------------------------------------
1937 #-------------------------------------------------------------------------
1939 # Things related to extracting values/expressions from kernel and user_ns
1938 # Things related to extracting values/expressions from kernel and user_ns
1940 #-------------------------------------------------------------------------
1939 #-------------------------------------------------------------------------
1941
1940
1942 def _simple_error(self):
1941 def _simple_error(self):
1943 etype, value = sys.exc_info()[:2]
1942 etype, value = sys.exc_info()[:2]
1944 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1943 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1945
1944
1946 def user_variables(self, names):
1945 def user_variables(self, names):
1947 """Get a list of variable names from the user's namespace.
1946 """Get a list of variable names from the user's namespace.
1948
1947
1949 Parameters
1948 Parameters
1950 ----------
1949 ----------
1951 names : list of strings
1950 names : list of strings
1952 A list of names of variables to be read from the user namespace.
1951 A list of names of variables to be read from the user namespace.
1953
1952
1954 Returns
1953 Returns
1955 -------
1954 -------
1956 A dict, keyed by the input names and with the repr() of each value.
1955 A dict, keyed by the input names and with the repr() of each value.
1957 """
1956 """
1958 out = {}
1957 out = {}
1959 user_ns = self.user_ns
1958 user_ns = self.user_ns
1960 for varname in names:
1959 for varname in names:
1961 try:
1960 try:
1962 value = repr(user_ns[varname])
1961 value = repr(user_ns[varname])
1963 except:
1962 except:
1964 value = self._simple_error()
1963 value = self._simple_error()
1965 out[varname] = value
1964 out[varname] = value
1966 return out
1965 return out
1967
1966
1968 def user_expressions(self, expressions):
1967 def user_expressions(self, expressions):
1969 """Evaluate a dict of expressions in the user's namespace.
1968 """Evaluate a dict of expressions in the user's namespace.
1970
1969
1971 Parameters
1970 Parameters
1972 ----------
1971 ----------
1973 expressions : dict
1972 expressions : dict
1974 A dict with string keys and string values. The expression values
1973 A dict with string keys and string values. The expression values
1975 should be valid Python expressions, each of which will be evaluated
1974 should be valid Python expressions, each of which will be evaluated
1976 in the user namespace.
1975 in the user namespace.
1977
1976
1978 Returns
1977 Returns
1979 -------
1978 -------
1980 A dict, keyed like the input expressions dict, with the repr() of each
1979 A dict, keyed like the input expressions dict, with the repr() of each
1981 value.
1980 value.
1982 """
1981 """
1983 out = {}
1982 out = {}
1984 user_ns = self.user_ns
1983 user_ns = self.user_ns
1985 global_ns = self.user_global_ns
1984 global_ns = self.user_global_ns
1986 for key, expr in expressions.iteritems():
1985 for key, expr in expressions.iteritems():
1987 try:
1986 try:
1988 value = repr(eval(expr, global_ns, user_ns))
1987 value = repr(eval(expr, global_ns, user_ns))
1989 except:
1988 except:
1990 value = self._simple_error()
1989 value = self._simple_error()
1991 out[key] = value
1990 out[key] = value
1992 return out
1991 return out
1993
1992
1994 #-------------------------------------------------------------------------
1993 #-------------------------------------------------------------------------
1995 # Things related to the running of code
1994 # Things related to the running of code
1996 #-------------------------------------------------------------------------
1995 #-------------------------------------------------------------------------
1997
1996
1998 def ex(self, cmd):
1997 def ex(self, cmd):
1999 """Execute a normal python statement in user namespace."""
1998 """Execute a normal python statement in user namespace."""
2000 with self.builtin_trap:
1999 with self.builtin_trap:
2001 exec cmd in self.user_global_ns, self.user_ns
2000 exec cmd in self.user_global_ns, self.user_ns
2002
2001
2003 def ev(self, expr):
2002 def ev(self, expr):
2004 """Evaluate python expression expr in user namespace.
2003 """Evaluate python expression expr in user namespace.
2005
2004
2006 Returns the result of evaluation
2005 Returns the result of evaluation
2007 """
2006 """
2008 with self.builtin_trap:
2007 with self.builtin_trap:
2009 return eval(expr, self.user_global_ns, self.user_ns)
2008 return eval(expr, self.user_global_ns, self.user_ns)
2010
2009
2011 def safe_execfile(self, fname, *where, **kw):
2010 def safe_execfile(self, fname, *where, **kw):
2012 """A safe version of the builtin execfile().
2011 """A safe version of the builtin execfile().
2013
2012
2014 This version will never throw an exception, but instead print
2013 This version will never throw an exception, but instead print
2015 helpful error messages to the screen. This only works on pure
2014 helpful error messages to the screen. This only works on pure
2016 Python files with the .py extension.
2015 Python files with the .py extension.
2017
2016
2018 Parameters
2017 Parameters
2019 ----------
2018 ----------
2020 fname : string
2019 fname : string
2021 The name of the file to be executed.
2020 The name of the file to be executed.
2022 where : tuple
2021 where : tuple
2023 One or two namespaces, passed to execfile() as (globals,locals).
2022 One or two namespaces, passed to execfile() as (globals,locals).
2024 If only one is given, it is passed as both.
2023 If only one is given, it is passed as both.
2025 exit_ignore : bool (False)
2024 exit_ignore : bool (False)
2026 If True, then silence SystemExit for non-zero status (it is always
2025 If True, then silence SystemExit for non-zero status (it is always
2027 silenced for zero status, as it is so common).
2026 silenced for zero status, as it is so common).
2028 """
2027 """
2029 kw.setdefault('exit_ignore', False)
2028 kw.setdefault('exit_ignore', False)
2030
2029
2031 fname = os.path.abspath(os.path.expanduser(fname))
2030 fname = os.path.abspath(os.path.expanduser(fname))
2032 # Make sure we have a .py file
2031 # Make sure we have a .py file
2033 if not fname.endswith('.py'):
2032 if not fname.endswith('.py'):
2034 warn('File must end with .py to be run using execfile: <%s>' % fname)
2033 warn('File must end with .py to be run using execfile: <%s>' % fname)
2035
2034
2036 # Make sure we can open the file
2035 # Make sure we can open the file
2037 try:
2036 try:
2038 with open(fname) as thefile:
2037 with open(fname) as thefile:
2039 pass
2038 pass
2040 except:
2039 except:
2041 warn('Could not open file <%s> for safe execution.' % fname)
2040 warn('Could not open file <%s> for safe execution.' % fname)
2042 return
2041 return
2043
2042
2044 # Find things also in current directory. This is needed to mimic the
2043 # Find things also in current directory. This is needed to mimic the
2045 # behavior of running a script from the system command line, where
2044 # behavior of running a script from the system command line, where
2046 # Python inserts the script's directory into sys.path
2045 # Python inserts the script's directory into sys.path
2047 dname = os.path.dirname(fname)
2046 dname = os.path.dirname(fname)
2048
2047
2049 if isinstance(fname, unicode):
2048 if isinstance(fname, unicode):
2050 # execfile uses default encoding instead of filesystem encoding
2049 # execfile uses default encoding instead of filesystem encoding
2051 # so unicode filenames will fail
2050 # so unicode filenames will fail
2052 fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding())
2051 fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding())
2053
2052
2054 with prepended_to_syspath(dname):
2053 with prepended_to_syspath(dname):
2055 try:
2054 try:
2056 execfile(fname,*where)
2055 execfile(fname,*where)
2057 except SystemExit, status:
2056 except SystemExit, status:
2058 # If the call was made with 0 or None exit status (sys.exit(0)
2057 # If the call was made with 0 or None exit status (sys.exit(0)
2059 # or sys.exit() ), don't bother showing a traceback, as both of
2058 # or sys.exit() ), don't bother showing a traceback, as both of
2060 # these are considered normal by the OS:
2059 # these are considered normal by the OS:
2061 # > python -c'import sys;sys.exit(0)'; echo $?
2060 # > python -c'import sys;sys.exit(0)'; echo $?
2062 # 0
2061 # 0
2063 # > python -c'import sys;sys.exit()'; echo $?
2062 # > python -c'import sys;sys.exit()'; echo $?
2064 # 0
2063 # 0
2065 # For other exit status, we show the exception unless
2064 # For other exit status, we show the exception unless
2066 # explicitly silenced, but only in short form.
2065 # explicitly silenced, but only in short form.
2067 if status.code not in (0, None) and not kw['exit_ignore']:
2066 if status.code not in (0, None) and not kw['exit_ignore']:
2068 self.showtraceback(exception_only=True)
2067 self.showtraceback(exception_only=True)
2069 except:
2068 except:
2070 self.showtraceback()
2069 self.showtraceback()
2071
2070
2072 def safe_execfile_ipy(self, fname):
2071 def safe_execfile_ipy(self, fname):
2073 """Like safe_execfile, but for .ipy files with IPython syntax.
2072 """Like safe_execfile, but for .ipy files with IPython syntax.
2074
2073
2075 Parameters
2074 Parameters
2076 ----------
2075 ----------
2077 fname : str
2076 fname : str
2078 The name of the file to execute. The filename must have a
2077 The name of the file to execute. The filename must have a
2079 .ipy extension.
2078 .ipy extension.
2080 """
2079 """
2081 fname = os.path.abspath(os.path.expanduser(fname))
2080 fname = os.path.abspath(os.path.expanduser(fname))
2082
2081
2083 # Make sure we have a .py file
2082 # Make sure we have a .py file
2084 if not fname.endswith('.ipy'):
2083 if not fname.endswith('.ipy'):
2085 warn('File must end with .py to be run using execfile: <%s>' % fname)
2084 warn('File must end with .py to be run using execfile: <%s>' % fname)
2086
2085
2087 # Make sure we can open the file
2086 # Make sure we can open the file
2088 try:
2087 try:
2089 with open(fname) as thefile:
2088 with open(fname) as thefile:
2090 pass
2089 pass
2091 except:
2090 except:
2092 warn('Could not open file <%s> for safe execution.' % fname)
2091 warn('Could not open file <%s> for safe execution.' % fname)
2093 return
2092 return
2094
2093
2095 # Find things also in current directory. This is needed to mimic the
2094 # Find things also in current directory. This is needed to mimic the
2096 # behavior of running a script from the system command line, where
2095 # behavior of running a script from the system command line, where
2097 # Python inserts the script's directory into sys.path
2096 # Python inserts the script's directory into sys.path
2098 dname = os.path.dirname(fname)
2097 dname = os.path.dirname(fname)
2099
2098
2100 with prepended_to_syspath(dname):
2099 with prepended_to_syspath(dname):
2101 try:
2100 try:
2102 with open(fname) as thefile:
2101 with open(fname) as thefile:
2103 # self.run_cell currently captures all exceptions
2102 # self.run_cell currently captures all exceptions
2104 # raised in user code. It would be nice if there were
2103 # raised in user code. It would be nice if there were
2105 # versions of runlines, execfile that did raise, so
2104 # versions of runlines, execfile that did raise, so
2106 # we could catch the errors.
2105 # we could catch the errors.
2107 self.run_cell(thefile.read(), store_history=False)
2106 self.run_cell(thefile.read(), store_history=False)
2108 except:
2107 except:
2109 self.showtraceback()
2108 self.showtraceback()
2110 warn('Unknown failure executing file: <%s>' % fname)
2109 warn('Unknown failure executing file: <%s>' % fname)
2111
2110
2112 def run_cell(self, raw_cell, store_history=True):
2111 def run_cell(self, raw_cell, store_history=True):
2113 """Run a complete IPython cell.
2112 """Run a complete IPython cell.
2114
2113
2115 Parameters
2114 Parameters
2116 ----------
2115 ----------
2117 raw_cell : str
2116 raw_cell : str
2118 The code (including IPython code such as %magic functions) to run.
2117 The code (including IPython code such as %magic functions) to run.
2119 store_history : bool
2118 store_history : bool
2120 If True, the raw and translated cell will be stored in IPython's
2119 If True, the raw and translated cell will be stored in IPython's
2121 history. For user code calling back into IPython's machinery, this
2120 history. For user code calling back into IPython's machinery, this
2122 should be set to False.
2121 should be set to False.
2123 """
2122 """
2124 if (not raw_cell) or raw_cell.isspace():
2123 if (not raw_cell) or raw_cell.isspace():
2125 return
2124 return
2126
2125
2127 for line in raw_cell.splitlines():
2126 for line in raw_cell.splitlines():
2128 self.input_splitter.push(line)
2127 self.input_splitter.push(line)
2129 cell = self.input_splitter.source_reset()
2128 cell = self.input_splitter.source_reset()
2130
2129
2131 with self.builtin_trap:
2130 with self.builtin_trap:
2132 if len(cell.splitlines()) == 1:
2131 if len(cell.splitlines()) == 1:
2133 cell = self.prefilter_manager.prefilter_lines(cell)
2132 cell = self.prefilter_manager.prefilter_lines(cell)
2134
2133
2135 # Store raw and processed history
2134 # Store raw and processed history
2136 if store_history:
2135 if store_history:
2137 self.history_manager.store_inputs(self.execution_count,
2136 self.history_manager.store_inputs(self.execution_count,
2138 cell, raw_cell)
2137 cell, raw_cell)
2139
2138
2140 self.logger.log(cell, raw_cell)
2139 self.logger.log(cell, raw_cell)
2141
2140
2142 cell_name = self.compile.cache(cell, self.execution_count)
2141 cell_name = self.compile.cache(cell, self.execution_count)
2143
2142
2144 with self.display_trap:
2143 with self.display_trap:
2145 try:
2144 try:
2146 code_ast = ast.parse(cell, filename=cell_name)
2145 code_ast = ast.parse(cell, filename=cell_name)
2147 except (OverflowError, SyntaxError, ValueError, TypeError,
2146 except (OverflowError, SyntaxError, ValueError, TypeError,
2148 MemoryError):
2147 MemoryError):
2149 self.showsyntaxerror()
2148 self.showsyntaxerror()
2150 self.execution_count += 1
2149 self.execution_count += 1
2151 return None
2150 return None
2152
2151
2153 self.run_ast_nodes(code_ast.body, cell_name,
2152 self.run_ast_nodes(code_ast.body, cell_name,
2154 interactivity="last_expr")
2153 interactivity="last_expr")
2155
2154
2156 # Execute any registered post-execution functions.
2155 # Execute any registered post-execution functions.
2157 for func, status in self._post_execute.iteritems():
2156 for func, status in self._post_execute.iteritems():
2158 if not status:
2157 if not status:
2159 continue
2158 continue
2160 try:
2159 try:
2161 func()
2160 func()
2162 except:
2161 except:
2163 self.showtraceback()
2162 self.showtraceback()
2164 # Deactivate failing function
2163 # Deactivate failing function
2165 self._post_execute[func] = False
2164 self._post_execute[func] = False
2166
2165
2167 if store_history:
2166 if store_history:
2168 # Write output to the database. Does nothing unless
2167 # Write output to the database. Does nothing unless
2169 # history output logging is enabled.
2168 # history output logging is enabled.
2170 self.history_manager.store_output(self.execution_count)
2169 self.history_manager.store_output(self.execution_count)
2171 # Each cell is a *single* input, regardless of how many lines it has
2170 # Each cell is a *single* input, regardless of how many lines it has
2172 self.execution_count += 1
2171 self.execution_count += 1
2173
2172
2174 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2173 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2175 """Run a sequence of AST nodes. The execution mode depends on the
2174 """Run a sequence of AST nodes. The execution mode depends on the
2176 interactivity parameter.
2175 interactivity parameter.
2177
2176
2178 Parameters
2177 Parameters
2179 ----------
2178 ----------
2180 nodelist : list
2179 nodelist : list
2181 A sequence of AST nodes to run.
2180 A sequence of AST nodes to run.
2182 cell_name : str
2181 cell_name : str
2183 Will be passed to the compiler as the filename of the cell. Typically
2182 Will be passed to the compiler as the filename of the cell. Typically
2184 the value returned by ip.compile.cache(cell).
2183 the value returned by ip.compile.cache(cell).
2185 interactivity : str
2184 interactivity : str
2186 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2185 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2187 run interactively (displaying output from expressions). 'last_expr'
2186 run interactively (displaying output from expressions). 'last_expr'
2188 will run the last node interactively only if it is an expression (i.e.
2187 will run the last node interactively only if it is an expression (i.e.
2189 expressions in loops or other blocks are not displayed. Other values
2188 expressions in loops or other blocks are not displayed. Other values
2190 for this parameter will raise a ValueError.
2189 for this parameter will raise a ValueError.
2191 """
2190 """
2192 if not nodelist:
2191 if not nodelist:
2193 return
2192 return
2194
2193
2195 if interactivity == 'last_expr':
2194 if interactivity == 'last_expr':
2196 if isinstance(nodelist[-1], ast.Expr):
2195 if isinstance(nodelist[-1], ast.Expr):
2197 interactivity = "last"
2196 interactivity = "last"
2198 else:
2197 else:
2199 interactivity = "none"
2198 interactivity = "none"
2200
2199
2201 if interactivity == 'none':
2200 if interactivity == 'none':
2202 to_run_exec, to_run_interactive = nodelist, []
2201 to_run_exec, to_run_interactive = nodelist, []
2203 elif interactivity == 'last':
2202 elif interactivity == 'last':
2204 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2203 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2205 elif interactivity == 'all':
2204 elif interactivity == 'all':
2206 to_run_exec, to_run_interactive = [], nodelist
2205 to_run_exec, to_run_interactive = [], nodelist
2207 else:
2206 else:
2208 raise ValueError("Interactivity was %r" % interactivity)
2207 raise ValueError("Interactivity was %r" % interactivity)
2209
2208
2210 exec_count = self.execution_count
2209 exec_count = self.execution_count
2211
2210
2212 for i, node in enumerate(to_run_exec):
2211 for i, node in enumerate(to_run_exec):
2213 mod = ast.Module([node])
2212 mod = ast.Module([node])
2214 code = self.compile(mod, cell_name, "exec")
2213 code = self.compile(mod, cell_name, "exec")
2215 if self.run_code(code):
2214 if self.run_code(code):
2216 return True
2215 return True
2217
2216
2218 for i, node in enumerate(to_run_interactive):
2217 for i, node in enumerate(to_run_interactive):
2219 mod = ast.Interactive([node])
2218 mod = ast.Interactive([node])
2220 code = self.compile(mod, cell_name, "single")
2219 code = self.compile(mod, cell_name, "single")
2221 if self.run_code(code):
2220 if self.run_code(code):
2222 return True
2221 return True
2223
2222
2224 return False
2223 return False
2225
2224
2226 def run_code(self, code_obj):
2225 def run_code(self, code_obj):
2227 """Execute a code object.
2226 """Execute a code object.
2228
2227
2229 When an exception occurs, self.showtraceback() is called to display a
2228 When an exception occurs, self.showtraceback() is called to display a
2230 traceback.
2229 traceback.
2231
2230
2232 Parameters
2231 Parameters
2233 ----------
2232 ----------
2234 code_obj : code object
2233 code_obj : code object
2235 A compiled code object, to be executed
2234 A compiled code object, to be executed
2236 post_execute : bool [default: True]
2235 post_execute : bool [default: True]
2237 whether to call post_execute hooks after this particular execution.
2236 whether to call post_execute hooks after this particular execution.
2238
2237
2239 Returns
2238 Returns
2240 -------
2239 -------
2241 False : successful execution.
2240 False : successful execution.
2242 True : an error occurred.
2241 True : an error occurred.
2243 """
2242 """
2244
2243
2245 # Set our own excepthook in case the user code tries to call it
2244 # Set our own excepthook in case the user code tries to call it
2246 # directly, so that the IPython crash handler doesn't get triggered
2245 # directly, so that the IPython crash handler doesn't get triggered
2247 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2246 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2248
2247
2249 # we save the original sys.excepthook in the instance, in case config
2248 # we save the original sys.excepthook in the instance, in case config
2250 # code (such as magics) needs access to it.
2249 # code (such as magics) needs access to it.
2251 self.sys_excepthook = old_excepthook
2250 self.sys_excepthook = old_excepthook
2252 outflag = 1 # happens in more places, so it's easier as default
2251 outflag = 1 # happens in more places, so it's easier as default
2253 try:
2252 try:
2254 try:
2253 try:
2255 self.hooks.pre_run_code_hook()
2254 self.hooks.pre_run_code_hook()
2256 #rprint('Running code', repr(code_obj)) # dbg
2255 #rprint('Running code', repr(code_obj)) # dbg
2257 exec code_obj in self.user_global_ns, self.user_ns
2256 exec code_obj in self.user_global_ns, self.user_ns
2258 finally:
2257 finally:
2259 # Reset our crash handler in place
2258 # Reset our crash handler in place
2260 sys.excepthook = old_excepthook
2259 sys.excepthook = old_excepthook
2261 except SystemExit:
2260 except SystemExit:
2262 self.showtraceback(exception_only=True)
2261 self.showtraceback(exception_only=True)
2263 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2262 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2264 except self.custom_exceptions:
2263 except self.custom_exceptions:
2265 etype,value,tb = sys.exc_info()
2264 etype,value,tb = sys.exc_info()
2266 self.CustomTB(etype,value,tb)
2265 self.CustomTB(etype,value,tb)
2267 except:
2266 except:
2268 self.showtraceback()
2267 self.showtraceback()
2269 else:
2268 else:
2270 outflag = 0
2269 outflag = 0
2271 if softspace(sys.stdout, 0):
2270 if softspace(sys.stdout, 0):
2272 print
2271 print
2273
2272
2274 return outflag
2273 return outflag
2275
2274
2276 # For backwards compatibility
2275 # For backwards compatibility
2277 runcode = run_code
2276 runcode = run_code
2278
2277
2279 #-------------------------------------------------------------------------
2278 #-------------------------------------------------------------------------
2280 # Things related to GUI support and pylab
2279 # Things related to GUI support and pylab
2281 #-------------------------------------------------------------------------
2280 #-------------------------------------------------------------------------
2282
2281
2283 def enable_pylab(self, gui=None):
2282 def enable_pylab(self, gui=None):
2284 raise NotImplementedError('Implement enable_pylab in a subclass')
2283 raise NotImplementedError('Implement enable_pylab in a subclass')
2285
2284
2286 #-------------------------------------------------------------------------
2285 #-------------------------------------------------------------------------
2287 # Utilities
2286 # Utilities
2288 #-------------------------------------------------------------------------
2287 #-------------------------------------------------------------------------
2289
2288
2290 def var_expand(self,cmd,depth=0):
2289 def var_expand(self,cmd,depth=0):
2291 """Expand python variables in a string.
2290 """Expand python variables in a string.
2292
2291
2293 The depth argument indicates how many frames above the caller should
2292 The depth argument indicates how many frames above the caller should
2294 be walked to look for the local namespace where to expand variables.
2293 be walked to look for the local namespace where to expand variables.
2295
2294
2296 The global namespace for expansion is always the user's interactive
2295 The global namespace for expansion is always the user's interactive
2297 namespace.
2296 namespace.
2298 """
2297 """
2299 res = ItplNS(cmd, self.user_ns, # globals
2298 res = ItplNS(cmd, self.user_ns, # globals
2300 # Skip our own frame in searching for locals:
2299 # Skip our own frame in searching for locals:
2301 sys._getframe(depth+1).f_locals # locals
2300 sys._getframe(depth+1).f_locals # locals
2302 )
2301 )
2303 return str(res).decode(res.codec)
2302 return str(res).decode(res.codec)
2304
2303
2305 def mktempfile(self, data=None, prefix='ipython_edit_'):
2304 def mktempfile(self, data=None, prefix='ipython_edit_'):
2306 """Make a new tempfile and return its filename.
2305 """Make a new tempfile and return its filename.
2307
2306
2308 This makes a call to tempfile.mktemp, but it registers the created
2307 This makes a call to tempfile.mktemp, but it registers the created
2309 filename internally so ipython cleans it up at exit time.
2308 filename internally so ipython cleans it up at exit time.
2310
2309
2311 Optional inputs:
2310 Optional inputs:
2312
2311
2313 - data(None): if data is given, it gets written out to the temp file
2312 - data(None): if data is given, it gets written out to the temp file
2314 immediately, and the file is closed again."""
2313 immediately, and the file is closed again."""
2315
2314
2316 filename = tempfile.mktemp('.py', prefix)
2315 filename = tempfile.mktemp('.py', prefix)
2317 self.tempfiles.append(filename)
2316 self.tempfiles.append(filename)
2318
2317
2319 if data:
2318 if data:
2320 tmp_file = open(filename,'w')
2319 tmp_file = open(filename,'w')
2321 tmp_file.write(data)
2320 tmp_file.write(data)
2322 tmp_file.close()
2321 tmp_file.close()
2323 return filename
2322 return filename
2324
2323
2325 # TODO: This should be removed when Term is refactored.
2324 # TODO: This should be removed when Term is refactored.
2326 def write(self,data):
2325 def write(self,data):
2327 """Write a string to the default output"""
2326 """Write a string to the default output"""
2328 io.Term.cout.write(data)
2327 io.stdout.write(data)
2329
2328
2330 # TODO: This should be removed when Term is refactored.
2329 # TODO: This should be removed when Term is refactored.
2331 def write_err(self,data):
2330 def write_err(self,data):
2332 """Write a string to the default error output"""
2331 """Write a string to the default error output"""
2333 io.Term.cerr.write(data)
2332 io.stderr.write(data)
2334
2333
2335 def ask_yes_no(self,prompt,default=True):
2334 def ask_yes_no(self,prompt,default=True):
2336 if self.quiet:
2335 if self.quiet:
2337 return True
2336 return True
2338 return ask_yes_no(prompt,default)
2337 return ask_yes_no(prompt,default)
2339
2338
2340 def show_usage(self):
2339 def show_usage(self):
2341 """Show a usage message"""
2340 """Show a usage message"""
2342 page.page(IPython.core.usage.interactive_usage)
2341 page.page(IPython.core.usage.interactive_usage)
2343
2342
2344 def find_user_code(self, target, raw=True):
2343 def find_user_code(self, target, raw=True):
2345 """Get a code string from history, file, or a string or macro.
2344 """Get a code string from history, file, or a string or macro.
2346
2345
2347 This is mainly used by magic functions.
2346 This is mainly used by magic functions.
2348
2347
2349 Parameters
2348 Parameters
2350 ----------
2349 ----------
2351 target : str
2350 target : str
2352 A string specifying code to retrieve. This will be tried respectively
2351 A string specifying code to retrieve. This will be tried respectively
2353 as: ranges of input history (see %history for syntax), a filename, or
2352 as: ranges of input history (see %history for syntax), a filename, or
2354 an expression evaluating to a string or Macro in the user namespace.
2353 an expression evaluating to a string or Macro in the user namespace.
2355 raw : bool
2354 raw : bool
2356 If true (default), retrieve raw history. Has no effect on the other
2355 If true (default), retrieve raw history. Has no effect on the other
2357 retrieval mechanisms.
2356 retrieval mechanisms.
2358
2357
2359 Returns
2358 Returns
2360 -------
2359 -------
2361 A string of code.
2360 A string of code.
2362
2361
2363 ValueError is raised if nothing is found, and TypeError if it evaluates
2362 ValueError is raised if nothing is found, and TypeError if it evaluates
2364 to an object of another type. In each case, .args[0] is a printable
2363 to an object of another type. In each case, .args[0] is a printable
2365 message.
2364 message.
2366 """
2365 """
2367 code = self.extract_input_lines(target, raw=raw) # Grab history
2366 code = self.extract_input_lines(target, raw=raw) # Grab history
2368 if code:
2367 if code:
2369 return code
2368 return code
2370 if os.path.isfile(target): # Read file
2369 if os.path.isfile(target): # Read file
2371 return open(target, "r").read()
2370 return open(target, "r").read()
2372
2371
2373 try: # User namespace
2372 try: # User namespace
2374 codeobj = eval(target, self.user_ns)
2373 codeobj = eval(target, self.user_ns)
2375 except Exception:
2374 except Exception:
2376 raise ValueError(("'%s' was not found in history, as a file, nor in"
2375 raise ValueError(("'%s' was not found in history, as a file, nor in"
2377 " the user namespace.") % target)
2376 " the user namespace.") % target)
2378 if isinstance(codeobj, basestring):
2377 if isinstance(codeobj, basestring):
2379 return codeobj
2378 return codeobj
2380 elif isinstance(codeobj, Macro):
2379 elif isinstance(codeobj, Macro):
2381 return codeobj.value
2380 return codeobj.value
2382
2381
2383 raise TypeError("%s is neither a string nor a macro." % target,
2382 raise TypeError("%s is neither a string nor a macro." % target,
2384 codeobj)
2383 codeobj)
2385
2384
2386 #-------------------------------------------------------------------------
2385 #-------------------------------------------------------------------------
2387 # Things related to IPython exiting
2386 # Things related to IPython exiting
2388 #-------------------------------------------------------------------------
2387 #-------------------------------------------------------------------------
2389 def atexit_operations(self):
2388 def atexit_operations(self):
2390 """This will be executed at the time of exit.
2389 """This will be executed at the time of exit.
2391
2390
2392 Cleanup operations and saving of persistent data that is done
2391 Cleanup operations and saving of persistent data that is done
2393 unconditionally by IPython should be performed here.
2392 unconditionally by IPython should be performed here.
2394
2393
2395 For things that may depend on startup flags or platform specifics (such
2394 For things that may depend on startup flags or platform specifics (such
2396 as having readline or not), register a separate atexit function in the
2395 as having readline or not), register a separate atexit function in the
2397 code that has the appropriate information, rather than trying to
2396 code that has the appropriate information, rather than trying to
2398 clutter
2397 clutter
2399 """
2398 """
2400 # Cleanup all tempfiles left around
2399 # Cleanup all tempfiles left around
2401 for tfile in self.tempfiles:
2400 for tfile in self.tempfiles:
2402 try:
2401 try:
2403 os.unlink(tfile)
2402 os.unlink(tfile)
2404 except OSError:
2403 except OSError:
2405 pass
2404 pass
2406
2405
2407 # Close the history session (this stores the end time and line count)
2406 # Close the history session (this stores the end time and line count)
2408 self.history_manager.end_session()
2407 self.history_manager.end_session()
2409
2408
2410 # Clear all user namespaces to release all references cleanly.
2409 # Clear all user namespaces to release all references cleanly.
2411 self.reset(new_session=False)
2410 self.reset(new_session=False)
2412
2411
2413 # Run user hooks
2412 # Run user hooks
2414 self.hooks.shutdown_hook()
2413 self.hooks.shutdown_hook()
2415
2414
2416 def cleanup(self):
2415 def cleanup(self):
2417 self.restore_sys_module_state()
2416 self.restore_sys_module_state()
2418
2417
2419
2418
2420 class InteractiveShellABC(object):
2419 class InteractiveShellABC(object):
2421 """An abstract base class for InteractiveShell."""
2420 """An abstract base class for InteractiveShell."""
2422 __metaclass__ = abc.ABCMeta
2421 __metaclass__ = abc.ABCMeta
2423
2422
2424 InteractiveShellABC.register(InteractiveShell)
2423 InteractiveShellABC.register(InteractiveShell)
@@ -1,60 +1,58 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 import re
10 import re
11 import sys
11 import sys
12
12
13 import IPython.utils.io
14
15 coding_declaration = re.compile(r"#\s*coding[:=]\s*([-\w.]+)")
13 coding_declaration = re.compile(r"#\s*coding[:=]\s*([-\w.]+)")
16
14
17 class Macro(object):
15 class Macro(object):
18 """Simple class to store the value of macros as strings.
16 """Simple class to store the value of macros as strings.
19
17
20 Macro is just a callable that executes a string of IPython
18 Macro is just a callable that executes a string of IPython
21 input when called.
19 input when called.
22
20
23 Args to macro are available in _margv list if you need them.
21 Args to macro are available in _margv list if you need them.
24 """
22 """
25
23
26 def __init__(self,code):
24 def __init__(self,code):
27 """store the macro value, as a single string which can be executed"""
25 """store the macro value, as a single string which can be executed"""
28 lines = []
26 lines = []
29 enc = None
27 enc = None
30 for line in code.splitlines():
28 for line in code.splitlines():
31 coding_match = coding_declaration.match(line)
29 coding_match = coding_declaration.match(line)
32 if coding_match:
30 if coding_match:
33 enc = coding_match.group(1)
31 enc = coding_match.group(1)
34 else:
32 else:
35 lines.append(line)
33 lines.append(line)
36 code = "\n".join(lines)
34 code = "\n".join(lines)
37 if isinstance(code, bytes):
35 if isinstance(code, bytes):
38 code = code.decode(enc or sys.getdefaultencoding())
36 code = code.decode(enc or sys.getdefaultencoding())
39 self.value = code + '\n'
37 self.value = code + '\n'
40
38
41 def __str__(self):
39 def __str__(self):
42 enc = sys.stdin.encoding or sys.getdefaultencoding()
40 enc = sys.stdin.encoding or sys.getdefaultencoding()
43 return self.value.encode(enc, "replace")
41 return self.value.encode(enc, "replace")
44
42
45 def __unicode__(self):
43 def __unicode__(self):
46 return self.value
44 return self.value
47
45
48 def __repr__(self):
46 def __repr__(self):
49 return 'IPython.macro.Macro(%s)' % repr(self.value)
47 return 'IPython.macro.Macro(%s)' % repr(self.value)
50
48
51 def __getstate__(self):
49 def __getstate__(self):
52 """ needed for safe pickling via %store """
50 """ needed for safe pickling via %store """
53 return {'value': self.value}
51 return {'value': self.value}
54
52
55 def __add__(self, other):
53 def __add__(self, other):
56 if isinstance(other, Macro):
54 if isinstance(other, Macro):
57 return Macro(self.value + other.value)
55 return Macro(self.value + other.value)
58 elif isinstance(other, basestring):
56 elif isinstance(other, basestring):
59 return Macro(self.value + other)
57 return Macro(self.value + other)
60 raise TypeError
58 raise TypeError
@@ -1,3470 +1,3469 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
9
9
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 import __builtin__
18 import __builtin__
19 import __future__
19 import __future__
20 import bdb
20 import bdb
21 import inspect
21 import inspect
22 import os
22 import os
23 import sys
23 import sys
24 import shutil
24 import shutil
25 import re
25 import re
26 import time
26 import time
27 import textwrap
27 import textwrap
28 from cStringIO import StringIO
28 from cStringIO import StringIO
29 from getopt import getopt,GetoptError
29 from getopt import getopt,GetoptError
30 from pprint import pformat
30 from pprint import pformat
31 from xmlrpclib import ServerProxy
31 from xmlrpclib import ServerProxy
32
32
33 # cProfile was added in Python2.5
33 # cProfile was added in Python2.5
34 try:
34 try:
35 import cProfile as profile
35 import cProfile as profile
36 import pstats
36 import pstats
37 except ImportError:
37 except ImportError:
38 # profile isn't bundled by default in Debian for license reasons
38 # profile isn't bundled by default in Debian for license reasons
39 try:
39 try:
40 import profile,pstats
40 import profile,pstats
41 except ImportError:
41 except ImportError:
42 profile = pstats = None
42 profile = pstats = None
43
43
44 import IPython
44 import IPython
45 from IPython.core import debugger, oinspect
45 from IPython.core import debugger, oinspect
46 from IPython.core.error import TryNext
46 from IPython.core.error import TryNext
47 from IPython.core.error import UsageError
47 from IPython.core.error import UsageError
48 from IPython.core.fakemodule import FakeModule
48 from IPython.core.fakemodule import FakeModule
49 from IPython.core.macro import Macro
49 from IPython.core.macro import Macro
50 from IPython.core import page
50 from IPython.core import page
51 from IPython.core.prefilter import ESC_MAGIC
51 from IPython.core.prefilter import ESC_MAGIC
52 from IPython.lib.pylabtools import mpl_runner
52 from IPython.lib.pylabtools import mpl_runner
53 from IPython.external.Itpl import itpl, printpl
53 from IPython.external.Itpl import itpl, printpl
54 from IPython.testing import decorators as testdec
54 from IPython.testing import decorators as testdec
55 from IPython.utils.io import file_read, nlprint
55 from IPython.utils.io import file_read, nlprint
56 import IPython.utils.io
57 from IPython.utils.path import get_py_filename
56 from IPython.utils.path import get_py_filename
58 from IPython.utils.process import arg_split, abbrev_cwd
57 from IPython.utils.process import arg_split, abbrev_cwd
59 from IPython.utils.terminal import set_term_title
58 from IPython.utils.terminal import set_term_title
60 from IPython.utils.text import LSString, SList, format_screen
59 from IPython.utils.text import LSString, SList, format_screen
61 from IPython.utils.timing import clock, clock2
60 from IPython.utils.timing import clock, clock2
62 from IPython.utils.warn import warn, error
61 from IPython.utils.warn import warn, error
63 from IPython.utils.ipstruct import Struct
62 from IPython.utils.ipstruct import Struct
64 import IPython.utils.generics
63 import IPython.utils.generics
65
64
66 #-----------------------------------------------------------------------------
65 #-----------------------------------------------------------------------------
67 # Utility functions
66 # Utility functions
68 #-----------------------------------------------------------------------------
67 #-----------------------------------------------------------------------------
69
68
70 def on_off(tag):
69 def on_off(tag):
71 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
70 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
72 return ['OFF','ON'][tag]
71 return ['OFF','ON'][tag]
73
72
74 class Bunch: pass
73 class Bunch: pass
75
74
76 def compress_dhist(dh):
75 def compress_dhist(dh):
77 head, tail = dh[:-10], dh[-10:]
76 head, tail = dh[:-10], dh[-10:]
78
77
79 newhead = []
78 newhead = []
80 done = set()
79 done = set()
81 for h in head:
80 for h in head:
82 if h in done:
81 if h in done:
83 continue
82 continue
84 newhead.append(h)
83 newhead.append(h)
85 done.add(h)
84 done.add(h)
86
85
87 return newhead + tail
86 return newhead + tail
88
87
89 def needs_local_scope(func):
88 def needs_local_scope(func):
90 """Decorator to mark magic functions which need to local scope to run."""
89 """Decorator to mark magic functions which need to local scope to run."""
91 func.needs_local_scope = True
90 func.needs_local_scope = True
92 return func
91 return func
93
92
94 #***************************************************************************
93 #***************************************************************************
95 # Main class implementing Magic functionality
94 # Main class implementing Magic functionality
96
95
97 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
96 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
98 # on construction of the main InteractiveShell object. Something odd is going
97 # on construction of the main InteractiveShell object. Something odd is going
99 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
98 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
100 # eventually this needs to be clarified.
99 # eventually this needs to be clarified.
101 # BG: This is because InteractiveShell inherits from this, but is itself a
100 # BG: This is because InteractiveShell inherits from this, but is itself a
102 # Configurable. This messes up the MRO in some way. The fix is that we need to
101 # Configurable. This messes up the MRO in some way. The fix is that we need to
103 # make Magic a configurable that InteractiveShell does not subclass.
102 # make Magic a configurable that InteractiveShell does not subclass.
104
103
105 class Magic:
104 class Magic:
106 """Magic functions for InteractiveShell.
105 """Magic functions for InteractiveShell.
107
106
108 Shell functions which can be reached as %function_name. All magic
107 Shell functions which can be reached as %function_name. All magic
109 functions should accept a string, which they can parse for their own
108 functions should accept a string, which they can parse for their own
110 needs. This can make some functions easier to type, eg `%cd ../`
109 needs. This can make some functions easier to type, eg `%cd ../`
111 vs. `%cd("../")`
110 vs. `%cd("../")`
112
111
113 ALL definitions MUST begin with the prefix magic_. The user won't need it
112 ALL definitions MUST begin with the prefix magic_. The user won't need it
114 at the command line, but it is is needed in the definition. """
113 at the command line, but it is is needed in the definition. """
115
114
116 # class globals
115 # class globals
117 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
116 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
118 'Automagic is ON, % prefix NOT needed for magic functions.']
117 'Automagic is ON, % prefix NOT needed for magic functions.']
119
118
120 #......................................................................
119 #......................................................................
121 # some utility functions
120 # some utility functions
122
121
123 def __init__(self,shell):
122 def __init__(self,shell):
124
123
125 self.options_table = {}
124 self.options_table = {}
126 if profile is None:
125 if profile is None:
127 self.magic_prun = self.profile_missing_notice
126 self.magic_prun = self.profile_missing_notice
128 self.shell = shell
127 self.shell = shell
129
128
130 # namespace for holding state we may need
129 # namespace for holding state we may need
131 self._magic_state = Bunch()
130 self._magic_state = Bunch()
132
131
133 def profile_missing_notice(self, *args, **kwargs):
132 def profile_missing_notice(self, *args, **kwargs):
134 error("""\
133 error("""\
135 The profile module could not be found. It has been removed from the standard
134 The profile module could not be found. It has been removed from the standard
136 python packages because of its non-free license. To use profiling, install the
135 python packages because of its non-free license. To use profiling, install the
137 python-profiler package from non-free.""")
136 python-profiler package from non-free.""")
138
137
139 def default_option(self,fn,optstr):
138 def default_option(self,fn,optstr):
140 """Make an entry in the options_table for fn, with value optstr"""
139 """Make an entry in the options_table for fn, with value optstr"""
141
140
142 if fn not in self.lsmagic():
141 if fn not in self.lsmagic():
143 error("%s is not a magic function" % fn)
142 error("%s is not a magic function" % fn)
144 self.options_table[fn] = optstr
143 self.options_table[fn] = optstr
145
144
146 def lsmagic(self):
145 def lsmagic(self):
147 """Return a list of currently available magic functions.
146 """Return a list of currently available magic functions.
148
147
149 Gives a list of the bare names after mangling (['ls','cd', ...], not
148 Gives a list of the bare names after mangling (['ls','cd', ...], not
150 ['magic_ls','magic_cd',...]"""
149 ['magic_ls','magic_cd',...]"""
151
150
152 # FIXME. This needs a cleanup, in the way the magics list is built.
151 # FIXME. This needs a cleanup, in the way the magics list is built.
153
152
154 # magics in class definition
153 # magics in class definition
155 class_magic = lambda fn: fn.startswith('magic_') and \
154 class_magic = lambda fn: fn.startswith('magic_') and \
156 callable(Magic.__dict__[fn])
155 callable(Magic.__dict__[fn])
157 # in instance namespace (run-time user additions)
156 # in instance namespace (run-time user additions)
158 inst_magic = lambda fn: fn.startswith('magic_') and \
157 inst_magic = lambda fn: fn.startswith('magic_') and \
159 callable(self.__dict__[fn])
158 callable(self.__dict__[fn])
160 # and bound magics by user (so they can access self):
159 # and bound magics by user (so they can access self):
161 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
160 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
162 callable(self.__class__.__dict__[fn])
161 callable(self.__class__.__dict__[fn])
163 magics = filter(class_magic,Magic.__dict__.keys()) + \
162 magics = filter(class_magic,Magic.__dict__.keys()) + \
164 filter(inst_magic,self.__dict__.keys()) + \
163 filter(inst_magic,self.__dict__.keys()) + \
165 filter(inst_bound_magic,self.__class__.__dict__.keys())
164 filter(inst_bound_magic,self.__class__.__dict__.keys())
166 out = []
165 out = []
167 for fn in set(magics):
166 for fn in set(magics):
168 out.append(fn.replace('magic_','',1))
167 out.append(fn.replace('magic_','',1))
169 out.sort()
168 out.sort()
170 return out
169 return out
171
170
172 def extract_input_lines(self, range_str, raw=False):
171 def extract_input_lines(self, range_str, raw=False):
173 """Return as a string a set of input history slices.
172 """Return as a string a set of input history slices.
174
173
175 Inputs:
174 Inputs:
176
175
177 - range_str: the set of slices is given as a string, like
176 - range_str: the set of slices is given as a string, like
178 "~5/6-~4/2 4:8 9", since this function is for use by magic functions
177 "~5/6-~4/2 4:8 9", since this function is for use by magic functions
179 which get their arguments as strings. The number before the / is the
178 which get their arguments as strings. The number before the / is the
180 session number: ~n goes n back from the current session.
179 session number: ~n goes n back from the current session.
181
180
182 Optional inputs:
181 Optional inputs:
183
182
184 - raw(False): by default, the processed input is used. If this is
183 - raw(False): by default, the processed input is used. If this is
185 true, the raw input history is used instead.
184 true, the raw input history is used instead.
186
185
187 Note that slices can be called with two notations:
186 Note that slices can be called with two notations:
188
187
189 N:M -> standard python form, means including items N...(M-1).
188 N:M -> standard python form, means including items N...(M-1).
190
189
191 N-M -> include items N..M (closed endpoint)."""
190 N-M -> include items N..M (closed endpoint)."""
192 lines = self.shell.history_manager.\
191 lines = self.shell.history_manager.\
193 get_range_by_str(range_str, raw=raw)
192 get_range_by_str(range_str, raw=raw)
194 return "\n".join(x for _, _, x in lines)
193 return "\n".join(x for _, _, x in lines)
195
194
196 def arg_err(self,func):
195 def arg_err(self,func):
197 """Print docstring if incorrect arguments were passed"""
196 """Print docstring if incorrect arguments were passed"""
198 print 'Error in arguments:'
197 print 'Error in arguments:'
199 print oinspect.getdoc(func)
198 print oinspect.getdoc(func)
200
199
201 def format_latex(self,strng):
200 def format_latex(self,strng):
202 """Format a string for latex inclusion."""
201 """Format a string for latex inclusion."""
203
202
204 # Characters that need to be escaped for latex:
203 # Characters that need to be escaped for latex:
205 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
204 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
206 # Magic command names as headers:
205 # Magic command names as headers:
207 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
206 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
208 re.MULTILINE)
207 re.MULTILINE)
209 # Magic commands
208 # Magic commands
210 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
209 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
211 re.MULTILINE)
210 re.MULTILINE)
212 # Paragraph continue
211 # Paragraph continue
213 par_re = re.compile(r'\\$',re.MULTILINE)
212 par_re = re.compile(r'\\$',re.MULTILINE)
214
213
215 # The "\n" symbol
214 # The "\n" symbol
216 newline_re = re.compile(r'\\n')
215 newline_re = re.compile(r'\\n')
217
216
218 # Now build the string for output:
217 # Now build the string for output:
219 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
218 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
220 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
219 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
221 strng)
220 strng)
222 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
221 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
223 strng = par_re.sub(r'\\\\',strng)
222 strng = par_re.sub(r'\\\\',strng)
224 strng = escape_re.sub(r'\\\1',strng)
223 strng = escape_re.sub(r'\\\1',strng)
225 strng = newline_re.sub(r'\\textbackslash{}n',strng)
224 strng = newline_re.sub(r'\\textbackslash{}n',strng)
226 return strng
225 return strng
227
226
228 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
227 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
229 """Parse options passed to an argument string.
228 """Parse options passed to an argument string.
230
229
231 The interface is similar to that of getopt(), but it returns back a
230 The interface is similar to that of getopt(), but it returns back a
232 Struct with the options as keys and the stripped argument string still
231 Struct with the options as keys and the stripped argument string still
233 as a string.
232 as a string.
234
233
235 arg_str is quoted as a true sys.argv vector by using shlex.split.
234 arg_str is quoted as a true sys.argv vector by using shlex.split.
236 This allows us to easily expand variables, glob files, quote
235 This allows us to easily expand variables, glob files, quote
237 arguments, etc.
236 arguments, etc.
238
237
239 Options:
238 Options:
240 -mode: default 'string'. If given as 'list', the argument string is
239 -mode: default 'string'. If given as 'list', the argument string is
241 returned as a list (split on whitespace) instead of a string.
240 returned as a list (split on whitespace) instead of a string.
242
241
243 -list_all: put all option values in lists. Normally only options
242 -list_all: put all option values in lists. Normally only options
244 appearing more than once are put in a list.
243 appearing more than once are put in a list.
245
244
246 -posix (True): whether to split the input line in POSIX mode or not,
245 -posix (True): whether to split the input line in POSIX mode or not,
247 as per the conventions outlined in the shlex module from the
246 as per the conventions outlined in the shlex module from the
248 standard library."""
247 standard library."""
249
248
250 # inject default options at the beginning of the input line
249 # inject default options at the beginning of the input line
251 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
250 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
252 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
251 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
253
252
254 mode = kw.get('mode','string')
253 mode = kw.get('mode','string')
255 if mode not in ['string','list']:
254 if mode not in ['string','list']:
256 raise ValueError,'incorrect mode given: %s' % mode
255 raise ValueError,'incorrect mode given: %s' % mode
257 # Get options
256 # Get options
258 list_all = kw.get('list_all',0)
257 list_all = kw.get('list_all',0)
259 posix = kw.get('posix', os.name == 'posix')
258 posix = kw.get('posix', os.name == 'posix')
260
259
261 # Check if we have more than one argument to warrant extra processing:
260 # Check if we have more than one argument to warrant extra processing:
262 odict = {} # Dictionary with options
261 odict = {} # Dictionary with options
263 args = arg_str.split()
262 args = arg_str.split()
264 if len(args) >= 1:
263 if len(args) >= 1:
265 # If the list of inputs only has 0 or 1 thing in it, there's no
264 # If the list of inputs only has 0 or 1 thing in it, there's no
266 # need to look for options
265 # need to look for options
267 argv = arg_split(arg_str,posix)
266 argv = arg_split(arg_str,posix)
268 # Do regular option processing
267 # Do regular option processing
269 try:
268 try:
270 opts,args = getopt(argv,opt_str,*long_opts)
269 opts,args = getopt(argv,opt_str,*long_opts)
271 except GetoptError,e:
270 except GetoptError,e:
272 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
271 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
273 " ".join(long_opts)))
272 " ".join(long_opts)))
274 for o,a in opts:
273 for o,a in opts:
275 if o.startswith('--'):
274 if o.startswith('--'):
276 o = o[2:]
275 o = o[2:]
277 else:
276 else:
278 o = o[1:]
277 o = o[1:]
279 try:
278 try:
280 odict[o].append(a)
279 odict[o].append(a)
281 except AttributeError:
280 except AttributeError:
282 odict[o] = [odict[o],a]
281 odict[o] = [odict[o],a]
283 except KeyError:
282 except KeyError:
284 if list_all:
283 if list_all:
285 odict[o] = [a]
284 odict[o] = [a]
286 else:
285 else:
287 odict[o] = a
286 odict[o] = a
288
287
289 # Prepare opts,args for return
288 # Prepare opts,args for return
290 opts = Struct(odict)
289 opts = Struct(odict)
291 if mode == 'string':
290 if mode == 'string':
292 args = ' '.join(args)
291 args = ' '.join(args)
293
292
294 return opts,args
293 return opts,args
295
294
296 #......................................................................
295 #......................................................................
297 # And now the actual magic functions
296 # And now the actual magic functions
298
297
299 # Functions for IPython shell work (vars,funcs, config, etc)
298 # Functions for IPython shell work (vars,funcs, config, etc)
300 def magic_lsmagic(self, parameter_s = ''):
299 def magic_lsmagic(self, parameter_s = ''):
301 """List currently available magic functions."""
300 """List currently available magic functions."""
302 mesc = ESC_MAGIC
301 mesc = ESC_MAGIC
303 print 'Available magic functions:\n'+mesc+\
302 print 'Available magic functions:\n'+mesc+\
304 (' '+mesc).join(self.lsmagic())
303 (' '+mesc).join(self.lsmagic())
305 print '\n' + Magic.auto_status[self.shell.automagic]
304 print '\n' + Magic.auto_status[self.shell.automagic]
306 return None
305 return None
307
306
308 def magic_magic(self, parameter_s = ''):
307 def magic_magic(self, parameter_s = ''):
309 """Print information about the magic function system.
308 """Print information about the magic function system.
310
309
311 Supported formats: -latex, -brief, -rest
310 Supported formats: -latex, -brief, -rest
312 """
311 """
313
312
314 mode = ''
313 mode = ''
315 try:
314 try:
316 if parameter_s.split()[0] == '-latex':
315 if parameter_s.split()[0] == '-latex':
317 mode = 'latex'
316 mode = 'latex'
318 if parameter_s.split()[0] == '-brief':
317 if parameter_s.split()[0] == '-brief':
319 mode = 'brief'
318 mode = 'brief'
320 if parameter_s.split()[0] == '-rest':
319 if parameter_s.split()[0] == '-rest':
321 mode = 'rest'
320 mode = 'rest'
322 rest_docs = []
321 rest_docs = []
323 except:
322 except:
324 pass
323 pass
325
324
326 magic_docs = []
325 magic_docs = []
327 for fname in self.lsmagic():
326 for fname in self.lsmagic():
328 mname = 'magic_' + fname
327 mname = 'magic_' + fname
329 for space in (Magic,self,self.__class__):
328 for space in (Magic,self,self.__class__):
330 try:
329 try:
331 fn = space.__dict__[mname]
330 fn = space.__dict__[mname]
332 except KeyError:
331 except KeyError:
333 pass
332 pass
334 else:
333 else:
335 break
334 break
336 if mode == 'brief':
335 if mode == 'brief':
337 # only first line
336 # only first line
338 if fn.__doc__:
337 if fn.__doc__:
339 fndoc = fn.__doc__.split('\n',1)[0]
338 fndoc = fn.__doc__.split('\n',1)[0]
340 else:
339 else:
341 fndoc = 'No documentation'
340 fndoc = 'No documentation'
342 else:
341 else:
343 if fn.__doc__:
342 if fn.__doc__:
344 fndoc = fn.__doc__.rstrip()
343 fndoc = fn.__doc__.rstrip()
345 else:
344 else:
346 fndoc = 'No documentation'
345 fndoc = 'No documentation'
347
346
348
347
349 if mode == 'rest':
348 if mode == 'rest':
350 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
349 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
351 fname,fndoc))
350 fname,fndoc))
352
351
353 else:
352 else:
354 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
353 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
355 fname,fndoc))
354 fname,fndoc))
356
355
357 magic_docs = ''.join(magic_docs)
356 magic_docs = ''.join(magic_docs)
358
357
359 if mode == 'rest':
358 if mode == 'rest':
360 return "".join(rest_docs)
359 return "".join(rest_docs)
361
360
362 if mode == 'latex':
361 if mode == 'latex':
363 print self.format_latex(magic_docs)
362 print self.format_latex(magic_docs)
364 return
363 return
365 else:
364 else:
366 magic_docs = format_screen(magic_docs)
365 magic_docs = format_screen(magic_docs)
367 if mode == 'brief':
366 if mode == 'brief':
368 return magic_docs
367 return magic_docs
369
368
370 outmsg = """
369 outmsg = """
371 IPython's 'magic' functions
370 IPython's 'magic' functions
372 ===========================
371 ===========================
373
372
374 The magic function system provides a series of functions which allow you to
373 The magic function system provides a series of functions which allow you to
375 control the behavior of IPython itself, plus a lot of system-type
374 control the behavior of IPython itself, plus a lot of system-type
376 features. All these functions are prefixed with a % character, but parameters
375 features. All these functions are prefixed with a % character, but parameters
377 are given without parentheses or quotes.
376 are given without parentheses or quotes.
378
377
379 NOTE: If you have 'automagic' enabled (via the command line option or with the
378 NOTE: If you have 'automagic' enabled (via the command line option or with the
380 %automagic function), you don't need to type in the % explicitly. By default,
379 %automagic function), you don't need to type in the % explicitly. By default,
381 IPython ships with automagic on, so you should only rarely need the % escape.
380 IPython ships with automagic on, so you should only rarely need the % escape.
382
381
383 Example: typing '%cd mydir' (without the quotes) changes you working directory
382 Example: typing '%cd mydir' (without the quotes) changes you working directory
384 to 'mydir', if it exists.
383 to 'mydir', if it exists.
385
384
386 You can define your own magic functions to extend the system. See the supplied
385 You can define your own magic functions to extend the system. See the supplied
387 ipythonrc and example-magic.py files for details (in your ipython
386 ipythonrc and example-magic.py files for details (in your ipython
388 configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere).
387 configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere).
389
388
390 You can also define your own aliased names for magic functions. In your
389 You can also define your own aliased names for magic functions. In your
391 ipythonrc file, placing a line like:
390 ipythonrc file, placing a line like:
392
391
393 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
392 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
394
393
395 will define %pf as a new name for %profile.
394 will define %pf as a new name for %profile.
396
395
397 You can also call magics in code using the magic() function, which IPython
396 You can also call magics in code using the magic() function, which IPython
398 automatically adds to the builtin namespace. Type 'magic?' for details.
397 automatically adds to the builtin namespace. Type 'magic?' for details.
399
398
400 For a list of the available magic functions, use %lsmagic. For a description
399 For a list of the available magic functions, use %lsmagic. For a description
401 of any of them, type %magic_name?, e.g. '%cd?'.
400 of any of them, type %magic_name?, e.g. '%cd?'.
402
401
403 Currently the magic system has the following functions:\n"""
402 Currently the magic system has the following functions:\n"""
404
403
405 mesc = ESC_MAGIC
404 mesc = ESC_MAGIC
406 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
405 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
407 "\n\n%s%s\n\n%s" % (outmsg,
406 "\n\n%s%s\n\n%s" % (outmsg,
408 magic_docs,mesc,mesc,
407 magic_docs,mesc,mesc,
409 (' '+mesc).join(self.lsmagic()),
408 (' '+mesc).join(self.lsmagic()),
410 Magic.auto_status[self.shell.automagic] ) )
409 Magic.auto_status[self.shell.automagic] ) )
411 page.page(outmsg)
410 page.page(outmsg)
412
411
413 def magic_automagic(self, parameter_s = ''):
412 def magic_automagic(self, parameter_s = ''):
414 """Make magic functions callable without having to type the initial %.
413 """Make magic functions callable without having to type the initial %.
415
414
416 Without argumentsl toggles on/off (when off, you must call it as
415 Without argumentsl toggles on/off (when off, you must call it as
417 %automagic, of course). With arguments it sets the value, and you can
416 %automagic, of course). With arguments it sets the value, and you can
418 use any of (case insensitive):
417 use any of (case insensitive):
419
418
420 - on,1,True: to activate
419 - on,1,True: to activate
421
420
422 - off,0,False: to deactivate.
421 - off,0,False: to deactivate.
423
422
424 Note that magic functions have lowest priority, so if there's a
423 Note that magic functions have lowest priority, so if there's a
425 variable whose name collides with that of a magic fn, automagic won't
424 variable whose name collides with that of a magic fn, automagic won't
426 work for that function (you get the variable instead). However, if you
425 work for that function (you get the variable instead). However, if you
427 delete the variable (del var), the previously shadowed magic function
426 delete the variable (del var), the previously shadowed magic function
428 becomes visible to automagic again."""
427 becomes visible to automagic again."""
429
428
430 arg = parameter_s.lower()
429 arg = parameter_s.lower()
431 if parameter_s in ('on','1','true'):
430 if parameter_s in ('on','1','true'):
432 self.shell.automagic = True
431 self.shell.automagic = True
433 elif parameter_s in ('off','0','false'):
432 elif parameter_s in ('off','0','false'):
434 self.shell.automagic = False
433 self.shell.automagic = False
435 else:
434 else:
436 self.shell.automagic = not self.shell.automagic
435 self.shell.automagic = not self.shell.automagic
437 print '\n' + Magic.auto_status[self.shell.automagic]
436 print '\n' + Magic.auto_status[self.shell.automagic]
438
437
439 @testdec.skip_doctest
438 @testdec.skip_doctest
440 def magic_autocall(self, parameter_s = ''):
439 def magic_autocall(self, parameter_s = ''):
441 """Make functions callable without having to type parentheses.
440 """Make functions callable without having to type parentheses.
442
441
443 Usage:
442 Usage:
444
443
445 %autocall [mode]
444 %autocall [mode]
446
445
447 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
446 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
448 value is toggled on and off (remembering the previous state).
447 value is toggled on and off (remembering the previous state).
449
448
450 In more detail, these values mean:
449 In more detail, these values mean:
451
450
452 0 -> fully disabled
451 0 -> fully disabled
453
452
454 1 -> active, but do not apply if there are no arguments on the line.
453 1 -> active, but do not apply if there are no arguments on the line.
455
454
456 In this mode, you get:
455 In this mode, you get:
457
456
458 In [1]: callable
457 In [1]: callable
459 Out[1]: <built-in function callable>
458 Out[1]: <built-in function callable>
460
459
461 In [2]: callable 'hello'
460 In [2]: callable 'hello'
462 ------> callable('hello')
461 ------> callable('hello')
463 Out[2]: False
462 Out[2]: False
464
463
465 2 -> Active always. Even if no arguments are present, the callable
464 2 -> Active always. Even if no arguments are present, the callable
466 object is called:
465 object is called:
467
466
468 In [2]: float
467 In [2]: float
469 ------> float()
468 ------> float()
470 Out[2]: 0.0
469 Out[2]: 0.0
471
470
472 Note that even with autocall off, you can still use '/' at the start of
471 Note that even with autocall off, you can still use '/' at the start of
473 a line to treat the first argument on the command line as a function
472 a line to treat the first argument on the command line as a function
474 and add parentheses to it:
473 and add parentheses to it:
475
474
476 In [8]: /str 43
475 In [8]: /str 43
477 ------> str(43)
476 ------> str(43)
478 Out[8]: '43'
477 Out[8]: '43'
479
478
480 # all-random (note for auto-testing)
479 # all-random (note for auto-testing)
481 """
480 """
482
481
483 if parameter_s:
482 if parameter_s:
484 arg = int(parameter_s)
483 arg = int(parameter_s)
485 else:
484 else:
486 arg = 'toggle'
485 arg = 'toggle'
487
486
488 if not arg in (0,1,2,'toggle'):
487 if not arg in (0,1,2,'toggle'):
489 error('Valid modes: (0->Off, 1->Smart, 2->Full')
488 error('Valid modes: (0->Off, 1->Smart, 2->Full')
490 return
489 return
491
490
492 if arg in (0,1,2):
491 if arg in (0,1,2):
493 self.shell.autocall = arg
492 self.shell.autocall = arg
494 else: # toggle
493 else: # toggle
495 if self.shell.autocall:
494 if self.shell.autocall:
496 self._magic_state.autocall_save = self.shell.autocall
495 self._magic_state.autocall_save = self.shell.autocall
497 self.shell.autocall = 0
496 self.shell.autocall = 0
498 else:
497 else:
499 try:
498 try:
500 self.shell.autocall = self._magic_state.autocall_save
499 self.shell.autocall = self._magic_state.autocall_save
501 except AttributeError:
500 except AttributeError:
502 self.shell.autocall = self._magic_state.autocall_save = 1
501 self.shell.autocall = self._magic_state.autocall_save = 1
503
502
504 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
503 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
505
504
506
505
507 def magic_page(self, parameter_s=''):
506 def magic_page(self, parameter_s=''):
508 """Pretty print the object and display it through a pager.
507 """Pretty print the object and display it through a pager.
509
508
510 %page [options] OBJECT
509 %page [options] OBJECT
511
510
512 If no object is given, use _ (last output).
511 If no object is given, use _ (last output).
513
512
514 Options:
513 Options:
515
514
516 -r: page str(object), don't pretty-print it."""
515 -r: page str(object), don't pretty-print it."""
517
516
518 # After a function contributed by Olivier Aubert, slightly modified.
517 # After a function contributed by Olivier Aubert, slightly modified.
519
518
520 # Process options/args
519 # Process options/args
521 opts,args = self.parse_options(parameter_s,'r')
520 opts,args = self.parse_options(parameter_s,'r')
522 raw = 'r' in opts
521 raw = 'r' in opts
523
522
524 oname = args and args or '_'
523 oname = args and args or '_'
525 info = self._ofind(oname)
524 info = self._ofind(oname)
526 if info['found']:
525 if info['found']:
527 txt = (raw and str or pformat)( info['obj'] )
526 txt = (raw and str or pformat)( info['obj'] )
528 page.page(txt)
527 page.page(txt)
529 else:
528 else:
530 print 'Object `%s` not found' % oname
529 print 'Object `%s` not found' % oname
531
530
532 def magic_profile(self, parameter_s=''):
531 def magic_profile(self, parameter_s=''):
533 """Print your currently active IPython profile."""
532 """Print your currently active IPython profile."""
534 if self.shell.profile:
533 if self.shell.profile:
535 printpl('Current IPython profile: $self.shell.profile.')
534 printpl('Current IPython profile: $self.shell.profile.')
536 else:
535 else:
537 print 'No profile active.'
536 print 'No profile active.'
538
537
539 def magic_pinfo(self, parameter_s='', namespaces=None):
538 def magic_pinfo(self, parameter_s='', namespaces=None):
540 """Provide detailed information about an object.
539 """Provide detailed information about an object.
541
540
542 '%pinfo object' is just a synonym for object? or ?object."""
541 '%pinfo object' is just a synonym for object? or ?object."""
543
542
544 #print 'pinfo par: <%s>' % parameter_s # dbg
543 #print 'pinfo par: <%s>' % parameter_s # dbg
545
544
546
545
547 # detail_level: 0 -> obj? , 1 -> obj??
546 # detail_level: 0 -> obj? , 1 -> obj??
548 detail_level = 0
547 detail_level = 0
549 # We need to detect if we got called as 'pinfo pinfo foo', which can
548 # We need to detect if we got called as 'pinfo pinfo foo', which can
550 # happen if the user types 'pinfo foo?' at the cmd line.
549 # happen if the user types 'pinfo foo?' at the cmd line.
551 pinfo,qmark1,oname,qmark2 = \
550 pinfo,qmark1,oname,qmark2 = \
552 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
551 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
553 if pinfo or qmark1 or qmark2:
552 if pinfo or qmark1 or qmark2:
554 detail_level = 1
553 detail_level = 1
555 if "*" in oname:
554 if "*" in oname:
556 self.magic_psearch(oname)
555 self.magic_psearch(oname)
557 else:
556 else:
558 self.shell._inspect('pinfo', oname, detail_level=detail_level,
557 self.shell._inspect('pinfo', oname, detail_level=detail_level,
559 namespaces=namespaces)
558 namespaces=namespaces)
560
559
561 def magic_pinfo2(self, parameter_s='', namespaces=None):
560 def magic_pinfo2(self, parameter_s='', namespaces=None):
562 """Provide extra detailed information about an object.
561 """Provide extra detailed information about an object.
563
562
564 '%pinfo2 object' is just a synonym for object?? or ??object."""
563 '%pinfo2 object' is just a synonym for object?? or ??object."""
565 self.shell._inspect('pinfo', parameter_s, detail_level=1,
564 self.shell._inspect('pinfo', parameter_s, detail_level=1,
566 namespaces=namespaces)
565 namespaces=namespaces)
567
566
568 @testdec.skip_doctest
567 @testdec.skip_doctest
569 def magic_pdef(self, parameter_s='', namespaces=None):
568 def magic_pdef(self, parameter_s='', namespaces=None):
570 """Print the definition header for any callable object.
569 """Print the definition header for any callable object.
571
570
572 If the object is a class, print the constructor information.
571 If the object is a class, print the constructor information.
573
572
574 Examples
573 Examples
575 --------
574 --------
576 ::
575 ::
577
576
578 In [3]: %pdef urllib.urlopen
577 In [3]: %pdef urllib.urlopen
579 urllib.urlopen(url, data=None, proxies=None)
578 urllib.urlopen(url, data=None, proxies=None)
580 """
579 """
581 self._inspect('pdef',parameter_s, namespaces)
580 self._inspect('pdef',parameter_s, namespaces)
582
581
583 def magic_pdoc(self, parameter_s='', namespaces=None):
582 def magic_pdoc(self, parameter_s='', namespaces=None):
584 """Print the docstring for an object.
583 """Print the docstring for an object.
585
584
586 If the given object is a class, it will print both the class and the
585 If the given object is a class, it will print both the class and the
587 constructor docstrings."""
586 constructor docstrings."""
588 self._inspect('pdoc',parameter_s, namespaces)
587 self._inspect('pdoc',parameter_s, namespaces)
589
588
590 def magic_psource(self, parameter_s='', namespaces=None):
589 def magic_psource(self, parameter_s='', namespaces=None):
591 """Print (or run through pager) the source code for an object."""
590 """Print (or run through pager) the source code for an object."""
592 self._inspect('psource',parameter_s, namespaces)
591 self._inspect('psource',parameter_s, namespaces)
593
592
594 def magic_pfile(self, parameter_s=''):
593 def magic_pfile(self, parameter_s=''):
595 """Print (or run through pager) the file where an object is defined.
594 """Print (or run through pager) the file where an object is defined.
596
595
597 The file opens at the line where the object definition begins. IPython
596 The file opens at the line where the object definition begins. IPython
598 will honor the environment variable PAGER if set, and otherwise will
597 will honor the environment variable PAGER if set, and otherwise will
599 do its best to print the file in a convenient form.
598 do its best to print the file in a convenient form.
600
599
601 If the given argument is not an object currently defined, IPython will
600 If the given argument is not an object currently defined, IPython will
602 try to interpret it as a filename (automatically adding a .py extension
601 try to interpret it as a filename (automatically adding a .py extension
603 if needed). You can thus use %pfile as a syntax highlighting code
602 if needed). You can thus use %pfile as a syntax highlighting code
604 viewer."""
603 viewer."""
605
604
606 # first interpret argument as an object name
605 # first interpret argument as an object name
607 out = self._inspect('pfile',parameter_s)
606 out = self._inspect('pfile',parameter_s)
608 # if not, try the input as a filename
607 # if not, try the input as a filename
609 if out == 'not found':
608 if out == 'not found':
610 try:
609 try:
611 filename = get_py_filename(parameter_s)
610 filename = get_py_filename(parameter_s)
612 except IOError,msg:
611 except IOError,msg:
613 print msg
612 print msg
614 return
613 return
615 page.page(self.shell.inspector.format(file(filename).read()))
614 page.page(self.shell.inspector.format(file(filename).read()))
616
615
617 def magic_psearch(self, parameter_s=''):
616 def magic_psearch(self, parameter_s=''):
618 """Search for object in namespaces by wildcard.
617 """Search for object in namespaces by wildcard.
619
618
620 %psearch [options] PATTERN [OBJECT TYPE]
619 %psearch [options] PATTERN [OBJECT TYPE]
621
620
622 Note: ? can be used as a synonym for %psearch, at the beginning or at
621 Note: ? can be used as a synonym for %psearch, at the beginning or at
623 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
622 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
624 rest of the command line must be unchanged (options come first), so
623 rest of the command line must be unchanged (options come first), so
625 for example the following forms are equivalent
624 for example the following forms are equivalent
626
625
627 %psearch -i a* function
626 %psearch -i a* function
628 -i a* function?
627 -i a* function?
629 ?-i a* function
628 ?-i a* function
630
629
631 Arguments:
630 Arguments:
632
631
633 PATTERN
632 PATTERN
634
633
635 where PATTERN is a string containing * as a wildcard similar to its
634 where PATTERN is a string containing * as a wildcard similar to its
636 use in a shell. The pattern is matched in all namespaces on the
635 use in a shell. The pattern is matched in all namespaces on the
637 search path. By default objects starting with a single _ are not
636 search path. By default objects starting with a single _ are not
638 matched, many IPython generated objects have a single
637 matched, many IPython generated objects have a single
639 underscore. The default is case insensitive matching. Matching is
638 underscore. The default is case insensitive matching. Matching is
640 also done on the attributes of objects and not only on the objects
639 also done on the attributes of objects and not only on the objects
641 in a module.
640 in a module.
642
641
643 [OBJECT TYPE]
642 [OBJECT TYPE]
644
643
645 Is the name of a python type from the types module. The name is
644 Is the name of a python type from the types module. The name is
646 given in lowercase without the ending type, ex. StringType is
645 given in lowercase without the ending type, ex. StringType is
647 written string. By adding a type here only objects matching the
646 written string. By adding a type here only objects matching the
648 given type are matched. Using all here makes the pattern match all
647 given type are matched. Using all here makes the pattern match all
649 types (this is the default).
648 types (this is the default).
650
649
651 Options:
650 Options:
652
651
653 -a: makes the pattern match even objects whose names start with a
652 -a: makes the pattern match even objects whose names start with a
654 single underscore. These names are normally ommitted from the
653 single underscore. These names are normally ommitted from the
655 search.
654 search.
656
655
657 -i/-c: make the pattern case insensitive/sensitive. If neither of
656 -i/-c: make the pattern case insensitive/sensitive. If neither of
658 these options is given, the default is read from your ipythonrc
657 these options is given, the default is read from your ipythonrc
659 file. The option name which sets this value is
658 file. The option name which sets this value is
660 'wildcards_case_sensitive'. If this option is not specified in your
659 'wildcards_case_sensitive'. If this option is not specified in your
661 ipythonrc file, IPython's internal default is to do a case sensitive
660 ipythonrc file, IPython's internal default is to do a case sensitive
662 search.
661 search.
663
662
664 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
663 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
665 specifiy can be searched in any of the following namespaces:
664 specifiy can be searched in any of the following namespaces:
666 'builtin', 'user', 'user_global','internal', 'alias', where
665 'builtin', 'user', 'user_global','internal', 'alias', where
667 'builtin' and 'user' are the search defaults. Note that you should
666 'builtin' and 'user' are the search defaults. Note that you should
668 not use quotes when specifying namespaces.
667 not use quotes when specifying namespaces.
669
668
670 'Builtin' contains the python module builtin, 'user' contains all
669 'Builtin' contains the python module builtin, 'user' contains all
671 user data, 'alias' only contain the shell aliases and no python
670 user data, 'alias' only contain the shell aliases and no python
672 objects, 'internal' contains objects used by IPython. The
671 objects, 'internal' contains objects used by IPython. The
673 'user_global' namespace is only used by embedded IPython instances,
672 'user_global' namespace is only used by embedded IPython instances,
674 and it contains module-level globals. You can add namespaces to the
673 and it contains module-level globals. You can add namespaces to the
675 search with -s or exclude them with -e (these options can be given
674 search with -s or exclude them with -e (these options can be given
676 more than once).
675 more than once).
677
676
678 Examples:
677 Examples:
679
678
680 %psearch a* -> objects beginning with an a
679 %psearch a* -> objects beginning with an a
681 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
680 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
682 %psearch a* function -> all functions beginning with an a
681 %psearch a* function -> all functions beginning with an a
683 %psearch re.e* -> objects beginning with an e in module re
682 %psearch re.e* -> objects beginning with an e in module re
684 %psearch r*.e* -> objects that start with e in modules starting in r
683 %psearch r*.e* -> objects that start with e in modules starting in r
685 %psearch r*.* string -> all strings in modules beginning with r
684 %psearch r*.* string -> all strings in modules beginning with r
686
685
687 Case sensitve search:
686 Case sensitve search:
688
687
689 %psearch -c a* list all object beginning with lower case a
688 %psearch -c a* list all object beginning with lower case a
690
689
691 Show objects beginning with a single _:
690 Show objects beginning with a single _:
692
691
693 %psearch -a _* list objects beginning with a single underscore"""
692 %psearch -a _* list objects beginning with a single underscore"""
694 try:
693 try:
695 parameter_s = parameter_s.encode('ascii')
694 parameter_s = parameter_s.encode('ascii')
696 except UnicodeEncodeError:
695 except UnicodeEncodeError:
697 print 'Python identifiers can only contain ascii characters.'
696 print 'Python identifiers can only contain ascii characters.'
698 return
697 return
699
698
700 # default namespaces to be searched
699 # default namespaces to be searched
701 def_search = ['user','builtin']
700 def_search = ['user','builtin']
702
701
703 # Process options/args
702 # Process options/args
704 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
703 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
705 opt = opts.get
704 opt = opts.get
706 shell = self.shell
705 shell = self.shell
707 psearch = shell.inspector.psearch
706 psearch = shell.inspector.psearch
708
707
709 # select case options
708 # select case options
710 if opts.has_key('i'):
709 if opts.has_key('i'):
711 ignore_case = True
710 ignore_case = True
712 elif opts.has_key('c'):
711 elif opts.has_key('c'):
713 ignore_case = False
712 ignore_case = False
714 else:
713 else:
715 ignore_case = not shell.wildcards_case_sensitive
714 ignore_case = not shell.wildcards_case_sensitive
716
715
717 # Build list of namespaces to search from user options
716 # Build list of namespaces to search from user options
718 def_search.extend(opt('s',[]))
717 def_search.extend(opt('s',[]))
719 ns_exclude = ns_exclude=opt('e',[])
718 ns_exclude = ns_exclude=opt('e',[])
720 ns_search = [nm for nm in def_search if nm not in ns_exclude]
719 ns_search = [nm for nm in def_search if nm not in ns_exclude]
721
720
722 # Call the actual search
721 # Call the actual search
723 try:
722 try:
724 psearch(args,shell.ns_table,ns_search,
723 psearch(args,shell.ns_table,ns_search,
725 show_all=opt('a'),ignore_case=ignore_case)
724 show_all=opt('a'),ignore_case=ignore_case)
726 except:
725 except:
727 shell.showtraceback()
726 shell.showtraceback()
728
727
729 @testdec.skip_doctest
728 @testdec.skip_doctest
730 def magic_who_ls(self, parameter_s=''):
729 def magic_who_ls(self, parameter_s=''):
731 """Return a sorted list of all interactive variables.
730 """Return a sorted list of all interactive variables.
732
731
733 If arguments are given, only variables of types matching these
732 If arguments are given, only variables of types matching these
734 arguments are returned.
733 arguments are returned.
735
734
736 Examples
735 Examples
737 --------
736 --------
738
737
739 Define two variables and list them with who_ls::
738 Define two variables and list them with who_ls::
740
739
741 In [1]: alpha = 123
740 In [1]: alpha = 123
742
741
743 In [2]: beta = 'test'
742 In [2]: beta = 'test'
744
743
745 In [3]: %who_ls
744 In [3]: %who_ls
746 Out[3]: ['alpha', 'beta']
745 Out[3]: ['alpha', 'beta']
747
746
748 In [4]: %who_ls int
747 In [4]: %who_ls int
749 Out[4]: ['alpha']
748 Out[4]: ['alpha']
750
749
751 In [5]: %who_ls str
750 In [5]: %who_ls str
752 Out[5]: ['beta']
751 Out[5]: ['beta']
753 """
752 """
754
753
755 user_ns = self.shell.user_ns
754 user_ns = self.shell.user_ns
756 internal_ns = self.shell.internal_ns
755 internal_ns = self.shell.internal_ns
757 user_ns_hidden = self.shell.user_ns_hidden
756 user_ns_hidden = self.shell.user_ns_hidden
758 out = [ i for i in user_ns
757 out = [ i for i in user_ns
759 if not i.startswith('_') \
758 if not i.startswith('_') \
760 and not (i in internal_ns or i in user_ns_hidden) ]
759 and not (i in internal_ns or i in user_ns_hidden) ]
761
760
762 typelist = parameter_s.split()
761 typelist = parameter_s.split()
763 if typelist:
762 if typelist:
764 typeset = set(typelist)
763 typeset = set(typelist)
765 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
764 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
766
765
767 out.sort()
766 out.sort()
768 return out
767 return out
769
768
770 @testdec.skip_doctest
769 @testdec.skip_doctest
771 def magic_who(self, parameter_s=''):
770 def magic_who(self, parameter_s=''):
772 """Print all interactive variables, with some minimal formatting.
771 """Print all interactive variables, with some minimal formatting.
773
772
774 If any arguments are given, only variables whose type matches one of
773 If any arguments are given, only variables whose type matches one of
775 these are printed. For example:
774 these are printed. For example:
776
775
777 %who function str
776 %who function str
778
777
779 will only list functions and strings, excluding all other types of
778 will only list functions and strings, excluding all other types of
780 variables. To find the proper type names, simply use type(var) at a
779 variables. To find the proper type names, simply use type(var) at a
781 command line to see how python prints type names. For example:
780 command line to see how python prints type names. For example:
782
781
783 In [1]: type('hello')\\
782 In [1]: type('hello')\\
784 Out[1]: <type 'str'>
783 Out[1]: <type 'str'>
785
784
786 indicates that the type name for strings is 'str'.
785 indicates that the type name for strings is 'str'.
787
786
788 %who always excludes executed names loaded through your configuration
787 %who always excludes executed names loaded through your configuration
789 file and things which are internal to IPython.
788 file and things which are internal to IPython.
790
789
791 This is deliberate, as typically you may load many modules and the
790 This is deliberate, as typically you may load many modules and the
792 purpose of %who is to show you only what you've manually defined.
791 purpose of %who is to show you only what you've manually defined.
793
792
794 Examples
793 Examples
795 --------
794 --------
796
795
797 Define two variables and list them with who::
796 Define two variables and list them with who::
798
797
799 In [1]: alpha = 123
798 In [1]: alpha = 123
800
799
801 In [2]: beta = 'test'
800 In [2]: beta = 'test'
802
801
803 In [3]: %who
802 In [3]: %who
804 alpha beta
803 alpha beta
805
804
806 In [4]: %who int
805 In [4]: %who int
807 alpha
806 alpha
808
807
809 In [5]: %who str
808 In [5]: %who str
810 beta
809 beta
811 """
810 """
812
811
813 varlist = self.magic_who_ls(parameter_s)
812 varlist = self.magic_who_ls(parameter_s)
814 if not varlist:
813 if not varlist:
815 if parameter_s:
814 if parameter_s:
816 print 'No variables match your requested type.'
815 print 'No variables match your requested type.'
817 else:
816 else:
818 print 'Interactive namespace is empty.'
817 print 'Interactive namespace is empty.'
819 return
818 return
820
819
821 # if we have variables, move on...
820 # if we have variables, move on...
822 count = 0
821 count = 0
823 for i in varlist:
822 for i in varlist:
824 print i+'\t',
823 print i+'\t',
825 count += 1
824 count += 1
826 if count > 8:
825 if count > 8:
827 count = 0
826 count = 0
828 print
827 print
829 print
828 print
830
829
831 @testdec.skip_doctest
830 @testdec.skip_doctest
832 def magic_whos(self, parameter_s=''):
831 def magic_whos(self, parameter_s=''):
833 """Like %who, but gives some extra information about each variable.
832 """Like %who, but gives some extra information about each variable.
834
833
835 The same type filtering of %who can be applied here.
834 The same type filtering of %who can be applied here.
836
835
837 For all variables, the type is printed. Additionally it prints:
836 For all variables, the type is printed. Additionally it prints:
838
837
839 - For {},[],(): their length.
838 - For {},[],(): their length.
840
839
841 - For numpy arrays, a summary with shape, number of
840 - For numpy arrays, a summary with shape, number of
842 elements, typecode and size in memory.
841 elements, typecode and size in memory.
843
842
844 - Everything else: a string representation, snipping their middle if
843 - Everything else: a string representation, snipping their middle if
845 too long.
844 too long.
846
845
847 Examples
846 Examples
848 --------
847 --------
849
848
850 Define two variables and list them with whos::
849 Define two variables and list them with whos::
851
850
852 In [1]: alpha = 123
851 In [1]: alpha = 123
853
852
854 In [2]: beta = 'test'
853 In [2]: beta = 'test'
855
854
856 In [3]: %whos
855 In [3]: %whos
857 Variable Type Data/Info
856 Variable Type Data/Info
858 --------------------------------
857 --------------------------------
859 alpha int 123
858 alpha int 123
860 beta str test
859 beta str test
861 """
860 """
862
861
863 varnames = self.magic_who_ls(parameter_s)
862 varnames = self.magic_who_ls(parameter_s)
864 if not varnames:
863 if not varnames:
865 if parameter_s:
864 if parameter_s:
866 print 'No variables match your requested type.'
865 print 'No variables match your requested type.'
867 else:
866 else:
868 print 'Interactive namespace is empty.'
867 print 'Interactive namespace is empty.'
869 return
868 return
870
869
871 # if we have variables, move on...
870 # if we have variables, move on...
872
871
873 # for these types, show len() instead of data:
872 # for these types, show len() instead of data:
874 seq_types = ['dict', 'list', 'tuple']
873 seq_types = ['dict', 'list', 'tuple']
875
874
876 # for numpy/Numeric arrays, display summary info
875 # for numpy/Numeric arrays, display summary info
877 try:
876 try:
878 import numpy
877 import numpy
879 except ImportError:
878 except ImportError:
880 ndarray_type = None
879 ndarray_type = None
881 else:
880 else:
882 ndarray_type = numpy.ndarray.__name__
881 ndarray_type = numpy.ndarray.__name__
883 try:
882 try:
884 import Numeric
883 import Numeric
885 except ImportError:
884 except ImportError:
886 array_type = None
885 array_type = None
887 else:
886 else:
888 array_type = Numeric.ArrayType.__name__
887 array_type = Numeric.ArrayType.__name__
889
888
890 # Find all variable names and types so we can figure out column sizes
889 # Find all variable names and types so we can figure out column sizes
891 def get_vars(i):
890 def get_vars(i):
892 return self.shell.user_ns[i]
891 return self.shell.user_ns[i]
893
892
894 # some types are well known and can be shorter
893 # some types are well known and can be shorter
895 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
894 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
896 def type_name(v):
895 def type_name(v):
897 tn = type(v).__name__
896 tn = type(v).__name__
898 return abbrevs.get(tn,tn)
897 return abbrevs.get(tn,tn)
899
898
900 varlist = map(get_vars,varnames)
899 varlist = map(get_vars,varnames)
901
900
902 typelist = []
901 typelist = []
903 for vv in varlist:
902 for vv in varlist:
904 tt = type_name(vv)
903 tt = type_name(vv)
905
904
906 if tt=='instance':
905 if tt=='instance':
907 typelist.append( abbrevs.get(str(vv.__class__),
906 typelist.append( abbrevs.get(str(vv.__class__),
908 str(vv.__class__)))
907 str(vv.__class__)))
909 else:
908 else:
910 typelist.append(tt)
909 typelist.append(tt)
911
910
912 # column labels and # of spaces as separator
911 # column labels and # of spaces as separator
913 varlabel = 'Variable'
912 varlabel = 'Variable'
914 typelabel = 'Type'
913 typelabel = 'Type'
915 datalabel = 'Data/Info'
914 datalabel = 'Data/Info'
916 colsep = 3
915 colsep = 3
917 # variable format strings
916 # variable format strings
918 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
917 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
919 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
918 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
920 aformat = "%s: %s elems, type `%s`, %s bytes"
919 aformat = "%s: %s elems, type `%s`, %s bytes"
921 # find the size of the columns to format the output nicely
920 # find the size of the columns to format the output nicely
922 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
921 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
923 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
922 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
924 # table header
923 # table header
925 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
924 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
926 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
925 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
927 # and the table itself
926 # and the table itself
928 kb = 1024
927 kb = 1024
929 Mb = 1048576 # kb**2
928 Mb = 1048576 # kb**2
930 for vname,var,vtype in zip(varnames,varlist,typelist):
929 for vname,var,vtype in zip(varnames,varlist,typelist):
931 print itpl(vformat),
930 print itpl(vformat),
932 if vtype in seq_types:
931 if vtype in seq_types:
933 print "n="+str(len(var))
932 print "n="+str(len(var))
934 elif vtype in [array_type,ndarray_type]:
933 elif vtype in [array_type,ndarray_type]:
935 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
934 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
936 if vtype==ndarray_type:
935 if vtype==ndarray_type:
937 # numpy
936 # numpy
938 vsize = var.size
937 vsize = var.size
939 vbytes = vsize*var.itemsize
938 vbytes = vsize*var.itemsize
940 vdtype = var.dtype
939 vdtype = var.dtype
941 else:
940 else:
942 # Numeric
941 # Numeric
943 vsize = Numeric.size(var)
942 vsize = Numeric.size(var)
944 vbytes = vsize*var.itemsize()
943 vbytes = vsize*var.itemsize()
945 vdtype = var.typecode()
944 vdtype = var.typecode()
946
945
947 if vbytes < 100000:
946 if vbytes < 100000:
948 print aformat % (vshape,vsize,vdtype,vbytes)
947 print aformat % (vshape,vsize,vdtype,vbytes)
949 else:
948 else:
950 print aformat % (vshape,vsize,vdtype,vbytes),
949 print aformat % (vshape,vsize,vdtype,vbytes),
951 if vbytes < Mb:
950 if vbytes < Mb:
952 print '(%s kb)' % (vbytes/kb,)
951 print '(%s kb)' % (vbytes/kb,)
953 else:
952 else:
954 print '(%s Mb)' % (vbytes/Mb,)
953 print '(%s Mb)' % (vbytes/Mb,)
955 else:
954 else:
956 try:
955 try:
957 vstr = str(var)
956 vstr = str(var)
958 except UnicodeEncodeError:
957 except UnicodeEncodeError:
959 vstr = unicode(var).encode(sys.getdefaultencoding(),
958 vstr = unicode(var).encode(sys.getdefaultencoding(),
960 'backslashreplace')
959 'backslashreplace')
961 vstr = vstr.replace('\n','\\n')
960 vstr = vstr.replace('\n','\\n')
962 if len(vstr) < 50:
961 if len(vstr) < 50:
963 print vstr
962 print vstr
964 else:
963 else:
965 printpl(vfmt_short)
964 printpl(vfmt_short)
966
965
967 def magic_reset(self, parameter_s=''):
966 def magic_reset(self, parameter_s=''):
968 """Resets the namespace by removing all names defined by the user.
967 """Resets the namespace by removing all names defined by the user.
969
968
970 Parameters
969 Parameters
971 ----------
970 ----------
972 -f : force reset without asking for confirmation.
971 -f : force reset without asking for confirmation.
973
972
974 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
973 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
975 References to objects may be kept. By default (without this option),
974 References to objects may be kept. By default (without this option),
976 we do a 'hard' reset, giving you a new session and removing all
975 we do a 'hard' reset, giving you a new session and removing all
977 references to objects from the current session.
976 references to objects from the current session.
978
977
979 Examples
978 Examples
980 --------
979 --------
981 In [6]: a = 1
980 In [6]: a = 1
982
981
983 In [7]: a
982 In [7]: a
984 Out[7]: 1
983 Out[7]: 1
985
984
986 In [8]: 'a' in _ip.user_ns
985 In [8]: 'a' in _ip.user_ns
987 Out[8]: True
986 Out[8]: True
988
987
989 In [9]: %reset -f
988 In [9]: %reset -f
990
989
991 In [1]: 'a' in _ip.user_ns
990 In [1]: 'a' in _ip.user_ns
992 Out[1]: False
991 Out[1]: False
993 """
992 """
994 opts, args = self.parse_options(parameter_s,'sf')
993 opts, args = self.parse_options(parameter_s,'sf')
995 if 'f' in opts:
994 if 'f' in opts:
996 ans = True
995 ans = True
997 else:
996 else:
998 ans = self.shell.ask_yes_no(
997 ans = self.shell.ask_yes_no(
999 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
998 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1000 if not ans:
999 if not ans:
1001 print 'Nothing done.'
1000 print 'Nothing done.'
1002 return
1001 return
1003
1002
1004 if 's' in opts: # Soft reset
1003 if 's' in opts: # Soft reset
1005 user_ns = self.shell.user_ns
1004 user_ns = self.shell.user_ns
1006 for i in self.magic_who_ls():
1005 for i in self.magic_who_ls():
1007 del(user_ns[i])
1006 del(user_ns[i])
1008
1007
1009 else: # Hard reset
1008 else: # Hard reset
1010 self.shell.reset(new_session = False)
1009 self.shell.reset(new_session = False)
1011
1010
1012
1011
1013
1012
1014 def magic_reset_selective(self, parameter_s=''):
1013 def magic_reset_selective(self, parameter_s=''):
1015 """Resets the namespace by removing names defined by the user.
1014 """Resets the namespace by removing names defined by the user.
1016
1015
1017 Input/Output history are left around in case you need them.
1016 Input/Output history are left around in case you need them.
1018
1017
1019 %reset_selective [-f] regex
1018 %reset_selective [-f] regex
1020
1019
1021 No action is taken if regex is not included
1020 No action is taken if regex is not included
1022
1021
1023 Options
1022 Options
1024 -f : force reset without asking for confirmation.
1023 -f : force reset without asking for confirmation.
1025
1024
1026 Examples
1025 Examples
1027 --------
1026 --------
1028
1027
1029 We first fully reset the namespace so your output looks identical to
1028 We first fully reset the namespace so your output looks identical to
1030 this example for pedagogical reasons; in practice you do not need a
1029 this example for pedagogical reasons; in practice you do not need a
1031 full reset.
1030 full reset.
1032
1031
1033 In [1]: %reset -f
1032 In [1]: %reset -f
1034
1033
1035 Now, with a clean namespace we can make a few variables and use
1034 Now, with a clean namespace we can make a few variables and use
1036 %reset_selective to only delete names that match our regexp:
1035 %reset_selective to only delete names that match our regexp:
1037
1036
1038 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1037 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1039
1038
1040 In [3]: who_ls
1039 In [3]: who_ls
1041 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1040 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1042
1041
1043 In [4]: %reset_selective -f b[2-3]m
1042 In [4]: %reset_selective -f b[2-3]m
1044
1043
1045 In [5]: who_ls
1044 In [5]: who_ls
1046 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1045 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1047
1046
1048 In [6]: %reset_selective -f d
1047 In [6]: %reset_selective -f d
1049
1048
1050 In [7]: who_ls
1049 In [7]: who_ls
1051 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1050 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1052
1051
1053 In [8]: %reset_selective -f c
1052 In [8]: %reset_selective -f c
1054
1053
1055 In [9]: who_ls
1054 In [9]: who_ls
1056 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1055 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1057
1056
1058 In [10]: %reset_selective -f b
1057 In [10]: %reset_selective -f b
1059
1058
1060 In [11]: who_ls
1059 In [11]: who_ls
1061 Out[11]: ['a']
1060 Out[11]: ['a']
1062 """
1061 """
1063
1062
1064 opts, regex = self.parse_options(parameter_s,'f')
1063 opts, regex = self.parse_options(parameter_s,'f')
1065
1064
1066 if opts.has_key('f'):
1065 if opts.has_key('f'):
1067 ans = True
1066 ans = True
1068 else:
1067 else:
1069 ans = self.shell.ask_yes_no(
1068 ans = self.shell.ask_yes_no(
1070 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1069 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1071 if not ans:
1070 if not ans:
1072 print 'Nothing done.'
1071 print 'Nothing done.'
1073 return
1072 return
1074 user_ns = self.shell.user_ns
1073 user_ns = self.shell.user_ns
1075 if not regex:
1074 if not regex:
1076 print 'No regex pattern specified. Nothing done.'
1075 print 'No regex pattern specified. Nothing done.'
1077 return
1076 return
1078 else:
1077 else:
1079 try:
1078 try:
1080 m = re.compile(regex)
1079 m = re.compile(regex)
1081 except TypeError:
1080 except TypeError:
1082 raise TypeError('regex must be a string or compiled pattern')
1081 raise TypeError('regex must be a string or compiled pattern')
1083 for i in self.magic_who_ls():
1082 for i in self.magic_who_ls():
1084 if m.search(i):
1083 if m.search(i):
1085 del(user_ns[i])
1084 del(user_ns[i])
1086
1085
1087 def magic_logstart(self,parameter_s=''):
1086 def magic_logstart(self,parameter_s=''):
1088 """Start logging anywhere in a session.
1087 """Start logging anywhere in a session.
1089
1088
1090 %logstart [-o|-r|-t] [log_name [log_mode]]
1089 %logstart [-o|-r|-t] [log_name [log_mode]]
1091
1090
1092 If no name is given, it defaults to a file named 'ipython_log.py' in your
1091 If no name is given, it defaults to a file named 'ipython_log.py' in your
1093 current directory, in 'rotate' mode (see below).
1092 current directory, in 'rotate' mode (see below).
1094
1093
1095 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1094 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1096 history up to that point and then continues logging.
1095 history up to that point and then continues logging.
1097
1096
1098 %logstart takes a second optional parameter: logging mode. This can be one
1097 %logstart takes a second optional parameter: logging mode. This can be one
1099 of (note that the modes are given unquoted):\\
1098 of (note that the modes are given unquoted):\\
1100 append: well, that says it.\\
1099 append: well, that says it.\\
1101 backup: rename (if exists) to name~ and start name.\\
1100 backup: rename (if exists) to name~ and start name.\\
1102 global: single logfile in your home dir, appended to.\\
1101 global: single logfile in your home dir, appended to.\\
1103 over : overwrite existing log.\\
1102 over : overwrite existing log.\\
1104 rotate: create rotating logs name.1~, name.2~, etc.
1103 rotate: create rotating logs name.1~, name.2~, etc.
1105
1104
1106 Options:
1105 Options:
1107
1106
1108 -o: log also IPython's output. In this mode, all commands which
1107 -o: log also IPython's output. In this mode, all commands which
1109 generate an Out[NN] prompt are recorded to the logfile, right after
1108 generate an Out[NN] prompt are recorded to the logfile, right after
1110 their corresponding input line. The output lines are always
1109 their corresponding input line. The output lines are always
1111 prepended with a '#[Out]# ' marker, so that the log remains valid
1110 prepended with a '#[Out]# ' marker, so that the log remains valid
1112 Python code.
1111 Python code.
1113
1112
1114 Since this marker is always the same, filtering only the output from
1113 Since this marker is always the same, filtering only the output from
1115 a log is very easy, using for example a simple awk call:
1114 a log is very easy, using for example a simple awk call:
1116
1115
1117 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1116 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1118
1117
1119 -r: log 'raw' input. Normally, IPython's logs contain the processed
1118 -r: log 'raw' input. Normally, IPython's logs contain the processed
1120 input, so that user lines are logged in their final form, converted
1119 input, so that user lines are logged in their final form, converted
1121 into valid Python. For example, %Exit is logged as
1120 into valid Python. For example, %Exit is logged as
1122 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1121 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1123 exactly as typed, with no transformations applied.
1122 exactly as typed, with no transformations applied.
1124
1123
1125 -t: put timestamps before each input line logged (these are put in
1124 -t: put timestamps before each input line logged (these are put in
1126 comments)."""
1125 comments)."""
1127
1126
1128 opts,par = self.parse_options(parameter_s,'ort')
1127 opts,par = self.parse_options(parameter_s,'ort')
1129 log_output = 'o' in opts
1128 log_output = 'o' in opts
1130 log_raw_input = 'r' in opts
1129 log_raw_input = 'r' in opts
1131 timestamp = 't' in opts
1130 timestamp = 't' in opts
1132
1131
1133 logger = self.shell.logger
1132 logger = self.shell.logger
1134
1133
1135 # if no args are given, the defaults set in the logger constructor by
1134 # if no args are given, the defaults set in the logger constructor by
1136 # ipytohn remain valid
1135 # ipytohn remain valid
1137 if par:
1136 if par:
1138 try:
1137 try:
1139 logfname,logmode = par.split()
1138 logfname,logmode = par.split()
1140 except:
1139 except:
1141 logfname = par
1140 logfname = par
1142 logmode = 'backup'
1141 logmode = 'backup'
1143 else:
1142 else:
1144 logfname = logger.logfname
1143 logfname = logger.logfname
1145 logmode = logger.logmode
1144 logmode = logger.logmode
1146 # put logfname into rc struct as if it had been called on the command
1145 # put logfname into rc struct as if it had been called on the command
1147 # line, so it ends up saved in the log header Save it in case we need
1146 # line, so it ends up saved in the log header Save it in case we need
1148 # to restore it...
1147 # to restore it...
1149 old_logfile = self.shell.logfile
1148 old_logfile = self.shell.logfile
1150 if logfname:
1149 if logfname:
1151 logfname = os.path.expanduser(logfname)
1150 logfname = os.path.expanduser(logfname)
1152 self.shell.logfile = logfname
1151 self.shell.logfile = logfname
1153
1152
1154 loghead = '# IPython log file\n\n'
1153 loghead = '# IPython log file\n\n'
1155 try:
1154 try:
1156 started = logger.logstart(logfname,loghead,logmode,
1155 started = logger.logstart(logfname,loghead,logmode,
1157 log_output,timestamp,log_raw_input)
1156 log_output,timestamp,log_raw_input)
1158 except:
1157 except:
1159 self.shell.logfile = old_logfile
1158 self.shell.logfile = old_logfile
1160 warn("Couldn't start log: %s" % sys.exc_info()[1])
1159 warn("Couldn't start log: %s" % sys.exc_info()[1])
1161 else:
1160 else:
1162 # log input history up to this point, optionally interleaving
1161 # log input history up to this point, optionally interleaving
1163 # output if requested
1162 # output if requested
1164
1163
1165 if timestamp:
1164 if timestamp:
1166 # disable timestamping for the previous history, since we've
1165 # disable timestamping for the previous history, since we've
1167 # lost those already (no time machine here).
1166 # lost those already (no time machine here).
1168 logger.timestamp = False
1167 logger.timestamp = False
1169
1168
1170 if log_raw_input:
1169 if log_raw_input:
1171 input_hist = self.shell.history_manager.input_hist_raw
1170 input_hist = self.shell.history_manager.input_hist_raw
1172 else:
1171 else:
1173 input_hist = self.shell.history_manager.input_hist_parsed
1172 input_hist = self.shell.history_manager.input_hist_parsed
1174
1173
1175 if log_output:
1174 if log_output:
1176 log_write = logger.log_write
1175 log_write = logger.log_write
1177 output_hist = self.shell.history_manager.output_hist
1176 output_hist = self.shell.history_manager.output_hist
1178 for n in range(1,len(input_hist)-1):
1177 for n in range(1,len(input_hist)-1):
1179 log_write(input_hist[n].rstrip())
1178 log_write(input_hist[n].rstrip())
1180 if n in output_hist:
1179 if n in output_hist:
1181 log_write(repr(output_hist[n]),'output')
1180 log_write(repr(output_hist[n]),'output')
1182 else:
1181 else:
1183 logger.log_write(''.join(input_hist[1:]))
1182 logger.log_write(''.join(input_hist[1:]))
1184 if timestamp:
1183 if timestamp:
1185 # re-enable timestamping
1184 # re-enable timestamping
1186 logger.timestamp = True
1185 logger.timestamp = True
1187
1186
1188 print ('Activating auto-logging. '
1187 print ('Activating auto-logging. '
1189 'Current session state plus future input saved.')
1188 'Current session state plus future input saved.')
1190 logger.logstate()
1189 logger.logstate()
1191
1190
1192 def magic_logstop(self,parameter_s=''):
1191 def magic_logstop(self,parameter_s=''):
1193 """Fully stop logging and close log file.
1192 """Fully stop logging and close log file.
1194
1193
1195 In order to start logging again, a new %logstart call needs to be made,
1194 In order to start logging again, a new %logstart call needs to be made,
1196 possibly (though not necessarily) with a new filename, mode and other
1195 possibly (though not necessarily) with a new filename, mode and other
1197 options."""
1196 options."""
1198 self.logger.logstop()
1197 self.logger.logstop()
1199
1198
1200 def magic_logoff(self,parameter_s=''):
1199 def magic_logoff(self,parameter_s=''):
1201 """Temporarily stop logging.
1200 """Temporarily stop logging.
1202
1201
1203 You must have previously started logging."""
1202 You must have previously started logging."""
1204 self.shell.logger.switch_log(0)
1203 self.shell.logger.switch_log(0)
1205
1204
1206 def magic_logon(self,parameter_s=''):
1205 def magic_logon(self,parameter_s=''):
1207 """Restart logging.
1206 """Restart logging.
1208
1207
1209 This function is for restarting logging which you've temporarily
1208 This function is for restarting logging which you've temporarily
1210 stopped with %logoff. For starting logging for the first time, you
1209 stopped with %logoff. For starting logging for the first time, you
1211 must use the %logstart function, which allows you to specify an
1210 must use the %logstart function, which allows you to specify an
1212 optional log filename."""
1211 optional log filename."""
1213
1212
1214 self.shell.logger.switch_log(1)
1213 self.shell.logger.switch_log(1)
1215
1214
1216 def magic_logstate(self,parameter_s=''):
1215 def magic_logstate(self,parameter_s=''):
1217 """Print the status of the logging system."""
1216 """Print the status of the logging system."""
1218
1217
1219 self.shell.logger.logstate()
1218 self.shell.logger.logstate()
1220
1219
1221 def magic_pdb(self, parameter_s=''):
1220 def magic_pdb(self, parameter_s=''):
1222 """Control the automatic calling of the pdb interactive debugger.
1221 """Control the automatic calling of the pdb interactive debugger.
1223
1222
1224 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1223 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1225 argument it works as a toggle.
1224 argument it works as a toggle.
1226
1225
1227 When an exception is triggered, IPython can optionally call the
1226 When an exception is triggered, IPython can optionally call the
1228 interactive pdb debugger after the traceback printout. %pdb toggles
1227 interactive pdb debugger after the traceback printout. %pdb toggles
1229 this feature on and off.
1228 this feature on and off.
1230
1229
1231 The initial state of this feature is set in your ipythonrc
1230 The initial state of this feature is set in your ipythonrc
1232 configuration file (the variable is called 'pdb').
1231 configuration file (the variable is called 'pdb').
1233
1232
1234 If you want to just activate the debugger AFTER an exception has fired,
1233 If you want to just activate the debugger AFTER an exception has fired,
1235 without having to type '%pdb on' and rerunning your code, you can use
1234 without having to type '%pdb on' and rerunning your code, you can use
1236 the %debug magic."""
1235 the %debug magic."""
1237
1236
1238 par = parameter_s.strip().lower()
1237 par = parameter_s.strip().lower()
1239
1238
1240 if par:
1239 if par:
1241 try:
1240 try:
1242 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1241 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1243 except KeyError:
1242 except KeyError:
1244 print ('Incorrect argument. Use on/1, off/0, '
1243 print ('Incorrect argument. Use on/1, off/0, '
1245 'or nothing for a toggle.')
1244 'or nothing for a toggle.')
1246 return
1245 return
1247 else:
1246 else:
1248 # toggle
1247 # toggle
1249 new_pdb = not self.shell.call_pdb
1248 new_pdb = not self.shell.call_pdb
1250
1249
1251 # set on the shell
1250 # set on the shell
1252 self.shell.call_pdb = new_pdb
1251 self.shell.call_pdb = new_pdb
1253 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1252 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1254
1253
1255 def magic_debug(self, parameter_s=''):
1254 def magic_debug(self, parameter_s=''):
1256 """Activate the interactive debugger in post-mortem mode.
1255 """Activate the interactive debugger in post-mortem mode.
1257
1256
1258 If an exception has just occurred, this lets you inspect its stack
1257 If an exception has just occurred, this lets you inspect its stack
1259 frames interactively. Note that this will always work only on the last
1258 frames interactively. Note that this will always work only on the last
1260 traceback that occurred, so you must call this quickly after an
1259 traceback that occurred, so you must call this quickly after an
1261 exception that you wish to inspect has fired, because if another one
1260 exception that you wish to inspect has fired, because if another one
1262 occurs, it clobbers the previous one.
1261 occurs, it clobbers the previous one.
1263
1262
1264 If you want IPython to automatically do this on every exception, see
1263 If you want IPython to automatically do this on every exception, see
1265 the %pdb magic for more details.
1264 the %pdb magic for more details.
1266 """
1265 """
1267 self.shell.debugger(force=True)
1266 self.shell.debugger(force=True)
1268
1267
1269 @testdec.skip_doctest
1268 @testdec.skip_doctest
1270 def magic_prun(self, parameter_s ='',user_mode=1,
1269 def magic_prun(self, parameter_s ='',user_mode=1,
1271 opts=None,arg_lst=None,prog_ns=None):
1270 opts=None,arg_lst=None,prog_ns=None):
1272
1271
1273 """Run a statement through the python code profiler.
1272 """Run a statement through the python code profiler.
1274
1273
1275 Usage:
1274 Usage:
1276 %prun [options] statement
1275 %prun [options] statement
1277
1276
1278 The given statement (which doesn't require quote marks) is run via the
1277 The given statement (which doesn't require quote marks) is run via the
1279 python profiler in a manner similar to the profile.run() function.
1278 python profiler in a manner similar to the profile.run() function.
1280 Namespaces are internally managed to work correctly; profile.run
1279 Namespaces are internally managed to work correctly; profile.run
1281 cannot be used in IPython because it makes certain assumptions about
1280 cannot be used in IPython because it makes certain assumptions about
1282 namespaces which do not hold under IPython.
1281 namespaces which do not hold under IPython.
1283
1282
1284 Options:
1283 Options:
1285
1284
1286 -l <limit>: you can place restrictions on what or how much of the
1285 -l <limit>: you can place restrictions on what or how much of the
1287 profile gets printed. The limit value can be:
1286 profile gets printed. The limit value can be:
1288
1287
1289 * A string: only information for function names containing this string
1288 * A string: only information for function names containing this string
1290 is printed.
1289 is printed.
1291
1290
1292 * An integer: only these many lines are printed.
1291 * An integer: only these many lines are printed.
1293
1292
1294 * A float (between 0 and 1): this fraction of the report is printed
1293 * A float (between 0 and 1): this fraction of the report is printed
1295 (for example, use a limit of 0.4 to see the topmost 40% only).
1294 (for example, use a limit of 0.4 to see the topmost 40% only).
1296
1295
1297 You can combine several limits with repeated use of the option. For
1296 You can combine several limits with repeated use of the option. For
1298 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1297 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1299 information about class constructors.
1298 information about class constructors.
1300
1299
1301 -r: return the pstats.Stats object generated by the profiling. This
1300 -r: return the pstats.Stats object generated by the profiling. This
1302 object has all the information about the profile in it, and you can
1301 object has all the information about the profile in it, and you can
1303 later use it for further analysis or in other functions.
1302 later use it for further analysis or in other functions.
1304
1303
1305 -s <key>: sort profile by given key. You can provide more than one key
1304 -s <key>: sort profile by given key. You can provide more than one key
1306 by using the option several times: '-s key1 -s key2 -s key3...'. The
1305 by using the option several times: '-s key1 -s key2 -s key3...'. The
1307 default sorting key is 'time'.
1306 default sorting key is 'time'.
1308
1307
1309 The following is copied verbatim from the profile documentation
1308 The following is copied verbatim from the profile documentation
1310 referenced below:
1309 referenced below:
1311
1310
1312 When more than one key is provided, additional keys are used as
1311 When more than one key is provided, additional keys are used as
1313 secondary criteria when the there is equality in all keys selected
1312 secondary criteria when the there is equality in all keys selected
1314 before them.
1313 before them.
1315
1314
1316 Abbreviations can be used for any key names, as long as the
1315 Abbreviations can be used for any key names, as long as the
1317 abbreviation is unambiguous. The following are the keys currently
1316 abbreviation is unambiguous. The following are the keys currently
1318 defined:
1317 defined:
1319
1318
1320 Valid Arg Meaning
1319 Valid Arg Meaning
1321 "calls" call count
1320 "calls" call count
1322 "cumulative" cumulative time
1321 "cumulative" cumulative time
1323 "file" file name
1322 "file" file name
1324 "module" file name
1323 "module" file name
1325 "pcalls" primitive call count
1324 "pcalls" primitive call count
1326 "line" line number
1325 "line" line number
1327 "name" function name
1326 "name" function name
1328 "nfl" name/file/line
1327 "nfl" name/file/line
1329 "stdname" standard name
1328 "stdname" standard name
1330 "time" internal time
1329 "time" internal time
1331
1330
1332 Note that all sorts on statistics are in descending order (placing
1331 Note that all sorts on statistics are in descending order (placing
1333 most time consuming items first), where as name, file, and line number
1332 most time consuming items first), where as name, file, and line number
1334 searches are in ascending order (i.e., alphabetical). The subtle
1333 searches are in ascending order (i.e., alphabetical). The subtle
1335 distinction between "nfl" and "stdname" is that the standard name is a
1334 distinction between "nfl" and "stdname" is that the standard name is a
1336 sort of the name as printed, which means that the embedded line
1335 sort of the name as printed, which means that the embedded line
1337 numbers get compared in an odd way. For example, lines 3, 20, and 40
1336 numbers get compared in an odd way. For example, lines 3, 20, and 40
1338 would (if the file names were the same) appear in the string order
1337 would (if the file names were the same) appear in the string order
1339 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1338 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1340 line numbers. In fact, sort_stats("nfl") is the same as
1339 line numbers. In fact, sort_stats("nfl") is the same as
1341 sort_stats("name", "file", "line").
1340 sort_stats("name", "file", "line").
1342
1341
1343 -T <filename>: save profile results as shown on screen to a text
1342 -T <filename>: save profile results as shown on screen to a text
1344 file. The profile is still shown on screen.
1343 file. The profile is still shown on screen.
1345
1344
1346 -D <filename>: save (via dump_stats) profile statistics to given
1345 -D <filename>: save (via dump_stats) profile statistics to given
1347 filename. This data is in a format understod by the pstats module, and
1346 filename. This data is in a format understod by the pstats module, and
1348 is generated by a call to the dump_stats() method of profile
1347 is generated by a call to the dump_stats() method of profile
1349 objects. The profile is still shown on screen.
1348 objects. The profile is still shown on screen.
1350
1349
1351 If you want to run complete programs under the profiler's control, use
1350 If you want to run complete programs under the profiler's control, use
1352 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1351 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1353 contains profiler specific options as described here.
1352 contains profiler specific options as described here.
1354
1353
1355 You can read the complete documentation for the profile module with::
1354 You can read the complete documentation for the profile module with::
1356
1355
1357 In [1]: import profile; profile.help()
1356 In [1]: import profile; profile.help()
1358 """
1357 """
1359
1358
1360 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1359 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1361 # protect user quote marks
1360 # protect user quote marks
1362 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1361 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1363
1362
1364 if user_mode: # regular user call
1363 if user_mode: # regular user call
1365 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1364 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1366 list_all=1)
1365 list_all=1)
1367 namespace = self.shell.user_ns
1366 namespace = self.shell.user_ns
1368 else: # called to run a program by %run -p
1367 else: # called to run a program by %run -p
1369 try:
1368 try:
1370 filename = get_py_filename(arg_lst[0])
1369 filename = get_py_filename(arg_lst[0])
1371 except IOError,msg:
1370 except IOError,msg:
1372 error(msg)
1371 error(msg)
1373 return
1372 return
1374
1373
1375 arg_str = 'execfile(filename,prog_ns)'
1374 arg_str = 'execfile(filename,prog_ns)'
1376 namespace = locals()
1375 namespace = locals()
1377
1376
1378 opts.merge(opts_def)
1377 opts.merge(opts_def)
1379
1378
1380 prof = profile.Profile()
1379 prof = profile.Profile()
1381 try:
1380 try:
1382 prof = prof.runctx(arg_str,namespace,namespace)
1381 prof = prof.runctx(arg_str,namespace,namespace)
1383 sys_exit = ''
1382 sys_exit = ''
1384 except SystemExit:
1383 except SystemExit:
1385 sys_exit = """*** SystemExit exception caught in code being profiled."""
1384 sys_exit = """*** SystemExit exception caught in code being profiled."""
1386
1385
1387 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1386 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1388
1387
1389 lims = opts.l
1388 lims = opts.l
1390 if lims:
1389 if lims:
1391 lims = [] # rebuild lims with ints/floats/strings
1390 lims = [] # rebuild lims with ints/floats/strings
1392 for lim in opts.l:
1391 for lim in opts.l:
1393 try:
1392 try:
1394 lims.append(int(lim))
1393 lims.append(int(lim))
1395 except ValueError:
1394 except ValueError:
1396 try:
1395 try:
1397 lims.append(float(lim))
1396 lims.append(float(lim))
1398 except ValueError:
1397 except ValueError:
1399 lims.append(lim)
1398 lims.append(lim)
1400
1399
1401 # Trap output.
1400 # Trap output.
1402 stdout_trap = StringIO()
1401 stdout_trap = StringIO()
1403
1402
1404 if hasattr(stats,'stream'):
1403 if hasattr(stats,'stream'):
1405 # In newer versions of python, the stats object has a 'stream'
1404 # In newer versions of python, the stats object has a 'stream'
1406 # attribute to write into.
1405 # attribute to write into.
1407 stats.stream = stdout_trap
1406 stats.stream = stdout_trap
1408 stats.print_stats(*lims)
1407 stats.print_stats(*lims)
1409 else:
1408 else:
1410 # For older versions, we manually redirect stdout during printing
1409 # For older versions, we manually redirect stdout during printing
1411 sys_stdout = sys.stdout
1410 sys_stdout = sys.stdout
1412 try:
1411 try:
1413 sys.stdout = stdout_trap
1412 sys.stdout = stdout_trap
1414 stats.print_stats(*lims)
1413 stats.print_stats(*lims)
1415 finally:
1414 finally:
1416 sys.stdout = sys_stdout
1415 sys.stdout = sys_stdout
1417
1416
1418 output = stdout_trap.getvalue()
1417 output = stdout_trap.getvalue()
1419 output = output.rstrip()
1418 output = output.rstrip()
1420
1419
1421 page.page(output)
1420 page.page(output)
1422 print sys_exit,
1421 print sys_exit,
1423
1422
1424 dump_file = opts.D[0]
1423 dump_file = opts.D[0]
1425 text_file = opts.T[0]
1424 text_file = opts.T[0]
1426 if dump_file:
1425 if dump_file:
1427 prof.dump_stats(dump_file)
1426 prof.dump_stats(dump_file)
1428 print '\n*** Profile stats marshalled to file',\
1427 print '\n*** Profile stats marshalled to file',\
1429 `dump_file`+'.',sys_exit
1428 `dump_file`+'.',sys_exit
1430 if text_file:
1429 if text_file:
1431 pfile = file(text_file,'w')
1430 pfile = file(text_file,'w')
1432 pfile.write(output)
1431 pfile.write(output)
1433 pfile.close()
1432 pfile.close()
1434 print '\n*** Profile printout saved to text file',\
1433 print '\n*** Profile printout saved to text file',\
1435 `text_file`+'.',sys_exit
1434 `text_file`+'.',sys_exit
1436
1435
1437 if opts.has_key('r'):
1436 if opts.has_key('r'):
1438 return stats
1437 return stats
1439 else:
1438 else:
1440 return None
1439 return None
1441
1440
1442 @testdec.skip_doctest
1441 @testdec.skip_doctest
1443 def magic_run(self, parameter_s ='',runner=None,
1442 def magic_run(self, parameter_s ='',runner=None,
1444 file_finder=get_py_filename):
1443 file_finder=get_py_filename):
1445 """Run the named file inside IPython as a program.
1444 """Run the named file inside IPython as a program.
1446
1445
1447 Usage:\\
1446 Usage:\\
1448 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1447 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1449
1448
1450 Parameters after the filename are passed as command-line arguments to
1449 Parameters after the filename are passed as command-line arguments to
1451 the program (put in sys.argv). Then, control returns to IPython's
1450 the program (put in sys.argv). Then, control returns to IPython's
1452 prompt.
1451 prompt.
1453
1452
1454 This is similar to running at a system prompt:\\
1453 This is similar to running at a system prompt:\\
1455 $ python file args\\
1454 $ python file args\\
1456 but with the advantage of giving you IPython's tracebacks, and of
1455 but with the advantage of giving you IPython's tracebacks, and of
1457 loading all variables into your interactive namespace for further use
1456 loading all variables into your interactive namespace for further use
1458 (unless -p is used, see below).
1457 (unless -p is used, see below).
1459
1458
1460 The file is executed in a namespace initially consisting only of
1459 The file is executed in a namespace initially consisting only of
1461 __name__=='__main__' and sys.argv constructed as indicated. It thus
1460 __name__=='__main__' and sys.argv constructed as indicated. It thus
1462 sees its environment as if it were being run as a stand-alone program
1461 sees its environment as if it were being run as a stand-alone program
1463 (except for sharing global objects such as previously imported
1462 (except for sharing global objects such as previously imported
1464 modules). But after execution, the IPython interactive namespace gets
1463 modules). But after execution, the IPython interactive namespace gets
1465 updated with all variables defined in the program (except for __name__
1464 updated with all variables defined in the program (except for __name__
1466 and sys.argv). This allows for very convenient loading of code for
1465 and sys.argv). This allows for very convenient loading of code for
1467 interactive work, while giving each program a 'clean sheet' to run in.
1466 interactive work, while giving each program a 'clean sheet' to run in.
1468
1467
1469 Options:
1468 Options:
1470
1469
1471 -n: __name__ is NOT set to '__main__', but to the running file's name
1470 -n: __name__ is NOT set to '__main__', but to the running file's name
1472 without extension (as python does under import). This allows running
1471 without extension (as python does under import). This allows running
1473 scripts and reloading the definitions in them without calling code
1472 scripts and reloading the definitions in them without calling code
1474 protected by an ' if __name__ == "__main__" ' clause.
1473 protected by an ' if __name__ == "__main__" ' clause.
1475
1474
1476 -i: run the file in IPython's namespace instead of an empty one. This
1475 -i: run the file in IPython's namespace instead of an empty one. This
1477 is useful if you are experimenting with code written in a text editor
1476 is useful if you are experimenting with code written in a text editor
1478 which depends on variables defined interactively.
1477 which depends on variables defined interactively.
1479
1478
1480 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1479 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1481 being run. This is particularly useful if IPython is being used to
1480 being run. This is particularly useful if IPython is being used to
1482 run unittests, which always exit with a sys.exit() call. In such
1481 run unittests, which always exit with a sys.exit() call. In such
1483 cases you are interested in the output of the test results, not in
1482 cases you are interested in the output of the test results, not in
1484 seeing a traceback of the unittest module.
1483 seeing a traceback of the unittest module.
1485
1484
1486 -t: print timing information at the end of the run. IPython will give
1485 -t: print timing information at the end of the run. IPython will give
1487 you an estimated CPU time consumption for your script, which under
1486 you an estimated CPU time consumption for your script, which under
1488 Unix uses the resource module to avoid the wraparound problems of
1487 Unix uses the resource module to avoid the wraparound problems of
1489 time.clock(). Under Unix, an estimate of time spent on system tasks
1488 time.clock(). Under Unix, an estimate of time spent on system tasks
1490 is also given (for Windows platforms this is reported as 0.0).
1489 is also given (for Windows platforms this is reported as 0.0).
1491
1490
1492 If -t is given, an additional -N<N> option can be given, where <N>
1491 If -t is given, an additional -N<N> option can be given, where <N>
1493 must be an integer indicating how many times you want the script to
1492 must be an integer indicating how many times you want the script to
1494 run. The final timing report will include total and per run results.
1493 run. The final timing report will include total and per run results.
1495
1494
1496 For example (testing the script uniq_stable.py):
1495 For example (testing the script uniq_stable.py):
1497
1496
1498 In [1]: run -t uniq_stable
1497 In [1]: run -t uniq_stable
1499
1498
1500 IPython CPU timings (estimated):\\
1499 IPython CPU timings (estimated):\\
1501 User : 0.19597 s.\\
1500 User : 0.19597 s.\\
1502 System: 0.0 s.\\
1501 System: 0.0 s.\\
1503
1502
1504 In [2]: run -t -N5 uniq_stable
1503 In [2]: run -t -N5 uniq_stable
1505
1504
1506 IPython CPU timings (estimated):\\
1505 IPython CPU timings (estimated):\\
1507 Total runs performed: 5\\
1506 Total runs performed: 5\\
1508 Times : Total Per run\\
1507 Times : Total Per run\\
1509 User : 0.910862 s, 0.1821724 s.\\
1508 User : 0.910862 s, 0.1821724 s.\\
1510 System: 0.0 s, 0.0 s.
1509 System: 0.0 s, 0.0 s.
1511
1510
1512 -d: run your program under the control of pdb, the Python debugger.
1511 -d: run your program under the control of pdb, the Python debugger.
1513 This allows you to execute your program step by step, watch variables,
1512 This allows you to execute your program step by step, watch variables,
1514 etc. Internally, what IPython does is similar to calling:
1513 etc. Internally, what IPython does is similar to calling:
1515
1514
1516 pdb.run('execfile("YOURFILENAME")')
1515 pdb.run('execfile("YOURFILENAME")')
1517
1516
1518 with a breakpoint set on line 1 of your file. You can change the line
1517 with a breakpoint set on line 1 of your file. You can change the line
1519 number for this automatic breakpoint to be <N> by using the -bN option
1518 number for this automatic breakpoint to be <N> by using the -bN option
1520 (where N must be an integer). For example:
1519 (where N must be an integer). For example:
1521
1520
1522 %run -d -b40 myscript
1521 %run -d -b40 myscript
1523
1522
1524 will set the first breakpoint at line 40 in myscript.py. Note that
1523 will set the first breakpoint at line 40 in myscript.py. Note that
1525 the first breakpoint must be set on a line which actually does
1524 the first breakpoint must be set on a line which actually does
1526 something (not a comment or docstring) for it to stop execution.
1525 something (not a comment or docstring) for it to stop execution.
1527
1526
1528 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1527 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1529 first enter 'c' (without qoutes) to start execution up to the first
1528 first enter 'c' (without qoutes) to start execution up to the first
1530 breakpoint.
1529 breakpoint.
1531
1530
1532 Entering 'help' gives information about the use of the debugger. You
1531 Entering 'help' gives information about the use of the debugger. You
1533 can easily see pdb's full documentation with "import pdb;pdb.help()"
1532 can easily see pdb's full documentation with "import pdb;pdb.help()"
1534 at a prompt.
1533 at a prompt.
1535
1534
1536 -p: run program under the control of the Python profiler module (which
1535 -p: run program under the control of the Python profiler module (which
1537 prints a detailed report of execution times, function calls, etc).
1536 prints a detailed report of execution times, function calls, etc).
1538
1537
1539 You can pass other options after -p which affect the behavior of the
1538 You can pass other options after -p which affect the behavior of the
1540 profiler itself. See the docs for %prun for details.
1539 profiler itself. See the docs for %prun for details.
1541
1540
1542 In this mode, the program's variables do NOT propagate back to the
1541 In this mode, the program's variables do NOT propagate back to the
1543 IPython interactive namespace (because they remain in the namespace
1542 IPython interactive namespace (because they remain in the namespace
1544 where the profiler executes them).
1543 where the profiler executes them).
1545
1544
1546 Internally this triggers a call to %prun, see its documentation for
1545 Internally this triggers a call to %prun, see its documentation for
1547 details on the options available specifically for profiling.
1546 details on the options available specifically for profiling.
1548
1547
1549 There is one special usage for which the text above doesn't apply:
1548 There is one special usage for which the text above doesn't apply:
1550 if the filename ends with .ipy, the file is run as ipython script,
1549 if the filename ends with .ipy, the file is run as ipython script,
1551 just as if the commands were written on IPython prompt.
1550 just as if the commands were written on IPython prompt.
1552 """
1551 """
1553
1552
1554 # get arguments and set sys.argv for program to be run.
1553 # get arguments and set sys.argv for program to be run.
1555 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1554 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1556 mode='list',list_all=1)
1555 mode='list',list_all=1)
1557
1556
1558 try:
1557 try:
1559 filename = file_finder(arg_lst[0])
1558 filename = file_finder(arg_lst[0])
1560 except IndexError:
1559 except IndexError:
1561 warn('you must provide at least a filename.')
1560 warn('you must provide at least a filename.')
1562 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1561 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1563 return
1562 return
1564 except IOError,msg:
1563 except IOError,msg:
1565 error(msg)
1564 error(msg)
1566 return
1565 return
1567
1566
1568 if filename.lower().endswith('.ipy'):
1567 if filename.lower().endswith('.ipy'):
1569 self.shell.safe_execfile_ipy(filename)
1568 self.shell.safe_execfile_ipy(filename)
1570 return
1569 return
1571
1570
1572 # Control the response to exit() calls made by the script being run
1571 # Control the response to exit() calls made by the script being run
1573 exit_ignore = opts.has_key('e')
1572 exit_ignore = opts.has_key('e')
1574
1573
1575 # Make sure that the running script gets a proper sys.argv as if it
1574 # Make sure that the running script gets a proper sys.argv as if it
1576 # were run from a system shell.
1575 # were run from a system shell.
1577 save_argv = sys.argv # save it for later restoring
1576 save_argv = sys.argv # save it for later restoring
1578 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1577 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1579
1578
1580 if opts.has_key('i'):
1579 if opts.has_key('i'):
1581 # Run in user's interactive namespace
1580 # Run in user's interactive namespace
1582 prog_ns = self.shell.user_ns
1581 prog_ns = self.shell.user_ns
1583 __name__save = self.shell.user_ns['__name__']
1582 __name__save = self.shell.user_ns['__name__']
1584 prog_ns['__name__'] = '__main__'
1583 prog_ns['__name__'] = '__main__'
1585 main_mod = self.shell.new_main_mod(prog_ns)
1584 main_mod = self.shell.new_main_mod(prog_ns)
1586 else:
1585 else:
1587 # Run in a fresh, empty namespace
1586 # Run in a fresh, empty namespace
1588 if opts.has_key('n'):
1587 if opts.has_key('n'):
1589 name = os.path.splitext(os.path.basename(filename))[0]
1588 name = os.path.splitext(os.path.basename(filename))[0]
1590 else:
1589 else:
1591 name = '__main__'
1590 name = '__main__'
1592
1591
1593 main_mod = self.shell.new_main_mod()
1592 main_mod = self.shell.new_main_mod()
1594 prog_ns = main_mod.__dict__
1593 prog_ns = main_mod.__dict__
1595 prog_ns['__name__'] = name
1594 prog_ns['__name__'] = name
1596
1595
1597 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1596 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1598 # set the __file__ global in the script's namespace
1597 # set the __file__ global in the script's namespace
1599 prog_ns['__file__'] = filename
1598 prog_ns['__file__'] = filename
1600
1599
1601 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1600 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1602 # that, if we overwrite __main__, we replace it at the end
1601 # that, if we overwrite __main__, we replace it at the end
1603 main_mod_name = prog_ns['__name__']
1602 main_mod_name = prog_ns['__name__']
1604
1603
1605 if main_mod_name == '__main__':
1604 if main_mod_name == '__main__':
1606 restore_main = sys.modules['__main__']
1605 restore_main = sys.modules['__main__']
1607 else:
1606 else:
1608 restore_main = False
1607 restore_main = False
1609
1608
1610 # This needs to be undone at the end to prevent holding references to
1609 # This needs to be undone at the end to prevent holding references to
1611 # every single object ever created.
1610 # every single object ever created.
1612 sys.modules[main_mod_name] = main_mod
1611 sys.modules[main_mod_name] = main_mod
1613
1612
1614 try:
1613 try:
1615 stats = None
1614 stats = None
1616 with self.readline_no_record:
1615 with self.readline_no_record:
1617 if opts.has_key('p'):
1616 if opts.has_key('p'):
1618 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1617 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1619 else:
1618 else:
1620 if opts.has_key('d'):
1619 if opts.has_key('d'):
1621 deb = debugger.Pdb(self.shell.colors)
1620 deb = debugger.Pdb(self.shell.colors)
1622 # reset Breakpoint state, which is moronically kept
1621 # reset Breakpoint state, which is moronically kept
1623 # in a class
1622 # in a class
1624 bdb.Breakpoint.next = 1
1623 bdb.Breakpoint.next = 1
1625 bdb.Breakpoint.bplist = {}
1624 bdb.Breakpoint.bplist = {}
1626 bdb.Breakpoint.bpbynumber = [None]
1625 bdb.Breakpoint.bpbynumber = [None]
1627 # Set an initial breakpoint to stop execution
1626 # Set an initial breakpoint to stop execution
1628 maxtries = 10
1627 maxtries = 10
1629 bp = int(opts.get('b',[1])[0])
1628 bp = int(opts.get('b',[1])[0])
1630 checkline = deb.checkline(filename,bp)
1629 checkline = deb.checkline(filename,bp)
1631 if not checkline:
1630 if not checkline:
1632 for bp in range(bp+1,bp+maxtries+1):
1631 for bp in range(bp+1,bp+maxtries+1):
1633 if deb.checkline(filename,bp):
1632 if deb.checkline(filename,bp):
1634 break
1633 break
1635 else:
1634 else:
1636 msg = ("\nI failed to find a valid line to set "
1635 msg = ("\nI failed to find a valid line to set "
1637 "a breakpoint\n"
1636 "a breakpoint\n"
1638 "after trying up to line: %s.\n"
1637 "after trying up to line: %s.\n"
1639 "Please set a valid breakpoint manually "
1638 "Please set a valid breakpoint manually "
1640 "with the -b option." % bp)
1639 "with the -b option." % bp)
1641 error(msg)
1640 error(msg)
1642 return
1641 return
1643 # if we find a good linenumber, set the breakpoint
1642 # if we find a good linenumber, set the breakpoint
1644 deb.do_break('%s:%s' % (filename,bp))
1643 deb.do_break('%s:%s' % (filename,bp))
1645 # Start file run
1644 # Start file run
1646 print "NOTE: Enter 'c' at the",
1645 print "NOTE: Enter 'c' at the",
1647 print "%s prompt to start your script." % deb.prompt
1646 print "%s prompt to start your script." % deb.prompt
1648 try:
1647 try:
1649 deb.run('execfile("%s")' % filename,prog_ns)
1648 deb.run('execfile("%s")' % filename,prog_ns)
1650
1649
1651 except:
1650 except:
1652 etype, value, tb = sys.exc_info()
1651 etype, value, tb = sys.exc_info()
1653 # Skip three frames in the traceback: the %run one,
1652 # Skip three frames in the traceback: the %run one,
1654 # one inside bdb.py, and the command-line typed by the
1653 # one inside bdb.py, and the command-line typed by the
1655 # user (run by exec in pdb itself).
1654 # user (run by exec in pdb itself).
1656 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1655 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1657 else:
1656 else:
1658 if runner is None:
1657 if runner is None:
1659 runner = self.shell.safe_execfile
1658 runner = self.shell.safe_execfile
1660 if opts.has_key('t'):
1659 if opts.has_key('t'):
1661 # timed execution
1660 # timed execution
1662 try:
1661 try:
1663 nruns = int(opts['N'][0])
1662 nruns = int(opts['N'][0])
1664 if nruns < 1:
1663 if nruns < 1:
1665 error('Number of runs must be >=1')
1664 error('Number of runs must be >=1')
1666 return
1665 return
1667 except (KeyError):
1666 except (KeyError):
1668 nruns = 1
1667 nruns = 1
1669 if nruns == 1:
1668 if nruns == 1:
1670 t0 = clock2()
1669 t0 = clock2()
1671 runner(filename,prog_ns,prog_ns,
1670 runner(filename,prog_ns,prog_ns,
1672 exit_ignore=exit_ignore)
1671 exit_ignore=exit_ignore)
1673 t1 = clock2()
1672 t1 = clock2()
1674 t_usr = t1[0]-t0[0]
1673 t_usr = t1[0]-t0[0]
1675 t_sys = t1[1]-t0[1]
1674 t_sys = t1[1]-t0[1]
1676 print "\nIPython CPU timings (estimated):"
1675 print "\nIPython CPU timings (estimated):"
1677 print " User : %10s s." % t_usr
1676 print " User : %10s s." % t_usr
1678 print " System: %10s s." % t_sys
1677 print " System: %10s s." % t_sys
1679 else:
1678 else:
1680 runs = range(nruns)
1679 runs = range(nruns)
1681 t0 = clock2()
1680 t0 = clock2()
1682 for nr in runs:
1681 for nr in runs:
1683 runner(filename,prog_ns,prog_ns,
1682 runner(filename,prog_ns,prog_ns,
1684 exit_ignore=exit_ignore)
1683 exit_ignore=exit_ignore)
1685 t1 = clock2()
1684 t1 = clock2()
1686 t_usr = t1[0]-t0[0]
1685 t_usr = t1[0]-t0[0]
1687 t_sys = t1[1]-t0[1]
1686 t_sys = t1[1]-t0[1]
1688 print "\nIPython CPU timings (estimated):"
1687 print "\nIPython CPU timings (estimated):"
1689 print "Total runs performed:",nruns
1688 print "Total runs performed:",nruns
1690 print " Times : %10s %10s" % ('Total','Per run')
1689 print " Times : %10s %10s" % ('Total','Per run')
1691 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1690 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1692 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1691 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1693
1692
1694 else:
1693 else:
1695 # regular execution
1694 # regular execution
1696 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1695 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1697
1696
1698 if opts.has_key('i'):
1697 if opts.has_key('i'):
1699 self.shell.user_ns['__name__'] = __name__save
1698 self.shell.user_ns['__name__'] = __name__save
1700 else:
1699 else:
1701 # The shell MUST hold a reference to prog_ns so after %run
1700 # The shell MUST hold a reference to prog_ns so after %run
1702 # exits, the python deletion mechanism doesn't zero it out
1701 # exits, the python deletion mechanism doesn't zero it out
1703 # (leaving dangling references).
1702 # (leaving dangling references).
1704 self.shell.cache_main_mod(prog_ns,filename)
1703 self.shell.cache_main_mod(prog_ns,filename)
1705 # update IPython interactive namespace
1704 # update IPython interactive namespace
1706
1705
1707 # Some forms of read errors on the file may mean the
1706 # Some forms of read errors on the file may mean the
1708 # __name__ key was never set; using pop we don't have to
1707 # __name__ key was never set; using pop we don't have to
1709 # worry about a possible KeyError.
1708 # worry about a possible KeyError.
1710 prog_ns.pop('__name__', None)
1709 prog_ns.pop('__name__', None)
1711
1710
1712 self.shell.user_ns.update(prog_ns)
1711 self.shell.user_ns.update(prog_ns)
1713 finally:
1712 finally:
1714 # It's a bit of a mystery why, but __builtins__ can change from
1713 # It's a bit of a mystery why, but __builtins__ can change from
1715 # being a module to becoming a dict missing some key data after
1714 # being a module to becoming a dict missing some key data after
1716 # %run. As best I can see, this is NOT something IPython is doing
1715 # %run. As best I can see, this is NOT something IPython is doing
1717 # at all, and similar problems have been reported before:
1716 # at all, and similar problems have been reported before:
1718 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1717 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1719 # Since this seems to be done by the interpreter itself, the best
1718 # Since this seems to be done by the interpreter itself, the best
1720 # we can do is to at least restore __builtins__ for the user on
1719 # we can do is to at least restore __builtins__ for the user on
1721 # exit.
1720 # exit.
1722 self.shell.user_ns['__builtins__'] = __builtin__
1721 self.shell.user_ns['__builtins__'] = __builtin__
1723
1722
1724 # Ensure key global structures are restored
1723 # Ensure key global structures are restored
1725 sys.argv = save_argv
1724 sys.argv = save_argv
1726 if restore_main:
1725 if restore_main:
1727 sys.modules['__main__'] = restore_main
1726 sys.modules['__main__'] = restore_main
1728 else:
1727 else:
1729 # Remove from sys.modules the reference to main_mod we'd
1728 # Remove from sys.modules the reference to main_mod we'd
1730 # added. Otherwise it will trap references to objects
1729 # added. Otherwise it will trap references to objects
1731 # contained therein.
1730 # contained therein.
1732 del sys.modules[main_mod_name]
1731 del sys.modules[main_mod_name]
1733
1732
1734 return stats
1733 return stats
1735
1734
1736 @testdec.skip_doctest
1735 @testdec.skip_doctest
1737 def magic_timeit(self, parameter_s =''):
1736 def magic_timeit(self, parameter_s =''):
1738 """Time execution of a Python statement or expression
1737 """Time execution of a Python statement or expression
1739
1738
1740 Usage:\\
1739 Usage:\\
1741 %timeit [-n<N> -r<R> [-t|-c]] statement
1740 %timeit [-n<N> -r<R> [-t|-c]] statement
1742
1741
1743 Time execution of a Python statement or expression using the timeit
1742 Time execution of a Python statement or expression using the timeit
1744 module.
1743 module.
1745
1744
1746 Options:
1745 Options:
1747 -n<N>: execute the given statement <N> times in a loop. If this value
1746 -n<N>: execute the given statement <N> times in a loop. If this value
1748 is not given, a fitting value is chosen.
1747 is not given, a fitting value is chosen.
1749
1748
1750 -r<R>: repeat the loop iteration <R> times and take the best result.
1749 -r<R>: repeat the loop iteration <R> times and take the best result.
1751 Default: 3
1750 Default: 3
1752
1751
1753 -t: use time.time to measure the time, which is the default on Unix.
1752 -t: use time.time to measure the time, which is the default on Unix.
1754 This function measures wall time.
1753 This function measures wall time.
1755
1754
1756 -c: use time.clock to measure the time, which is the default on
1755 -c: use time.clock to measure the time, which is the default on
1757 Windows and measures wall time. On Unix, resource.getrusage is used
1756 Windows and measures wall time. On Unix, resource.getrusage is used
1758 instead and returns the CPU user time.
1757 instead and returns the CPU user time.
1759
1758
1760 -p<P>: use a precision of <P> digits to display the timing result.
1759 -p<P>: use a precision of <P> digits to display the timing result.
1761 Default: 3
1760 Default: 3
1762
1761
1763
1762
1764 Examples:
1763 Examples:
1765
1764
1766 In [1]: %timeit pass
1765 In [1]: %timeit pass
1767 10000000 loops, best of 3: 53.3 ns per loop
1766 10000000 loops, best of 3: 53.3 ns per loop
1768
1767
1769 In [2]: u = None
1768 In [2]: u = None
1770
1769
1771 In [3]: %timeit u is None
1770 In [3]: %timeit u is None
1772 10000000 loops, best of 3: 184 ns per loop
1771 10000000 loops, best of 3: 184 ns per loop
1773
1772
1774 In [4]: %timeit -r 4 u == None
1773 In [4]: %timeit -r 4 u == None
1775 1000000 loops, best of 4: 242 ns per loop
1774 1000000 loops, best of 4: 242 ns per loop
1776
1775
1777 In [5]: import time
1776 In [5]: import time
1778
1777
1779 In [6]: %timeit -n1 time.sleep(2)
1778 In [6]: %timeit -n1 time.sleep(2)
1780 1 loops, best of 3: 2 s per loop
1779 1 loops, best of 3: 2 s per loop
1781
1780
1782
1781
1783 The times reported by %timeit will be slightly higher than those
1782 The times reported by %timeit will be slightly higher than those
1784 reported by the timeit.py script when variables are accessed. This is
1783 reported by the timeit.py script when variables are accessed. This is
1785 due to the fact that %timeit executes the statement in the namespace
1784 due to the fact that %timeit executes the statement in the namespace
1786 of the shell, compared with timeit.py, which uses a single setup
1785 of the shell, compared with timeit.py, which uses a single setup
1787 statement to import function or create variables. Generally, the bias
1786 statement to import function or create variables. Generally, the bias
1788 does not matter as long as results from timeit.py are not mixed with
1787 does not matter as long as results from timeit.py are not mixed with
1789 those from %timeit."""
1788 those from %timeit."""
1790
1789
1791 import timeit
1790 import timeit
1792 import math
1791 import math
1793
1792
1794 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1793 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1795 # certain terminals. Until we figure out a robust way of
1794 # certain terminals. Until we figure out a robust way of
1796 # auto-detecting if the terminal can deal with it, use plain 'us' for
1795 # auto-detecting if the terminal can deal with it, use plain 'us' for
1797 # microseconds. I am really NOT happy about disabling the proper
1796 # microseconds. I am really NOT happy about disabling the proper
1798 # 'micro' prefix, but crashing is worse... If anyone knows what the
1797 # 'micro' prefix, but crashing is worse... If anyone knows what the
1799 # right solution for this is, I'm all ears...
1798 # right solution for this is, I'm all ears...
1800 #
1799 #
1801 # Note: using
1800 # Note: using
1802 #
1801 #
1803 # s = u'\xb5'
1802 # s = u'\xb5'
1804 # s.encode(sys.getdefaultencoding())
1803 # s.encode(sys.getdefaultencoding())
1805 #
1804 #
1806 # is not sufficient, as I've seen terminals where that fails but
1805 # is not sufficient, as I've seen terminals where that fails but
1807 # print s
1806 # print s
1808 #
1807 #
1809 # succeeds
1808 # succeeds
1810 #
1809 #
1811 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1810 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1812
1811
1813 #units = [u"s", u"ms",u'\xb5',"ns"]
1812 #units = [u"s", u"ms",u'\xb5',"ns"]
1814 units = [u"s", u"ms",u'us',"ns"]
1813 units = [u"s", u"ms",u'us',"ns"]
1815
1814
1816 scaling = [1, 1e3, 1e6, 1e9]
1815 scaling = [1, 1e3, 1e6, 1e9]
1817
1816
1818 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1817 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1819 posix=False)
1818 posix=False)
1820 if stmt == "":
1819 if stmt == "":
1821 return
1820 return
1822 timefunc = timeit.default_timer
1821 timefunc = timeit.default_timer
1823 number = int(getattr(opts, "n", 0))
1822 number = int(getattr(opts, "n", 0))
1824 repeat = int(getattr(opts, "r", timeit.default_repeat))
1823 repeat = int(getattr(opts, "r", timeit.default_repeat))
1825 precision = int(getattr(opts, "p", 3))
1824 precision = int(getattr(opts, "p", 3))
1826 if hasattr(opts, "t"):
1825 if hasattr(opts, "t"):
1827 timefunc = time.time
1826 timefunc = time.time
1828 if hasattr(opts, "c"):
1827 if hasattr(opts, "c"):
1829 timefunc = clock
1828 timefunc = clock
1830
1829
1831 timer = timeit.Timer(timer=timefunc)
1830 timer = timeit.Timer(timer=timefunc)
1832 # this code has tight coupling to the inner workings of timeit.Timer,
1831 # this code has tight coupling to the inner workings of timeit.Timer,
1833 # but is there a better way to achieve that the code stmt has access
1832 # but is there a better way to achieve that the code stmt has access
1834 # to the shell namespace?
1833 # to the shell namespace?
1835
1834
1836 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1835 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1837 'setup': "pass"}
1836 'setup': "pass"}
1838 # Track compilation time so it can be reported if too long
1837 # Track compilation time so it can be reported if too long
1839 # Minimum time above which compilation time will be reported
1838 # Minimum time above which compilation time will be reported
1840 tc_min = 0.1
1839 tc_min = 0.1
1841
1840
1842 t0 = clock()
1841 t0 = clock()
1843 code = compile(src, "<magic-timeit>", "exec")
1842 code = compile(src, "<magic-timeit>", "exec")
1844 tc = clock()-t0
1843 tc = clock()-t0
1845
1844
1846 ns = {}
1845 ns = {}
1847 exec code in self.shell.user_ns, ns
1846 exec code in self.shell.user_ns, ns
1848 timer.inner = ns["inner"]
1847 timer.inner = ns["inner"]
1849
1848
1850 if number == 0:
1849 if number == 0:
1851 # determine number so that 0.2 <= total time < 2.0
1850 # determine number so that 0.2 <= total time < 2.0
1852 number = 1
1851 number = 1
1853 for i in range(1, 10):
1852 for i in range(1, 10):
1854 if timer.timeit(number) >= 0.2:
1853 if timer.timeit(number) >= 0.2:
1855 break
1854 break
1856 number *= 10
1855 number *= 10
1857
1856
1858 best = min(timer.repeat(repeat, number)) / number
1857 best = min(timer.repeat(repeat, number)) / number
1859
1858
1860 if best > 0.0 and best < 1000.0:
1859 if best > 0.0 and best < 1000.0:
1861 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1860 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1862 elif best >= 1000.0:
1861 elif best >= 1000.0:
1863 order = 0
1862 order = 0
1864 else:
1863 else:
1865 order = 3
1864 order = 3
1866 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1865 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1867 precision,
1866 precision,
1868 best * scaling[order],
1867 best * scaling[order],
1869 units[order])
1868 units[order])
1870 if tc > tc_min:
1869 if tc > tc_min:
1871 print "Compiler time: %.2f s" % tc
1870 print "Compiler time: %.2f s" % tc
1872
1871
1873 @testdec.skip_doctest
1872 @testdec.skip_doctest
1874 @needs_local_scope
1873 @needs_local_scope
1875 def magic_time(self,parameter_s = ''):
1874 def magic_time(self,parameter_s = ''):
1876 """Time execution of a Python statement or expression.
1875 """Time execution of a Python statement or expression.
1877
1876
1878 The CPU and wall clock times are printed, and the value of the
1877 The CPU and wall clock times are printed, and the value of the
1879 expression (if any) is returned. Note that under Win32, system time
1878 expression (if any) is returned. Note that under Win32, system time
1880 is always reported as 0, since it can not be measured.
1879 is always reported as 0, since it can not be measured.
1881
1880
1882 This function provides very basic timing functionality. In Python
1881 This function provides very basic timing functionality. In Python
1883 2.3, the timeit module offers more control and sophistication, so this
1882 2.3, the timeit module offers more control and sophistication, so this
1884 could be rewritten to use it (patches welcome).
1883 could be rewritten to use it (patches welcome).
1885
1884
1886 Some examples:
1885 Some examples:
1887
1886
1888 In [1]: time 2**128
1887 In [1]: time 2**128
1889 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1888 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1890 Wall time: 0.00
1889 Wall time: 0.00
1891 Out[1]: 340282366920938463463374607431768211456L
1890 Out[1]: 340282366920938463463374607431768211456L
1892
1891
1893 In [2]: n = 1000000
1892 In [2]: n = 1000000
1894
1893
1895 In [3]: time sum(range(n))
1894 In [3]: time sum(range(n))
1896 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1895 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1897 Wall time: 1.37
1896 Wall time: 1.37
1898 Out[3]: 499999500000L
1897 Out[3]: 499999500000L
1899
1898
1900 In [4]: time print 'hello world'
1899 In [4]: time print 'hello world'
1901 hello world
1900 hello world
1902 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1901 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1903 Wall time: 0.00
1902 Wall time: 0.00
1904
1903
1905 Note that the time needed by Python to compile the given expression
1904 Note that the time needed by Python to compile the given expression
1906 will be reported if it is more than 0.1s. In this example, the
1905 will be reported if it is more than 0.1s. In this example, the
1907 actual exponentiation is done by Python at compilation time, so while
1906 actual exponentiation is done by Python at compilation time, so while
1908 the expression can take a noticeable amount of time to compute, that
1907 the expression can take a noticeable amount of time to compute, that
1909 time is purely due to the compilation:
1908 time is purely due to the compilation:
1910
1909
1911 In [5]: time 3**9999;
1910 In [5]: time 3**9999;
1912 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1911 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1913 Wall time: 0.00 s
1912 Wall time: 0.00 s
1914
1913
1915 In [6]: time 3**999999;
1914 In [6]: time 3**999999;
1916 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1915 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1917 Wall time: 0.00 s
1916 Wall time: 0.00 s
1918 Compiler : 0.78 s
1917 Compiler : 0.78 s
1919 """
1918 """
1920
1919
1921 # fail immediately if the given expression can't be compiled
1920 # fail immediately if the given expression can't be compiled
1922
1921
1923 expr = self.shell.prefilter(parameter_s,False)
1922 expr = self.shell.prefilter(parameter_s,False)
1924
1923
1925 # Minimum time above which compilation time will be reported
1924 # Minimum time above which compilation time will be reported
1926 tc_min = 0.1
1925 tc_min = 0.1
1927
1926
1928 try:
1927 try:
1929 mode = 'eval'
1928 mode = 'eval'
1930 t0 = clock()
1929 t0 = clock()
1931 code = compile(expr,'<timed eval>',mode)
1930 code = compile(expr,'<timed eval>',mode)
1932 tc = clock()-t0
1931 tc = clock()-t0
1933 except SyntaxError:
1932 except SyntaxError:
1934 mode = 'exec'
1933 mode = 'exec'
1935 t0 = clock()
1934 t0 = clock()
1936 code = compile(expr,'<timed exec>',mode)
1935 code = compile(expr,'<timed exec>',mode)
1937 tc = clock()-t0
1936 tc = clock()-t0
1938 # skew measurement as little as possible
1937 # skew measurement as little as possible
1939 glob = self.shell.user_ns
1938 glob = self.shell.user_ns
1940 locs = self._magic_locals
1939 locs = self._magic_locals
1941 clk = clock2
1940 clk = clock2
1942 wtime = time.time
1941 wtime = time.time
1943 # time execution
1942 # time execution
1944 wall_st = wtime()
1943 wall_st = wtime()
1945 if mode=='eval':
1944 if mode=='eval':
1946 st = clk()
1945 st = clk()
1947 out = eval(code, glob, locs)
1946 out = eval(code, glob, locs)
1948 end = clk()
1947 end = clk()
1949 else:
1948 else:
1950 st = clk()
1949 st = clk()
1951 exec code in glob, locs
1950 exec code in glob, locs
1952 end = clk()
1951 end = clk()
1953 out = None
1952 out = None
1954 wall_end = wtime()
1953 wall_end = wtime()
1955 # Compute actual times and report
1954 # Compute actual times and report
1956 wall_time = wall_end-wall_st
1955 wall_time = wall_end-wall_st
1957 cpu_user = end[0]-st[0]
1956 cpu_user = end[0]-st[0]
1958 cpu_sys = end[1]-st[1]
1957 cpu_sys = end[1]-st[1]
1959 cpu_tot = cpu_user+cpu_sys
1958 cpu_tot = cpu_user+cpu_sys
1960 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1959 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1961 (cpu_user,cpu_sys,cpu_tot)
1960 (cpu_user,cpu_sys,cpu_tot)
1962 print "Wall time: %.2f s" % wall_time
1961 print "Wall time: %.2f s" % wall_time
1963 if tc > tc_min:
1962 if tc > tc_min:
1964 print "Compiler : %.2f s" % tc
1963 print "Compiler : %.2f s" % tc
1965 return out
1964 return out
1966
1965
1967 @testdec.skip_doctest
1966 @testdec.skip_doctest
1968 def magic_macro(self,parameter_s = ''):
1967 def magic_macro(self,parameter_s = ''):
1969 """Define a macro for future re-execution. It accepts ranges of history,
1968 """Define a macro for future re-execution. It accepts ranges of history,
1970 filenames or string objects.
1969 filenames or string objects.
1971
1970
1972 Usage:\\
1971 Usage:\\
1973 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1972 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1974
1973
1975 Options:
1974 Options:
1976
1975
1977 -r: use 'raw' input. By default, the 'processed' history is used,
1976 -r: use 'raw' input. By default, the 'processed' history is used,
1978 so that magics are loaded in their transformed version to valid
1977 so that magics are loaded in their transformed version to valid
1979 Python. If this option is given, the raw input as typed as the
1978 Python. If this option is given, the raw input as typed as the
1980 command line is used instead.
1979 command line is used instead.
1981
1980
1982 This will define a global variable called `name` which is a string
1981 This will define a global variable called `name` which is a string
1983 made of joining the slices and lines you specify (n1,n2,... numbers
1982 made of joining the slices and lines you specify (n1,n2,... numbers
1984 above) from your input history into a single string. This variable
1983 above) from your input history into a single string. This variable
1985 acts like an automatic function which re-executes those lines as if
1984 acts like an automatic function which re-executes those lines as if
1986 you had typed them. You just type 'name' at the prompt and the code
1985 you had typed them. You just type 'name' at the prompt and the code
1987 executes.
1986 executes.
1988
1987
1989 The syntax for indicating input ranges is described in %history.
1988 The syntax for indicating input ranges is described in %history.
1990
1989
1991 Note: as a 'hidden' feature, you can also use traditional python slice
1990 Note: as a 'hidden' feature, you can also use traditional python slice
1992 notation, where N:M means numbers N through M-1.
1991 notation, where N:M means numbers N through M-1.
1993
1992
1994 For example, if your history contains (%hist prints it):
1993 For example, if your history contains (%hist prints it):
1995
1994
1996 44: x=1
1995 44: x=1
1997 45: y=3
1996 45: y=3
1998 46: z=x+y
1997 46: z=x+y
1999 47: print x
1998 47: print x
2000 48: a=5
1999 48: a=5
2001 49: print 'x',x,'y',y
2000 49: print 'x',x,'y',y
2002
2001
2003 you can create a macro with lines 44 through 47 (included) and line 49
2002 you can create a macro with lines 44 through 47 (included) and line 49
2004 called my_macro with:
2003 called my_macro with:
2005
2004
2006 In [55]: %macro my_macro 44-47 49
2005 In [55]: %macro my_macro 44-47 49
2007
2006
2008 Now, typing `my_macro` (without quotes) will re-execute all this code
2007 Now, typing `my_macro` (without quotes) will re-execute all this code
2009 in one pass.
2008 in one pass.
2010
2009
2011 You don't need to give the line-numbers in order, and any given line
2010 You don't need to give the line-numbers in order, and any given line
2012 number can appear multiple times. You can assemble macros with any
2011 number can appear multiple times. You can assemble macros with any
2013 lines from your input history in any order.
2012 lines from your input history in any order.
2014
2013
2015 The macro is a simple object which holds its value in an attribute,
2014 The macro is a simple object which holds its value in an attribute,
2016 but IPython's display system checks for macros and executes them as
2015 but IPython's display system checks for macros and executes them as
2017 code instead of printing them when you type their name.
2016 code instead of printing them when you type their name.
2018
2017
2019 You can view a macro's contents by explicitly printing it with:
2018 You can view a macro's contents by explicitly printing it with:
2020
2019
2021 'print macro_name'.
2020 'print macro_name'.
2022
2021
2023 """
2022 """
2024
2023
2025 opts,args = self.parse_options(parameter_s,'r',mode='list')
2024 opts,args = self.parse_options(parameter_s,'r',mode='list')
2026 if not args: # List existing macros
2025 if not args: # List existing macros
2027 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2026 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2028 isinstance(v, Macro))
2027 isinstance(v, Macro))
2029 if len(args) == 1:
2028 if len(args) == 1:
2030 raise UsageError(
2029 raise UsageError(
2031 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2030 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2032 name, codefrom = args[0], " ".join(args[1:])
2031 name, codefrom = args[0], " ".join(args[1:])
2033
2032
2034 #print 'rng',ranges # dbg
2033 #print 'rng',ranges # dbg
2035 try:
2034 try:
2036 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2035 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2037 except (ValueError, TypeError) as e:
2036 except (ValueError, TypeError) as e:
2038 print e.args[0]
2037 print e.args[0]
2039 return
2038 return
2040 macro = Macro(lines)
2039 macro = Macro(lines)
2041 self.shell.define_macro(name, macro)
2040 self.shell.define_macro(name, macro)
2042 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2041 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2043 print '=== Macro contents: ==='
2042 print '=== Macro contents: ==='
2044 print macro,
2043 print macro,
2045
2044
2046 def magic_save(self,parameter_s = ''):
2045 def magic_save(self,parameter_s = ''):
2047 """Save a set of lines or a macro to a given filename.
2046 """Save a set of lines or a macro to a given filename.
2048
2047
2049 Usage:\\
2048 Usage:\\
2050 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2049 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2051
2050
2052 Options:
2051 Options:
2053
2052
2054 -r: use 'raw' input. By default, the 'processed' history is used,
2053 -r: use 'raw' input. By default, the 'processed' history is used,
2055 so that magics are loaded in their transformed version to valid
2054 so that magics are loaded in their transformed version to valid
2056 Python. If this option is given, the raw input as typed as the
2055 Python. If this option is given, the raw input as typed as the
2057 command line is used instead.
2056 command line is used instead.
2058
2057
2059 This function uses the same syntax as %history for input ranges,
2058 This function uses the same syntax as %history for input ranges,
2060 then saves the lines to the filename you specify.
2059 then saves the lines to the filename you specify.
2061
2060
2062 It adds a '.py' extension to the file if you don't do so yourself, and
2061 It adds a '.py' extension to the file if you don't do so yourself, and
2063 it asks for confirmation before overwriting existing files."""
2062 it asks for confirmation before overwriting existing files."""
2064
2063
2065 opts,args = self.parse_options(parameter_s,'r',mode='list')
2064 opts,args = self.parse_options(parameter_s,'r',mode='list')
2066 fname, codefrom = args[0], " ".join(args[1:])
2065 fname, codefrom = args[0], " ".join(args[1:])
2067 if not fname.endswith('.py'):
2066 if not fname.endswith('.py'):
2068 fname += '.py'
2067 fname += '.py'
2069 if os.path.isfile(fname):
2068 if os.path.isfile(fname):
2070 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2069 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2071 if ans.lower() not in ['y','yes']:
2070 if ans.lower() not in ['y','yes']:
2072 print 'Operation cancelled.'
2071 print 'Operation cancelled.'
2073 return
2072 return
2074 try:
2073 try:
2075 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2074 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2076 except (TypeError, ValueError) as e:
2075 except (TypeError, ValueError) as e:
2077 print e.args[0]
2076 print e.args[0]
2078 return
2077 return
2079 if isinstance(cmds, unicode):
2078 if isinstance(cmds, unicode):
2080 cmds = cmds.encode("utf-8")
2079 cmds = cmds.encode("utf-8")
2081 with open(fname,'w') as f:
2080 with open(fname,'w') as f:
2082 f.write("# coding: utf-8\n")
2081 f.write("# coding: utf-8\n")
2083 f.write(cmds)
2082 f.write(cmds)
2084 print 'The following commands were written to file `%s`:' % fname
2083 print 'The following commands were written to file `%s`:' % fname
2085 print cmds
2084 print cmds
2086
2085
2087 def magic_pastebin(self, parameter_s = ''):
2086 def magic_pastebin(self, parameter_s = ''):
2088 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2087 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2089 try:
2088 try:
2090 code = self.shell.find_user_code(parameter_s)
2089 code = self.shell.find_user_code(parameter_s)
2091 except (ValueError, TypeError) as e:
2090 except (ValueError, TypeError) as e:
2092 print e.args[0]
2091 print e.args[0]
2093 return
2092 return
2094 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2093 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2095 id = pbserver.pastes.newPaste("python", code)
2094 id = pbserver.pastes.newPaste("python", code)
2096 return "http://paste.pocoo.org/show/" + id
2095 return "http://paste.pocoo.org/show/" + id
2097
2096
2098 def _edit_macro(self,mname,macro):
2097 def _edit_macro(self,mname,macro):
2099 """open an editor with the macro data in a file"""
2098 """open an editor with the macro data in a file"""
2100 filename = self.shell.mktempfile(macro.value)
2099 filename = self.shell.mktempfile(macro.value)
2101 self.shell.hooks.editor(filename)
2100 self.shell.hooks.editor(filename)
2102
2101
2103 # and make a new macro object, to replace the old one
2102 # and make a new macro object, to replace the old one
2104 mfile = open(filename)
2103 mfile = open(filename)
2105 mvalue = mfile.read()
2104 mvalue = mfile.read()
2106 mfile.close()
2105 mfile.close()
2107 self.shell.user_ns[mname] = Macro(mvalue)
2106 self.shell.user_ns[mname] = Macro(mvalue)
2108
2107
2109 def magic_ed(self,parameter_s=''):
2108 def magic_ed(self,parameter_s=''):
2110 """Alias to %edit."""
2109 """Alias to %edit."""
2111 return self.magic_edit(parameter_s)
2110 return self.magic_edit(parameter_s)
2112
2111
2113 @testdec.skip_doctest
2112 @testdec.skip_doctest
2114 def magic_edit(self,parameter_s='',last_call=['','']):
2113 def magic_edit(self,parameter_s='',last_call=['','']):
2115 """Bring up an editor and execute the resulting code.
2114 """Bring up an editor and execute the resulting code.
2116
2115
2117 Usage:
2116 Usage:
2118 %edit [options] [args]
2117 %edit [options] [args]
2119
2118
2120 %edit runs IPython's editor hook. The default version of this hook is
2119 %edit runs IPython's editor hook. The default version of this hook is
2121 set to call the __IPYTHON__.rc.editor command. This is read from your
2120 set to call the __IPYTHON__.rc.editor command. This is read from your
2122 environment variable $EDITOR. If this isn't found, it will default to
2121 environment variable $EDITOR. If this isn't found, it will default to
2123 vi under Linux/Unix and to notepad under Windows. See the end of this
2122 vi under Linux/Unix and to notepad under Windows. See the end of this
2124 docstring for how to change the editor hook.
2123 docstring for how to change the editor hook.
2125
2124
2126 You can also set the value of this editor via the command line option
2125 You can also set the value of this editor via the command line option
2127 '-editor' or in your ipythonrc file. This is useful if you wish to use
2126 '-editor' or in your ipythonrc file. This is useful if you wish to use
2128 specifically for IPython an editor different from your typical default
2127 specifically for IPython an editor different from your typical default
2129 (and for Windows users who typically don't set environment variables).
2128 (and for Windows users who typically don't set environment variables).
2130
2129
2131 This command allows you to conveniently edit multi-line code right in
2130 This command allows you to conveniently edit multi-line code right in
2132 your IPython session.
2131 your IPython session.
2133
2132
2134 If called without arguments, %edit opens up an empty editor with a
2133 If called without arguments, %edit opens up an empty editor with a
2135 temporary file and will execute the contents of this file when you
2134 temporary file and will execute the contents of this file when you
2136 close it (don't forget to save it!).
2135 close it (don't forget to save it!).
2137
2136
2138
2137
2139 Options:
2138 Options:
2140
2139
2141 -n <number>: open the editor at a specified line number. By default,
2140 -n <number>: open the editor at a specified line number. By default,
2142 the IPython editor hook uses the unix syntax 'editor +N filename', but
2141 the IPython editor hook uses the unix syntax 'editor +N filename', but
2143 you can configure this by providing your own modified hook if your
2142 you can configure this by providing your own modified hook if your
2144 favorite editor supports line-number specifications with a different
2143 favorite editor supports line-number specifications with a different
2145 syntax.
2144 syntax.
2146
2145
2147 -p: this will call the editor with the same data as the previous time
2146 -p: this will call the editor with the same data as the previous time
2148 it was used, regardless of how long ago (in your current session) it
2147 it was used, regardless of how long ago (in your current session) it
2149 was.
2148 was.
2150
2149
2151 -r: use 'raw' input. This option only applies to input taken from the
2150 -r: use 'raw' input. This option only applies to input taken from the
2152 user's history. By default, the 'processed' history is used, so that
2151 user's history. By default, the 'processed' history is used, so that
2153 magics are loaded in their transformed version to valid Python. If
2152 magics are loaded in their transformed version to valid Python. If
2154 this option is given, the raw input as typed as the command line is
2153 this option is given, the raw input as typed as the command line is
2155 used instead. When you exit the editor, it will be executed by
2154 used instead. When you exit the editor, it will be executed by
2156 IPython's own processor.
2155 IPython's own processor.
2157
2156
2158 -x: do not execute the edited code immediately upon exit. This is
2157 -x: do not execute the edited code immediately upon exit. This is
2159 mainly useful if you are editing programs which need to be called with
2158 mainly useful if you are editing programs which need to be called with
2160 command line arguments, which you can then do using %run.
2159 command line arguments, which you can then do using %run.
2161
2160
2162
2161
2163 Arguments:
2162 Arguments:
2164
2163
2165 If arguments are given, the following possibilites exist:
2164 If arguments are given, the following possibilites exist:
2166
2165
2167 - If the argument is a filename, IPython will load that into the
2166 - If the argument is a filename, IPython will load that into the
2168 editor. It will execute its contents with execfile() when you exit,
2167 editor. It will execute its contents with execfile() when you exit,
2169 loading any code in the file into your interactive namespace.
2168 loading any code in the file into your interactive namespace.
2170
2169
2171 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2170 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2172 The syntax is the same as in the %history magic.
2171 The syntax is the same as in the %history magic.
2173
2172
2174 - If the argument is a string variable, its contents are loaded
2173 - If the argument is a string variable, its contents are loaded
2175 into the editor. You can thus edit any string which contains
2174 into the editor. You can thus edit any string which contains
2176 python code (including the result of previous edits).
2175 python code (including the result of previous edits).
2177
2176
2178 - If the argument is the name of an object (other than a string),
2177 - If the argument is the name of an object (other than a string),
2179 IPython will try to locate the file where it was defined and open the
2178 IPython will try to locate the file where it was defined and open the
2180 editor at the point where it is defined. You can use `%edit function`
2179 editor at the point where it is defined. You can use `%edit function`
2181 to load an editor exactly at the point where 'function' is defined,
2180 to load an editor exactly at the point where 'function' is defined,
2182 edit it and have the file be executed automatically.
2181 edit it and have the file be executed automatically.
2183
2182
2184 If the object is a macro (see %macro for details), this opens up your
2183 If the object is a macro (see %macro for details), this opens up your
2185 specified editor with a temporary file containing the macro's data.
2184 specified editor with a temporary file containing the macro's data.
2186 Upon exit, the macro is reloaded with the contents of the file.
2185 Upon exit, the macro is reloaded with the contents of the file.
2187
2186
2188 Note: opening at an exact line is only supported under Unix, and some
2187 Note: opening at an exact line is only supported under Unix, and some
2189 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2188 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2190 '+NUMBER' parameter necessary for this feature. Good editors like
2189 '+NUMBER' parameter necessary for this feature. Good editors like
2191 (X)Emacs, vi, jed, pico and joe all do.
2190 (X)Emacs, vi, jed, pico and joe all do.
2192
2191
2193 After executing your code, %edit will return as output the code you
2192 After executing your code, %edit will return as output the code you
2194 typed in the editor (except when it was an existing file). This way
2193 typed in the editor (except when it was an existing file). This way
2195 you can reload the code in further invocations of %edit as a variable,
2194 you can reload the code in further invocations of %edit as a variable,
2196 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2195 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2197 the output.
2196 the output.
2198
2197
2199 Note that %edit is also available through the alias %ed.
2198 Note that %edit is also available through the alias %ed.
2200
2199
2201 This is an example of creating a simple function inside the editor and
2200 This is an example of creating a simple function inside the editor and
2202 then modifying it. First, start up the editor:
2201 then modifying it. First, start up the editor:
2203
2202
2204 In [1]: ed
2203 In [1]: ed
2205 Editing... done. Executing edited code...
2204 Editing... done. Executing edited code...
2206 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2205 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2207
2206
2208 We can then call the function foo():
2207 We can then call the function foo():
2209
2208
2210 In [2]: foo()
2209 In [2]: foo()
2211 foo() was defined in an editing session
2210 foo() was defined in an editing session
2212
2211
2213 Now we edit foo. IPython automatically loads the editor with the
2212 Now we edit foo. IPython automatically loads the editor with the
2214 (temporary) file where foo() was previously defined:
2213 (temporary) file where foo() was previously defined:
2215
2214
2216 In [3]: ed foo
2215 In [3]: ed foo
2217 Editing... done. Executing edited code...
2216 Editing... done. Executing edited code...
2218
2217
2219 And if we call foo() again we get the modified version:
2218 And if we call foo() again we get the modified version:
2220
2219
2221 In [4]: foo()
2220 In [4]: foo()
2222 foo() has now been changed!
2221 foo() has now been changed!
2223
2222
2224 Here is an example of how to edit a code snippet successive
2223 Here is an example of how to edit a code snippet successive
2225 times. First we call the editor:
2224 times. First we call the editor:
2226
2225
2227 In [5]: ed
2226 In [5]: ed
2228 Editing... done. Executing edited code...
2227 Editing... done. Executing edited code...
2229 hello
2228 hello
2230 Out[5]: "print 'hello'n"
2229 Out[5]: "print 'hello'n"
2231
2230
2232 Now we call it again with the previous output (stored in _):
2231 Now we call it again with the previous output (stored in _):
2233
2232
2234 In [6]: ed _
2233 In [6]: ed _
2235 Editing... done. Executing edited code...
2234 Editing... done. Executing edited code...
2236 hello world
2235 hello world
2237 Out[6]: "print 'hello world'n"
2236 Out[6]: "print 'hello world'n"
2238
2237
2239 Now we call it with the output #8 (stored in _8, also as Out[8]):
2238 Now we call it with the output #8 (stored in _8, also as Out[8]):
2240
2239
2241 In [7]: ed _8
2240 In [7]: ed _8
2242 Editing... done. Executing edited code...
2241 Editing... done. Executing edited code...
2243 hello again
2242 hello again
2244 Out[7]: "print 'hello again'n"
2243 Out[7]: "print 'hello again'n"
2245
2244
2246
2245
2247 Changing the default editor hook:
2246 Changing the default editor hook:
2248
2247
2249 If you wish to write your own editor hook, you can put it in a
2248 If you wish to write your own editor hook, you can put it in a
2250 configuration file which you load at startup time. The default hook
2249 configuration file which you load at startup time. The default hook
2251 is defined in the IPython.core.hooks module, and you can use that as a
2250 is defined in the IPython.core.hooks module, and you can use that as a
2252 starting example for further modifications. That file also has
2251 starting example for further modifications. That file also has
2253 general instructions on how to set a new hook for use once you've
2252 general instructions on how to set a new hook for use once you've
2254 defined it."""
2253 defined it."""
2255
2254
2256 # FIXME: This function has become a convoluted mess. It needs a
2255 # FIXME: This function has become a convoluted mess. It needs a
2257 # ground-up rewrite with clean, simple logic.
2256 # ground-up rewrite with clean, simple logic.
2258
2257
2259 def make_filename(arg):
2258 def make_filename(arg):
2260 "Make a filename from the given args"
2259 "Make a filename from the given args"
2261 try:
2260 try:
2262 filename = get_py_filename(arg)
2261 filename = get_py_filename(arg)
2263 except IOError:
2262 except IOError:
2264 if args.endswith('.py'):
2263 if args.endswith('.py'):
2265 filename = arg
2264 filename = arg
2266 else:
2265 else:
2267 filename = None
2266 filename = None
2268 return filename
2267 return filename
2269
2268
2270 # custom exceptions
2269 # custom exceptions
2271 class DataIsObject(Exception): pass
2270 class DataIsObject(Exception): pass
2272
2271
2273 opts,args = self.parse_options(parameter_s,'prxn:')
2272 opts,args = self.parse_options(parameter_s,'prxn:')
2274 # Set a few locals from the options for convenience:
2273 # Set a few locals from the options for convenience:
2275 opts_prev = 'p' in opts
2274 opts_prev = 'p' in opts
2276 opts_raw = 'r' in opts
2275 opts_raw = 'r' in opts
2277
2276
2278 # Default line number value
2277 # Default line number value
2279 lineno = opts.get('n',None)
2278 lineno = opts.get('n',None)
2280
2279
2281 if opts_prev:
2280 if opts_prev:
2282 args = '_%s' % last_call[0]
2281 args = '_%s' % last_call[0]
2283 if not self.shell.user_ns.has_key(args):
2282 if not self.shell.user_ns.has_key(args):
2284 args = last_call[1]
2283 args = last_call[1]
2285
2284
2286 # use last_call to remember the state of the previous call, but don't
2285 # use last_call to remember the state of the previous call, but don't
2287 # let it be clobbered by successive '-p' calls.
2286 # let it be clobbered by successive '-p' calls.
2288 try:
2287 try:
2289 last_call[0] = self.shell.displayhook.prompt_count
2288 last_call[0] = self.shell.displayhook.prompt_count
2290 if not opts_prev:
2289 if not opts_prev:
2291 last_call[1] = parameter_s
2290 last_call[1] = parameter_s
2292 except:
2291 except:
2293 pass
2292 pass
2294
2293
2295 # by default this is done with temp files, except when the given
2294 # by default this is done with temp files, except when the given
2296 # arg is a filename
2295 # arg is a filename
2297 use_temp = True
2296 use_temp = True
2298
2297
2299 data = ''
2298 data = ''
2300 if args.endswith('.py'):
2299 if args.endswith('.py'):
2301 filename = make_filename(args)
2300 filename = make_filename(args)
2302 use_temp = False
2301 use_temp = False
2303 elif args:
2302 elif args:
2304 # Mode where user specifies ranges of lines, like in %macro.
2303 # Mode where user specifies ranges of lines, like in %macro.
2305 data = self.extract_input_lines(args, opts_raw)
2304 data = self.extract_input_lines(args, opts_raw)
2306 if not data:
2305 if not data:
2307 try:
2306 try:
2308 # Load the parameter given as a variable. If not a string,
2307 # Load the parameter given as a variable. If not a string,
2309 # process it as an object instead (below)
2308 # process it as an object instead (below)
2310
2309
2311 #print '*** args',args,'type',type(args) # dbg
2310 #print '*** args',args,'type',type(args) # dbg
2312 data = eval(args, self.shell.user_ns)
2311 data = eval(args, self.shell.user_ns)
2313 if not isinstance(data, basestring):
2312 if not isinstance(data, basestring):
2314 raise DataIsObject
2313 raise DataIsObject
2315
2314
2316 except (NameError,SyntaxError):
2315 except (NameError,SyntaxError):
2317 # given argument is not a variable, try as a filename
2316 # given argument is not a variable, try as a filename
2318 filename = make_filename(args)
2317 filename = make_filename(args)
2319 if filename is None:
2318 if filename is None:
2320 warn("Argument given (%s) can't be found as a variable "
2319 warn("Argument given (%s) can't be found as a variable "
2321 "or as a filename." % args)
2320 "or as a filename." % args)
2322 return
2321 return
2323 use_temp = False
2322 use_temp = False
2324
2323
2325 except DataIsObject:
2324 except DataIsObject:
2326 # macros have a special edit function
2325 # macros have a special edit function
2327 if isinstance(data, Macro):
2326 if isinstance(data, Macro):
2328 self._edit_macro(args,data)
2327 self._edit_macro(args,data)
2329 return
2328 return
2330
2329
2331 # For objects, try to edit the file where they are defined
2330 # For objects, try to edit the file where they are defined
2332 try:
2331 try:
2333 filename = inspect.getabsfile(data)
2332 filename = inspect.getabsfile(data)
2334 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2333 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2335 # class created by %edit? Try to find source
2334 # class created by %edit? Try to find source
2336 # by looking for method definitions instead, the
2335 # by looking for method definitions instead, the
2337 # __module__ in those classes is FakeModule.
2336 # __module__ in those classes is FakeModule.
2338 attrs = [getattr(data, aname) for aname in dir(data)]
2337 attrs = [getattr(data, aname) for aname in dir(data)]
2339 for attr in attrs:
2338 for attr in attrs:
2340 if not inspect.ismethod(attr):
2339 if not inspect.ismethod(attr):
2341 continue
2340 continue
2342 filename = inspect.getabsfile(attr)
2341 filename = inspect.getabsfile(attr)
2343 if filename and 'fakemodule' not in filename.lower():
2342 if filename and 'fakemodule' not in filename.lower():
2344 # change the attribute to be the edit target instead
2343 # change the attribute to be the edit target instead
2345 data = attr
2344 data = attr
2346 break
2345 break
2347
2346
2348 datafile = 1
2347 datafile = 1
2349 except TypeError:
2348 except TypeError:
2350 filename = make_filename(args)
2349 filename = make_filename(args)
2351 datafile = 1
2350 datafile = 1
2352 warn('Could not find file where `%s` is defined.\n'
2351 warn('Could not find file where `%s` is defined.\n'
2353 'Opening a file named `%s`' % (args,filename))
2352 'Opening a file named `%s`' % (args,filename))
2354 # Now, make sure we can actually read the source (if it was in
2353 # Now, make sure we can actually read the source (if it was in
2355 # a temp file it's gone by now).
2354 # a temp file it's gone by now).
2356 if datafile:
2355 if datafile:
2357 try:
2356 try:
2358 if lineno is None:
2357 if lineno is None:
2359 lineno = inspect.getsourcelines(data)[1]
2358 lineno = inspect.getsourcelines(data)[1]
2360 except IOError:
2359 except IOError:
2361 filename = make_filename(args)
2360 filename = make_filename(args)
2362 if filename is None:
2361 if filename is None:
2363 warn('The file `%s` where `%s` was defined cannot '
2362 warn('The file `%s` where `%s` was defined cannot '
2364 'be read.' % (filename,data))
2363 'be read.' % (filename,data))
2365 return
2364 return
2366 use_temp = False
2365 use_temp = False
2367
2366
2368 if use_temp:
2367 if use_temp:
2369 filename = self.shell.mktempfile(data)
2368 filename = self.shell.mktempfile(data)
2370 print 'IPython will make a temporary file named:',filename
2369 print 'IPython will make a temporary file named:',filename
2371
2370
2372 # do actual editing here
2371 # do actual editing here
2373 print 'Editing...',
2372 print 'Editing...',
2374 sys.stdout.flush()
2373 sys.stdout.flush()
2375 try:
2374 try:
2376 # Quote filenames that may have spaces in them
2375 # Quote filenames that may have spaces in them
2377 if ' ' in filename:
2376 if ' ' in filename:
2378 filename = "%s" % filename
2377 filename = "%s" % filename
2379 self.shell.hooks.editor(filename,lineno)
2378 self.shell.hooks.editor(filename,lineno)
2380 except TryNext:
2379 except TryNext:
2381 warn('Could not open editor')
2380 warn('Could not open editor')
2382 return
2381 return
2383
2382
2384 # XXX TODO: should this be generalized for all string vars?
2383 # XXX TODO: should this be generalized for all string vars?
2385 # For now, this is special-cased to blocks created by cpaste
2384 # For now, this is special-cased to blocks created by cpaste
2386 if args.strip() == 'pasted_block':
2385 if args.strip() == 'pasted_block':
2387 self.shell.user_ns['pasted_block'] = file_read(filename)
2386 self.shell.user_ns['pasted_block'] = file_read(filename)
2388
2387
2389 if 'x' in opts: # -x prevents actual execution
2388 if 'x' in opts: # -x prevents actual execution
2390 print
2389 print
2391 else:
2390 else:
2392 print 'done. Executing edited code...'
2391 print 'done. Executing edited code...'
2393 if opts_raw:
2392 if opts_raw:
2394 self.shell.run_cell(file_read(filename),
2393 self.shell.run_cell(file_read(filename),
2395 store_history=False)
2394 store_history=False)
2396 else:
2395 else:
2397 self.shell.safe_execfile(filename,self.shell.user_ns,
2396 self.shell.safe_execfile(filename,self.shell.user_ns,
2398 self.shell.user_ns)
2397 self.shell.user_ns)
2399
2398
2400
2399
2401 if use_temp:
2400 if use_temp:
2402 try:
2401 try:
2403 return open(filename).read()
2402 return open(filename).read()
2404 except IOError,msg:
2403 except IOError,msg:
2405 if msg.filename == filename:
2404 if msg.filename == filename:
2406 warn('File not found. Did you forget to save?')
2405 warn('File not found. Did you forget to save?')
2407 return
2406 return
2408 else:
2407 else:
2409 self.shell.showtraceback()
2408 self.shell.showtraceback()
2410
2409
2411 def magic_xmode(self,parameter_s = ''):
2410 def magic_xmode(self,parameter_s = ''):
2412 """Switch modes for the exception handlers.
2411 """Switch modes for the exception handlers.
2413
2412
2414 Valid modes: Plain, Context and Verbose.
2413 Valid modes: Plain, Context and Verbose.
2415
2414
2416 If called without arguments, acts as a toggle."""
2415 If called without arguments, acts as a toggle."""
2417
2416
2418 def xmode_switch_err(name):
2417 def xmode_switch_err(name):
2419 warn('Error changing %s exception modes.\n%s' %
2418 warn('Error changing %s exception modes.\n%s' %
2420 (name,sys.exc_info()[1]))
2419 (name,sys.exc_info()[1]))
2421
2420
2422 shell = self.shell
2421 shell = self.shell
2423 new_mode = parameter_s.strip().capitalize()
2422 new_mode = parameter_s.strip().capitalize()
2424 try:
2423 try:
2425 shell.InteractiveTB.set_mode(mode=new_mode)
2424 shell.InteractiveTB.set_mode(mode=new_mode)
2426 print 'Exception reporting mode:',shell.InteractiveTB.mode
2425 print 'Exception reporting mode:',shell.InteractiveTB.mode
2427 except:
2426 except:
2428 xmode_switch_err('user')
2427 xmode_switch_err('user')
2429
2428
2430 def magic_colors(self,parameter_s = ''):
2429 def magic_colors(self,parameter_s = ''):
2431 """Switch color scheme for prompts, info system and exception handlers.
2430 """Switch color scheme for prompts, info system and exception handlers.
2432
2431
2433 Currently implemented schemes: NoColor, Linux, LightBG.
2432 Currently implemented schemes: NoColor, Linux, LightBG.
2434
2433
2435 Color scheme names are not case-sensitive.
2434 Color scheme names are not case-sensitive.
2436
2435
2437 Examples
2436 Examples
2438 --------
2437 --------
2439 To get a plain black and white terminal::
2438 To get a plain black and white terminal::
2440
2439
2441 %colors nocolor
2440 %colors nocolor
2442 """
2441 """
2443
2442
2444 def color_switch_err(name):
2443 def color_switch_err(name):
2445 warn('Error changing %s color schemes.\n%s' %
2444 warn('Error changing %s color schemes.\n%s' %
2446 (name,sys.exc_info()[1]))
2445 (name,sys.exc_info()[1]))
2447
2446
2448
2447
2449 new_scheme = parameter_s.strip()
2448 new_scheme = parameter_s.strip()
2450 if not new_scheme:
2449 if not new_scheme:
2451 raise UsageError(
2450 raise UsageError(
2452 "%colors: you must specify a color scheme. See '%colors?'")
2451 "%colors: you must specify a color scheme. See '%colors?'")
2453 return
2452 return
2454 # local shortcut
2453 # local shortcut
2455 shell = self.shell
2454 shell = self.shell
2456
2455
2457 import IPython.utils.rlineimpl as readline
2456 import IPython.utils.rlineimpl as readline
2458
2457
2459 if not readline.have_readline and sys.platform == "win32":
2458 if not readline.have_readline and sys.platform == "win32":
2460 msg = """\
2459 msg = """\
2461 Proper color support under MS Windows requires the pyreadline library.
2460 Proper color support under MS Windows requires the pyreadline library.
2462 You can find it at:
2461 You can find it at:
2463 http://ipython.scipy.org/moin/PyReadline/Intro
2462 http://ipython.scipy.org/moin/PyReadline/Intro
2464 Gary's readline needs the ctypes module, from:
2463 Gary's readline needs the ctypes module, from:
2465 http://starship.python.net/crew/theller/ctypes
2464 http://starship.python.net/crew/theller/ctypes
2466 (Note that ctypes is already part of Python versions 2.5 and newer).
2465 (Note that ctypes is already part of Python versions 2.5 and newer).
2467
2466
2468 Defaulting color scheme to 'NoColor'"""
2467 Defaulting color scheme to 'NoColor'"""
2469 new_scheme = 'NoColor'
2468 new_scheme = 'NoColor'
2470 warn(msg)
2469 warn(msg)
2471
2470
2472 # readline option is 0
2471 # readline option is 0
2473 if not shell.has_readline:
2472 if not shell.has_readline:
2474 new_scheme = 'NoColor'
2473 new_scheme = 'NoColor'
2475
2474
2476 # Set prompt colors
2475 # Set prompt colors
2477 try:
2476 try:
2478 shell.displayhook.set_colors(new_scheme)
2477 shell.displayhook.set_colors(new_scheme)
2479 except:
2478 except:
2480 color_switch_err('prompt')
2479 color_switch_err('prompt')
2481 else:
2480 else:
2482 shell.colors = \
2481 shell.colors = \
2483 shell.displayhook.color_table.active_scheme_name
2482 shell.displayhook.color_table.active_scheme_name
2484 # Set exception colors
2483 # Set exception colors
2485 try:
2484 try:
2486 shell.InteractiveTB.set_colors(scheme = new_scheme)
2485 shell.InteractiveTB.set_colors(scheme = new_scheme)
2487 shell.SyntaxTB.set_colors(scheme = new_scheme)
2486 shell.SyntaxTB.set_colors(scheme = new_scheme)
2488 except:
2487 except:
2489 color_switch_err('exception')
2488 color_switch_err('exception')
2490
2489
2491 # Set info (for 'object?') colors
2490 # Set info (for 'object?') colors
2492 if shell.color_info:
2491 if shell.color_info:
2493 try:
2492 try:
2494 shell.inspector.set_active_scheme(new_scheme)
2493 shell.inspector.set_active_scheme(new_scheme)
2495 except:
2494 except:
2496 color_switch_err('object inspector')
2495 color_switch_err('object inspector')
2497 else:
2496 else:
2498 shell.inspector.set_active_scheme('NoColor')
2497 shell.inspector.set_active_scheme('NoColor')
2499
2498
2500 def magic_pprint(self, parameter_s=''):
2499 def magic_pprint(self, parameter_s=''):
2501 """Toggle pretty printing on/off."""
2500 """Toggle pretty printing on/off."""
2502 ptformatter = self.shell.display_formatter.formatters['text/plain']
2501 ptformatter = self.shell.display_formatter.formatters['text/plain']
2503 ptformatter.pprint = bool(1 - ptformatter.pprint)
2502 ptformatter.pprint = bool(1 - ptformatter.pprint)
2504 print 'Pretty printing has been turned', \
2503 print 'Pretty printing has been turned', \
2505 ['OFF','ON'][ptformatter.pprint]
2504 ['OFF','ON'][ptformatter.pprint]
2506
2505
2507 #......................................................................
2506 #......................................................................
2508 # Functions to implement unix shell-type things
2507 # Functions to implement unix shell-type things
2509
2508
2510 @testdec.skip_doctest
2509 @testdec.skip_doctest
2511 def magic_alias(self, parameter_s = ''):
2510 def magic_alias(self, parameter_s = ''):
2512 """Define an alias for a system command.
2511 """Define an alias for a system command.
2513
2512
2514 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2513 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2515
2514
2516 Then, typing 'alias_name params' will execute the system command 'cmd
2515 Then, typing 'alias_name params' will execute the system command 'cmd
2517 params' (from your underlying operating system).
2516 params' (from your underlying operating system).
2518
2517
2519 Aliases have lower precedence than magic functions and Python normal
2518 Aliases have lower precedence than magic functions and Python normal
2520 variables, so if 'foo' is both a Python variable and an alias, the
2519 variables, so if 'foo' is both a Python variable and an alias, the
2521 alias can not be executed until 'del foo' removes the Python variable.
2520 alias can not be executed until 'del foo' removes the Python variable.
2522
2521
2523 You can use the %l specifier in an alias definition to represent the
2522 You can use the %l specifier in an alias definition to represent the
2524 whole line when the alias is called. For example:
2523 whole line when the alias is called. For example:
2525
2524
2526 In [2]: alias bracket echo "Input in brackets: <%l>"
2525 In [2]: alias bracket echo "Input in brackets: <%l>"
2527 In [3]: bracket hello world
2526 In [3]: bracket hello world
2528 Input in brackets: <hello world>
2527 Input in brackets: <hello world>
2529
2528
2530 You can also define aliases with parameters using %s specifiers (one
2529 You can also define aliases with parameters using %s specifiers (one
2531 per parameter):
2530 per parameter):
2532
2531
2533 In [1]: alias parts echo first %s second %s
2532 In [1]: alias parts echo first %s second %s
2534 In [2]: %parts A B
2533 In [2]: %parts A B
2535 first A second B
2534 first A second B
2536 In [3]: %parts A
2535 In [3]: %parts A
2537 Incorrect number of arguments: 2 expected.
2536 Incorrect number of arguments: 2 expected.
2538 parts is an alias to: 'echo first %s second %s'
2537 parts is an alias to: 'echo first %s second %s'
2539
2538
2540 Note that %l and %s are mutually exclusive. You can only use one or
2539 Note that %l and %s are mutually exclusive. You can only use one or
2541 the other in your aliases.
2540 the other in your aliases.
2542
2541
2543 Aliases expand Python variables just like system calls using ! or !!
2542 Aliases expand Python variables just like system calls using ! or !!
2544 do: all expressions prefixed with '$' get expanded. For details of
2543 do: all expressions prefixed with '$' get expanded. For details of
2545 the semantic rules, see PEP-215:
2544 the semantic rules, see PEP-215:
2546 http://www.python.org/peps/pep-0215.html. This is the library used by
2545 http://www.python.org/peps/pep-0215.html. This is the library used by
2547 IPython for variable expansion. If you want to access a true shell
2546 IPython for variable expansion. If you want to access a true shell
2548 variable, an extra $ is necessary to prevent its expansion by IPython:
2547 variable, an extra $ is necessary to prevent its expansion by IPython:
2549
2548
2550 In [6]: alias show echo
2549 In [6]: alias show echo
2551 In [7]: PATH='A Python string'
2550 In [7]: PATH='A Python string'
2552 In [8]: show $PATH
2551 In [8]: show $PATH
2553 A Python string
2552 A Python string
2554 In [9]: show $$PATH
2553 In [9]: show $$PATH
2555 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2554 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2556
2555
2557 You can use the alias facility to acess all of $PATH. See the %rehash
2556 You can use the alias facility to acess all of $PATH. See the %rehash
2558 and %rehashx functions, which automatically create aliases for the
2557 and %rehashx functions, which automatically create aliases for the
2559 contents of your $PATH.
2558 contents of your $PATH.
2560
2559
2561 If called with no parameters, %alias prints the current alias table."""
2560 If called with no parameters, %alias prints the current alias table."""
2562
2561
2563 par = parameter_s.strip()
2562 par = parameter_s.strip()
2564 if not par:
2563 if not par:
2565 stored = self.db.get('stored_aliases', {} )
2564 stored = self.db.get('stored_aliases', {} )
2566 aliases = sorted(self.shell.alias_manager.aliases)
2565 aliases = sorted(self.shell.alias_manager.aliases)
2567 # for k, v in stored:
2566 # for k, v in stored:
2568 # atab.append(k, v[0])
2567 # atab.append(k, v[0])
2569
2568
2570 print "Total number of aliases:", len(aliases)
2569 print "Total number of aliases:", len(aliases)
2571 sys.stdout.flush()
2570 sys.stdout.flush()
2572 return aliases
2571 return aliases
2573
2572
2574 # Now try to define a new one
2573 # Now try to define a new one
2575 try:
2574 try:
2576 alias,cmd = par.split(None, 1)
2575 alias,cmd = par.split(None, 1)
2577 except:
2576 except:
2578 print oinspect.getdoc(self.magic_alias)
2577 print oinspect.getdoc(self.magic_alias)
2579 else:
2578 else:
2580 self.shell.alias_manager.soft_define_alias(alias, cmd)
2579 self.shell.alias_manager.soft_define_alias(alias, cmd)
2581 # end magic_alias
2580 # end magic_alias
2582
2581
2583 def magic_unalias(self, parameter_s = ''):
2582 def magic_unalias(self, parameter_s = ''):
2584 """Remove an alias"""
2583 """Remove an alias"""
2585
2584
2586 aname = parameter_s.strip()
2585 aname = parameter_s.strip()
2587 self.shell.alias_manager.undefine_alias(aname)
2586 self.shell.alias_manager.undefine_alias(aname)
2588 stored = self.db.get('stored_aliases', {} )
2587 stored = self.db.get('stored_aliases', {} )
2589 if aname in stored:
2588 if aname in stored:
2590 print "Removing %stored alias",aname
2589 print "Removing %stored alias",aname
2591 del stored[aname]
2590 del stored[aname]
2592 self.db['stored_aliases'] = stored
2591 self.db['stored_aliases'] = stored
2593
2592
2594 def magic_rehashx(self, parameter_s = ''):
2593 def magic_rehashx(self, parameter_s = ''):
2595 """Update the alias table with all executable files in $PATH.
2594 """Update the alias table with all executable files in $PATH.
2596
2595
2597 This version explicitly checks that every entry in $PATH is a file
2596 This version explicitly checks that every entry in $PATH is a file
2598 with execute access (os.X_OK), so it is much slower than %rehash.
2597 with execute access (os.X_OK), so it is much slower than %rehash.
2599
2598
2600 Under Windows, it checks executability as a match agains a
2599 Under Windows, it checks executability as a match agains a
2601 '|'-separated string of extensions, stored in the IPython config
2600 '|'-separated string of extensions, stored in the IPython config
2602 variable win_exec_ext. This defaults to 'exe|com|bat'.
2601 variable win_exec_ext. This defaults to 'exe|com|bat'.
2603
2602
2604 This function also resets the root module cache of module completer,
2603 This function also resets the root module cache of module completer,
2605 used on slow filesystems.
2604 used on slow filesystems.
2606 """
2605 """
2607 from IPython.core.alias import InvalidAliasError
2606 from IPython.core.alias import InvalidAliasError
2608
2607
2609 # for the benefit of module completer in ipy_completers.py
2608 # for the benefit of module completer in ipy_completers.py
2610 del self.db['rootmodules']
2609 del self.db['rootmodules']
2611
2610
2612 path = [os.path.abspath(os.path.expanduser(p)) for p in
2611 path = [os.path.abspath(os.path.expanduser(p)) for p in
2613 os.environ.get('PATH','').split(os.pathsep)]
2612 os.environ.get('PATH','').split(os.pathsep)]
2614 path = filter(os.path.isdir,path)
2613 path = filter(os.path.isdir,path)
2615
2614
2616 syscmdlist = []
2615 syscmdlist = []
2617 # Now define isexec in a cross platform manner.
2616 # Now define isexec in a cross platform manner.
2618 if os.name == 'posix':
2617 if os.name == 'posix':
2619 isexec = lambda fname:os.path.isfile(fname) and \
2618 isexec = lambda fname:os.path.isfile(fname) and \
2620 os.access(fname,os.X_OK)
2619 os.access(fname,os.X_OK)
2621 else:
2620 else:
2622 try:
2621 try:
2623 winext = os.environ['pathext'].replace(';','|').replace('.','')
2622 winext = os.environ['pathext'].replace(';','|').replace('.','')
2624 except KeyError:
2623 except KeyError:
2625 winext = 'exe|com|bat|py'
2624 winext = 'exe|com|bat|py'
2626 if 'py' not in winext:
2625 if 'py' not in winext:
2627 winext += '|py'
2626 winext += '|py'
2628 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2627 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2629 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2628 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2630 savedir = os.getcwd()
2629 savedir = os.getcwd()
2631
2630
2632 # Now walk the paths looking for executables to alias.
2631 # Now walk the paths looking for executables to alias.
2633 try:
2632 try:
2634 # write the whole loop for posix/Windows so we don't have an if in
2633 # write the whole loop for posix/Windows so we don't have an if in
2635 # the innermost part
2634 # the innermost part
2636 if os.name == 'posix':
2635 if os.name == 'posix':
2637 for pdir in path:
2636 for pdir in path:
2638 os.chdir(pdir)
2637 os.chdir(pdir)
2639 for ff in os.listdir(pdir):
2638 for ff in os.listdir(pdir):
2640 if isexec(ff):
2639 if isexec(ff):
2641 try:
2640 try:
2642 # Removes dots from the name since ipython
2641 # Removes dots from the name since ipython
2643 # will assume names with dots to be python.
2642 # will assume names with dots to be python.
2644 self.shell.alias_manager.define_alias(
2643 self.shell.alias_manager.define_alias(
2645 ff.replace('.',''), ff)
2644 ff.replace('.',''), ff)
2646 except InvalidAliasError:
2645 except InvalidAliasError:
2647 pass
2646 pass
2648 else:
2647 else:
2649 syscmdlist.append(ff)
2648 syscmdlist.append(ff)
2650 else:
2649 else:
2651 no_alias = self.shell.alias_manager.no_alias
2650 no_alias = self.shell.alias_manager.no_alias
2652 for pdir in path:
2651 for pdir in path:
2653 os.chdir(pdir)
2652 os.chdir(pdir)
2654 for ff in os.listdir(pdir):
2653 for ff in os.listdir(pdir):
2655 base, ext = os.path.splitext(ff)
2654 base, ext = os.path.splitext(ff)
2656 if isexec(ff) and base.lower() not in no_alias:
2655 if isexec(ff) and base.lower() not in no_alias:
2657 if ext.lower() == '.exe':
2656 if ext.lower() == '.exe':
2658 ff = base
2657 ff = base
2659 try:
2658 try:
2660 # Removes dots from the name since ipython
2659 # Removes dots from the name since ipython
2661 # will assume names with dots to be python.
2660 # will assume names with dots to be python.
2662 self.shell.alias_manager.define_alias(
2661 self.shell.alias_manager.define_alias(
2663 base.lower().replace('.',''), ff)
2662 base.lower().replace('.',''), ff)
2664 except InvalidAliasError:
2663 except InvalidAliasError:
2665 pass
2664 pass
2666 syscmdlist.append(ff)
2665 syscmdlist.append(ff)
2667 db = self.db
2666 db = self.db
2668 db['syscmdlist'] = syscmdlist
2667 db['syscmdlist'] = syscmdlist
2669 finally:
2668 finally:
2670 os.chdir(savedir)
2669 os.chdir(savedir)
2671
2670
2672 @testdec.skip_doctest
2671 @testdec.skip_doctest
2673 def magic_pwd(self, parameter_s = ''):
2672 def magic_pwd(self, parameter_s = ''):
2674 """Return the current working directory path.
2673 """Return the current working directory path.
2675
2674
2676 Examples
2675 Examples
2677 --------
2676 --------
2678 ::
2677 ::
2679
2678
2680 In [9]: pwd
2679 In [9]: pwd
2681 Out[9]: '/home/tsuser/sprint/ipython'
2680 Out[9]: '/home/tsuser/sprint/ipython'
2682 """
2681 """
2683 return os.getcwd()
2682 return os.getcwd()
2684
2683
2685 @testdec.skip_doctest
2684 @testdec.skip_doctest
2686 def magic_cd(self, parameter_s=''):
2685 def magic_cd(self, parameter_s=''):
2687 """Change the current working directory.
2686 """Change the current working directory.
2688
2687
2689 This command automatically maintains an internal list of directories
2688 This command automatically maintains an internal list of directories
2690 you visit during your IPython session, in the variable _dh. The
2689 you visit during your IPython session, in the variable _dh. The
2691 command %dhist shows this history nicely formatted. You can also
2690 command %dhist shows this history nicely formatted. You can also
2692 do 'cd -<tab>' to see directory history conveniently.
2691 do 'cd -<tab>' to see directory history conveniently.
2693
2692
2694 Usage:
2693 Usage:
2695
2694
2696 cd 'dir': changes to directory 'dir'.
2695 cd 'dir': changes to directory 'dir'.
2697
2696
2698 cd -: changes to the last visited directory.
2697 cd -: changes to the last visited directory.
2699
2698
2700 cd -<n>: changes to the n-th directory in the directory history.
2699 cd -<n>: changes to the n-th directory in the directory history.
2701
2700
2702 cd --foo: change to directory that matches 'foo' in history
2701 cd --foo: change to directory that matches 'foo' in history
2703
2702
2704 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2703 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2705 (note: cd <bookmark_name> is enough if there is no
2704 (note: cd <bookmark_name> is enough if there is no
2706 directory <bookmark_name>, but a bookmark with the name exists.)
2705 directory <bookmark_name>, but a bookmark with the name exists.)
2707 'cd -b <tab>' allows you to tab-complete bookmark names.
2706 'cd -b <tab>' allows you to tab-complete bookmark names.
2708
2707
2709 Options:
2708 Options:
2710
2709
2711 -q: quiet. Do not print the working directory after the cd command is
2710 -q: quiet. Do not print the working directory after the cd command is
2712 executed. By default IPython's cd command does print this directory,
2711 executed. By default IPython's cd command does print this directory,
2713 since the default prompts do not display path information.
2712 since the default prompts do not display path information.
2714
2713
2715 Note that !cd doesn't work for this purpose because the shell where
2714 Note that !cd doesn't work for this purpose because the shell where
2716 !command runs is immediately discarded after executing 'command'.
2715 !command runs is immediately discarded after executing 'command'.
2717
2716
2718 Examples
2717 Examples
2719 --------
2718 --------
2720 ::
2719 ::
2721
2720
2722 In [10]: cd parent/child
2721 In [10]: cd parent/child
2723 /home/tsuser/parent/child
2722 /home/tsuser/parent/child
2724 """
2723 """
2725
2724
2726 parameter_s = parameter_s.strip()
2725 parameter_s = parameter_s.strip()
2727 #bkms = self.shell.persist.get("bookmarks",{})
2726 #bkms = self.shell.persist.get("bookmarks",{})
2728
2727
2729 oldcwd = os.getcwd()
2728 oldcwd = os.getcwd()
2730 numcd = re.match(r'(-)(\d+)$',parameter_s)
2729 numcd = re.match(r'(-)(\d+)$',parameter_s)
2731 # jump in directory history by number
2730 # jump in directory history by number
2732 if numcd:
2731 if numcd:
2733 nn = int(numcd.group(2))
2732 nn = int(numcd.group(2))
2734 try:
2733 try:
2735 ps = self.shell.user_ns['_dh'][nn]
2734 ps = self.shell.user_ns['_dh'][nn]
2736 except IndexError:
2735 except IndexError:
2737 print 'The requested directory does not exist in history.'
2736 print 'The requested directory does not exist in history.'
2738 return
2737 return
2739 else:
2738 else:
2740 opts = {}
2739 opts = {}
2741 elif parameter_s.startswith('--'):
2740 elif parameter_s.startswith('--'):
2742 ps = None
2741 ps = None
2743 fallback = None
2742 fallback = None
2744 pat = parameter_s[2:]
2743 pat = parameter_s[2:]
2745 dh = self.shell.user_ns['_dh']
2744 dh = self.shell.user_ns['_dh']
2746 # first search only by basename (last component)
2745 # first search only by basename (last component)
2747 for ent in reversed(dh):
2746 for ent in reversed(dh):
2748 if pat in os.path.basename(ent) and os.path.isdir(ent):
2747 if pat in os.path.basename(ent) and os.path.isdir(ent):
2749 ps = ent
2748 ps = ent
2750 break
2749 break
2751
2750
2752 if fallback is None and pat in ent and os.path.isdir(ent):
2751 if fallback is None and pat in ent and os.path.isdir(ent):
2753 fallback = ent
2752 fallback = ent
2754
2753
2755 # if we have no last part match, pick the first full path match
2754 # if we have no last part match, pick the first full path match
2756 if ps is None:
2755 if ps is None:
2757 ps = fallback
2756 ps = fallback
2758
2757
2759 if ps is None:
2758 if ps is None:
2760 print "No matching entry in directory history"
2759 print "No matching entry in directory history"
2761 return
2760 return
2762 else:
2761 else:
2763 opts = {}
2762 opts = {}
2764
2763
2765
2764
2766 else:
2765 else:
2767 #turn all non-space-escaping backslashes to slashes,
2766 #turn all non-space-escaping backslashes to slashes,
2768 # for c:\windows\directory\names\
2767 # for c:\windows\directory\names\
2769 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2768 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2770 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2769 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2771 # jump to previous
2770 # jump to previous
2772 if ps == '-':
2771 if ps == '-':
2773 try:
2772 try:
2774 ps = self.shell.user_ns['_dh'][-2]
2773 ps = self.shell.user_ns['_dh'][-2]
2775 except IndexError:
2774 except IndexError:
2776 raise UsageError('%cd -: No previous directory to change to.')
2775 raise UsageError('%cd -: No previous directory to change to.')
2777 # jump to bookmark if needed
2776 # jump to bookmark if needed
2778 else:
2777 else:
2779 if not os.path.isdir(ps) or opts.has_key('b'):
2778 if not os.path.isdir(ps) or opts.has_key('b'):
2780 bkms = self.db.get('bookmarks', {})
2779 bkms = self.db.get('bookmarks', {})
2781
2780
2782 if bkms.has_key(ps):
2781 if bkms.has_key(ps):
2783 target = bkms[ps]
2782 target = bkms[ps]
2784 print '(bookmark:%s) -> %s' % (ps,target)
2783 print '(bookmark:%s) -> %s' % (ps,target)
2785 ps = target
2784 ps = target
2786 else:
2785 else:
2787 if opts.has_key('b'):
2786 if opts.has_key('b'):
2788 raise UsageError("Bookmark '%s' not found. "
2787 raise UsageError("Bookmark '%s' not found. "
2789 "Use '%%bookmark -l' to see your bookmarks." % ps)
2788 "Use '%%bookmark -l' to see your bookmarks." % ps)
2790
2789
2791 # at this point ps should point to the target dir
2790 # at this point ps should point to the target dir
2792 if ps:
2791 if ps:
2793 try:
2792 try:
2794 os.chdir(os.path.expanduser(ps))
2793 os.chdir(os.path.expanduser(ps))
2795 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2794 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2796 set_term_title('IPython: ' + abbrev_cwd())
2795 set_term_title('IPython: ' + abbrev_cwd())
2797 except OSError:
2796 except OSError:
2798 print sys.exc_info()[1]
2797 print sys.exc_info()[1]
2799 else:
2798 else:
2800 cwd = os.getcwd()
2799 cwd = os.getcwd()
2801 dhist = self.shell.user_ns['_dh']
2800 dhist = self.shell.user_ns['_dh']
2802 if oldcwd != cwd:
2801 if oldcwd != cwd:
2803 dhist.append(cwd)
2802 dhist.append(cwd)
2804 self.db['dhist'] = compress_dhist(dhist)[-100:]
2803 self.db['dhist'] = compress_dhist(dhist)[-100:]
2805
2804
2806 else:
2805 else:
2807 os.chdir(self.shell.home_dir)
2806 os.chdir(self.shell.home_dir)
2808 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2807 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2809 set_term_title('IPython: ' + '~')
2808 set_term_title('IPython: ' + '~')
2810 cwd = os.getcwd()
2809 cwd = os.getcwd()
2811 dhist = self.shell.user_ns['_dh']
2810 dhist = self.shell.user_ns['_dh']
2812
2811
2813 if oldcwd != cwd:
2812 if oldcwd != cwd:
2814 dhist.append(cwd)
2813 dhist.append(cwd)
2815 self.db['dhist'] = compress_dhist(dhist)[-100:]
2814 self.db['dhist'] = compress_dhist(dhist)[-100:]
2816 if not 'q' in opts and self.shell.user_ns['_dh']:
2815 if not 'q' in opts and self.shell.user_ns['_dh']:
2817 print self.shell.user_ns['_dh'][-1]
2816 print self.shell.user_ns['_dh'][-1]
2818
2817
2819
2818
2820 def magic_env(self, parameter_s=''):
2819 def magic_env(self, parameter_s=''):
2821 """List environment variables."""
2820 """List environment variables."""
2822
2821
2823 return os.environ.data
2822 return os.environ.data
2824
2823
2825 def magic_pushd(self, parameter_s=''):
2824 def magic_pushd(self, parameter_s=''):
2826 """Place the current dir on stack and change directory.
2825 """Place the current dir on stack and change directory.
2827
2826
2828 Usage:\\
2827 Usage:\\
2829 %pushd ['dirname']
2828 %pushd ['dirname']
2830 """
2829 """
2831
2830
2832 dir_s = self.shell.dir_stack
2831 dir_s = self.shell.dir_stack
2833 tgt = os.path.expanduser(parameter_s)
2832 tgt = os.path.expanduser(parameter_s)
2834 cwd = os.getcwd().replace(self.home_dir,'~')
2833 cwd = os.getcwd().replace(self.home_dir,'~')
2835 if tgt:
2834 if tgt:
2836 self.magic_cd(parameter_s)
2835 self.magic_cd(parameter_s)
2837 dir_s.insert(0,cwd)
2836 dir_s.insert(0,cwd)
2838 return self.magic_dirs()
2837 return self.magic_dirs()
2839
2838
2840 def magic_popd(self, parameter_s=''):
2839 def magic_popd(self, parameter_s=''):
2841 """Change to directory popped off the top of the stack.
2840 """Change to directory popped off the top of the stack.
2842 """
2841 """
2843 if not self.shell.dir_stack:
2842 if not self.shell.dir_stack:
2844 raise UsageError("%popd on empty stack")
2843 raise UsageError("%popd on empty stack")
2845 top = self.shell.dir_stack.pop(0)
2844 top = self.shell.dir_stack.pop(0)
2846 self.magic_cd(top)
2845 self.magic_cd(top)
2847 print "popd ->",top
2846 print "popd ->",top
2848
2847
2849 def magic_dirs(self, parameter_s=''):
2848 def magic_dirs(self, parameter_s=''):
2850 """Return the current directory stack."""
2849 """Return the current directory stack."""
2851
2850
2852 return self.shell.dir_stack
2851 return self.shell.dir_stack
2853
2852
2854 def magic_dhist(self, parameter_s=''):
2853 def magic_dhist(self, parameter_s=''):
2855 """Print your history of visited directories.
2854 """Print your history of visited directories.
2856
2855
2857 %dhist -> print full history\\
2856 %dhist -> print full history\\
2858 %dhist n -> print last n entries only\\
2857 %dhist n -> print last n entries only\\
2859 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2858 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2860
2859
2861 This history is automatically maintained by the %cd command, and
2860 This history is automatically maintained by the %cd command, and
2862 always available as the global list variable _dh. You can use %cd -<n>
2861 always available as the global list variable _dh. You can use %cd -<n>
2863 to go to directory number <n>.
2862 to go to directory number <n>.
2864
2863
2865 Note that most of time, you should view directory history by entering
2864 Note that most of time, you should view directory history by entering
2866 cd -<TAB>.
2865 cd -<TAB>.
2867
2866
2868 """
2867 """
2869
2868
2870 dh = self.shell.user_ns['_dh']
2869 dh = self.shell.user_ns['_dh']
2871 if parameter_s:
2870 if parameter_s:
2872 try:
2871 try:
2873 args = map(int,parameter_s.split())
2872 args = map(int,parameter_s.split())
2874 except:
2873 except:
2875 self.arg_err(Magic.magic_dhist)
2874 self.arg_err(Magic.magic_dhist)
2876 return
2875 return
2877 if len(args) == 1:
2876 if len(args) == 1:
2878 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2877 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2879 elif len(args) == 2:
2878 elif len(args) == 2:
2880 ini,fin = args
2879 ini,fin = args
2881 else:
2880 else:
2882 self.arg_err(Magic.magic_dhist)
2881 self.arg_err(Magic.magic_dhist)
2883 return
2882 return
2884 else:
2883 else:
2885 ini,fin = 0,len(dh)
2884 ini,fin = 0,len(dh)
2886 nlprint(dh,
2885 nlprint(dh,
2887 header = 'Directory history (kept in _dh)',
2886 header = 'Directory history (kept in _dh)',
2888 start=ini,stop=fin)
2887 start=ini,stop=fin)
2889
2888
2890 @testdec.skip_doctest
2889 @testdec.skip_doctest
2891 def magic_sc(self, parameter_s=''):
2890 def magic_sc(self, parameter_s=''):
2892 """Shell capture - execute a shell command and capture its output.
2891 """Shell capture - execute a shell command and capture its output.
2893
2892
2894 DEPRECATED. Suboptimal, retained for backwards compatibility.
2893 DEPRECATED. Suboptimal, retained for backwards compatibility.
2895
2894
2896 You should use the form 'var = !command' instead. Example:
2895 You should use the form 'var = !command' instead. Example:
2897
2896
2898 "%sc -l myfiles = ls ~" should now be written as
2897 "%sc -l myfiles = ls ~" should now be written as
2899
2898
2900 "myfiles = !ls ~"
2899 "myfiles = !ls ~"
2901
2900
2902 myfiles.s, myfiles.l and myfiles.n still apply as documented
2901 myfiles.s, myfiles.l and myfiles.n still apply as documented
2903 below.
2902 below.
2904
2903
2905 --
2904 --
2906 %sc [options] varname=command
2905 %sc [options] varname=command
2907
2906
2908 IPython will run the given command using commands.getoutput(), and
2907 IPython will run the given command using commands.getoutput(), and
2909 will then update the user's interactive namespace with a variable
2908 will then update the user's interactive namespace with a variable
2910 called varname, containing the value of the call. Your command can
2909 called varname, containing the value of the call. Your command can
2911 contain shell wildcards, pipes, etc.
2910 contain shell wildcards, pipes, etc.
2912
2911
2913 The '=' sign in the syntax is mandatory, and the variable name you
2912 The '=' sign in the syntax is mandatory, and the variable name you
2914 supply must follow Python's standard conventions for valid names.
2913 supply must follow Python's standard conventions for valid names.
2915
2914
2916 (A special format without variable name exists for internal use)
2915 (A special format without variable name exists for internal use)
2917
2916
2918 Options:
2917 Options:
2919
2918
2920 -l: list output. Split the output on newlines into a list before
2919 -l: list output. Split the output on newlines into a list before
2921 assigning it to the given variable. By default the output is stored
2920 assigning it to the given variable. By default the output is stored
2922 as a single string.
2921 as a single string.
2923
2922
2924 -v: verbose. Print the contents of the variable.
2923 -v: verbose. Print the contents of the variable.
2925
2924
2926 In most cases you should not need to split as a list, because the
2925 In most cases you should not need to split as a list, because the
2927 returned value is a special type of string which can automatically
2926 returned value is a special type of string which can automatically
2928 provide its contents either as a list (split on newlines) or as a
2927 provide its contents either as a list (split on newlines) or as a
2929 space-separated string. These are convenient, respectively, either
2928 space-separated string. These are convenient, respectively, either
2930 for sequential processing or to be passed to a shell command.
2929 for sequential processing or to be passed to a shell command.
2931
2930
2932 For example:
2931 For example:
2933
2932
2934 # all-random
2933 # all-random
2935
2934
2936 # Capture into variable a
2935 # Capture into variable a
2937 In [1]: sc a=ls *py
2936 In [1]: sc a=ls *py
2938
2937
2939 # a is a string with embedded newlines
2938 # a is a string with embedded newlines
2940 In [2]: a
2939 In [2]: a
2941 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2940 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2942
2941
2943 # which can be seen as a list:
2942 # which can be seen as a list:
2944 In [3]: a.l
2943 In [3]: a.l
2945 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2944 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2946
2945
2947 # or as a whitespace-separated string:
2946 # or as a whitespace-separated string:
2948 In [4]: a.s
2947 In [4]: a.s
2949 Out[4]: 'setup.py win32_manual_post_install.py'
2948 Out[4]: 'setup.py win32_manual_post_install.py'
2950
2949
2951 # a.s is useful to pass as a single command line:
2950 # a.s is useful to pass as a single command line:
2952 In [5]: !wc -l $a.s
2951 In [5]: !wc -l $a.s
2953 146 setup.py
2952 146 setup.py
2954 130 win32_manual_post_install.py
2953 130 win32_manual_post_install.py
2955 276 total
2954 276 total
2956
2955
2957 # while the list form is useful to loop over:
2956 # while the list form is useful to loop over:
2958 In [6]: for f in a.l:
2957 In [6]: for f in a.l:
2959 ...: !wc -l $f
2958 ...: !wc -l $f
2960 ...:
2959 ...:
2961 146 setup.py
2960 146 setup.py
2962 130 win32_manual_post_install.py
2961 130 win32_manual_post_install.py
2963
2962
2964 Similiarly, the lists returned by the -l option are also special, in
2963 Similiarly, the lists returned by the -l option are also special, in
2965 the sense that you can equally invoke the .s attribute on them to
2964 the sense that you can equally invoke the .s attribute on them to
2966 automatically get a whitespace-separated string from their contents:
2965 automatically get a whitespace-separated string from their contents:
2967
2966
2968 In [7]: sc -l b=ls *py
2967 In [7]: sc -l b=ls *py
2969
2968
2970 In [8]: b
2969 In [8]: b
2971 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2970 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2972
2971
2973 In [9]: b.s
2972 In [9]: b.s
2974 Out[9]: 'setup.py win32_manual_post_install.py'
2973 Out[9]: 'setup.py win32_manual_post_install.py'
2975
2974
2976 In summary, both the lists and strings used for ouptut capture have
2975 In summary, both the lists and strings used for ouptut capture have
2977 the following special attributes:
2976 the following special attributes:
2978
2977
2979 .l (or .list) : value as list.
2978 .l (or .list) : value as list.
2980 .n (or .nlstr): value as newline-separated string.
2979 .n (or .nlstr): value as newline-separated string.
2981 .s (or .spstr): value as space-separated string.
2980 .s (or .spstr): value as space-separated string.
2982 """
2981 """
2983
2982
2984 opts,args = self.parse_options(parameter_s,'lv')
2983 opts,args = self.parse_options(parameter_s,'lv')
2985 # Try to get a variable name and command to run
2984 # Try to get a variable name and command to run
2986 try:
2985 try:
2987 # the variable name must be obtained from the parse_options
2986 # the variable name must be obtained from the parse_options
2988 # output, which uses shlex.split to strip options out.
2987 # output, which uses shlex.split to strip options out.
2989 var,_ = args.split('=',1)
2988 var,_ = args.split('=',1)
2990 var = var.strip()
2989 var = var.strip()
2991 # But the the command has to be extracted from the original input
2990 # But the the command has to be extracted from the original input
2992 # parameter_s, not on what parse_options returns, to avoid the
2991 # parameter_s, not on what parse_options returns, to avoid the
2993 # quote stripping which shlex.split performs on it.
2992 # quote stripping which shlex.split performs on it.
2994 _,cmd = parameter_s.split('=',1)
2993 _,cmd = parameter_s.split('=',1)
2995 except ValueError:
2994 except ValueError:
2996 var,cmd = '',''
2995 var,cmd = '',''
2997 # If all looks ok, proceed
2996 # If all looks ok, proceed
2998 split = 'l' in opts
2997 split = 'l' in opts
2999 out = self.shell.getoutput(cmd, split=split)
2998 out = self.shell.getoutput(cmd, split=split)
3000 if opts.has_key('v'):
2999 if opts.has_key('v'):
3001 print '%s ==\n%s' % (var,pformat(out))
3000 print '%s ==\n%s' % (var,pformat(out))
3002 if var:
3001 if var:
3003 self.shell.user_ns.update({var:out})
3002 self.shell.user_ns.update({var:out})
3004 else:
3003 else:
3005 return out
3004 return out
3006
3005
3007 def magic_sx(self, parameter_s=''):
3006 def magic_sx(self, parameter_s=''):
3008 """Shell execute - run a shell command and capture its output.
3007 """Shell execute - run a shell command and capture its output.
3009
3008
3010 %sx command
3009 %sx command
3011
3010
3012 IPython will run the given command using commands.getoutput(), and
3011 IPython will run the given command using commands.getoutput(), and
3013 return the result formatted as a list (split on '\\n'). Since the
3012 return the result formatted as a list (split on '\\n'). Since the
3014 output is _returned_, it will be stored in ipython's regular output
3013 output is _returned_, it will be stored in ipython's regular output
3015 cache Out[N] and in the '_N' automatic variables.
3014 cache Out[N] and in the '_N' automatic variables.
3016
3015
3017 Notes:
3016 Notes:
3018
3017
3019 1) If an input line begins with '!!', then %sx is automatically
3018 1) If an input line begins with '!!', then %sx is automatically
3020 invoked. That is, while:
3019 invoked. That is, while:
3021 !ls
3020 !ls
3022 causes ipython to simply issue system('ls'), typing
3021 causes ipython to simply issue system('ls'), typing
3023 !!ls
3022 !!ls
3024 is a shorthand equivalent to:
3023 is a shorthand equivalent to:
3025 %sx ls
3024 %sx ls
3026
3025
3027 2) %sx differs from %sc in that %sx automatically splits into a list,
3026 2) %sx differs from %sc in that %sx automatically splits into a list,
3028 like '%sc -l'. The reason for this is to make it as easy as possible
3027 like '%sc -l'. The reason for this is to make it as easy as possible
3029 to process line-oriented shell output via further python commands.
3028 to process line-oriented shell output via further python commands.
3030 %sc is meant to provide much finer control, but requires more
3029 %sc is meant to provide much finer control, but requires more
3031 typing.
3030 typing.
3032
3031
3033 3) Just like %sc -l, this is a list with special attributes:
3032 3) Just like %sc -l, this is a list with special attributes:
3034
3033
3035 .l (or .list) : value as list.
3034 .l (or .list) : value as list.
3036 .n (or .nlstr): value as newline-separated string.
3035 .n (or .nlstr): value as newline-separated string.
3037 .s (or .spstr): value as whitespace-separated string.
3036 .s (or .spstr): value as whitespace-separated string.
3038
3037
3039 This is very useful when trying to use such lists as arguments to
3038 This is very useful when trying to use such lists as arguments to
3040 system commands."""
3039 system commands."""
3041
3040
3042 if parameter_s:
3041 if parameter_s:
3043 return self.shell.getoutput(parameter_s)
3042 return self.shell.getoutput(parameter_s)
3044
3043
3045
3044
3046 def magic_bookmark(self, parameter_s=''):
3045 def magic_bookmark(self, parameter_s=''):
3047 """Manage IPython's bookmark system.
3046 """Manage IPython's bookmark system.
3048
3047
3049 %bookmark <name> - set bookmark to current dir
3048 %bookmark <name> - set bookmark to current dir
3050 %bookmark <name> <dir> - set bookmark to <dir>
3049 %bookmark <name> <dir> - set bookmark to <dir>
3051 %bookmark -l - list all bookmarks
3050 %bookmark -l - list all bookmarks
3052 %bookmark -d <name> - remove bookmark
3051 %bookmark -d <name> - remove bookmark
3053 %bookmark -r - remove all bookmarks
3052 %bookmark -r - remove all bookmarks
3054
3053
3055 You can later on access a bookmarked folder with:
3054 You can later on access a bookmarked folder with:
3056 %cd -b <name>
3055 %cd -b <name>
3057 or simply '%cd <name>' if there is no directory called <name> AND
3056 or simply '%cd <name>' if there is no directory called <name> AND
3058 there is such a bookmark defined.
3057 there is such a bookmark defined.
3059
3058
3060 Your bookmarks persist through IPython sessions, but they are
3059 Your bookmarks persist through IPython sessions, but they are
3061 associated with each profile."""
3060 associated with each profile."""
3062
3061
3063 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3062 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3064 if len(args) > 2:
3063 if len(args) > 2:
3065 raise UsageError("%bookmark: too many arguments")
3064 raise UsageError("%bookmark: too many arguments")
3066
3065
3067 bkms = self.db.get('bookmarks',{})
3066 bkms = self.db.get('bookmarks',{})
3068
3067
3069 if opts.has_key('d'):
3068 if opts.has_key('d'):
3070 try:
3069 try:
3071 todel = args[0]
3070 todel = args[0]
3072 except IndexError:
3071 except IndexError:
3073 raise UsageError(
3072 raise UsageError(
3074 "%bookmark -d: must provide a bookmark to delete")
3073 "%bookmark -d: must provide a bookmark to delete")
3075 else:
3074 else:
3076 try:
3075 try:
3077 del bkms[todel]
3076 del bkms[todel]
3078 except KeyError:
3077 except KeyError:
3079 raise UsageError(
3078 raise UsageError(
3080 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3079 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3081
3080
3082 elif opts.has_key('r'):
3081 elif opts.has_key('r'):
3083 bkms = {}
3082 bkms = {}
3084 elif opts.has_key('l'):
3083 elif opts.has_key('l'):
3085 bks = bkms.keys()
3084 bks = bkms.keys()
3086 bks.sort()
3085 bks.sort()
3087 if bks:
3086 if bks:
3088 size = max(map(len,bks))
3087 size = max(map(len,bks))
3089 else:
3088 else:
3090 size = 0
3089 size = 0
3091 fmt = '%-'+str(size)+'s -> %s'
3090 fmt = '%-'+str(size)+'s -> %s'
3092 print 'Current bookmarks:'
3091 print 'Current bookmarks:'
3093 for bk in bks:
3092 for bk in bks:
3094 print fmt % (bk,bkms[bk])
3093 print fmt % (bk,bkms[bk])
3095 else:
3094 else:
3096 if not args:
3095 if not args:
3097 raise UsageError("%bookmark: You must specify the bookmark name")
3096 raise UsageError("%bookmark: You must specify the bookmark name")
3098 elif len(args)==1:
3097 elif len(args)==1:
3099 bkms[args[0]] = os.getcwd()
3098 bkms[args[0]] = os.getcwd()
3100 elif len(args)==2:
3099 elif len(args)==2:
3101 bkms[args[0]] = args[1]
3100 bkms[args[0]] = args[1]
3102 self.db['bookmarks'] = bkms
3101 self.db['bookmarks'] = bkms
3103
3102
3104 def magic_pycat(self, parameter_s=''):
3103 def magic_pycat(self, parameter_s=''):
3105 """Show a syntax-highlighted file through a pager.
3104 """Show a syntax-highlighted file through a pager.
3106
3105
3107 This magic is similar to the cat utility, but it will assume the file
3106 This magic is similar to the cat utility, but it will assume the file
3108 to be Python source and will show it with syntax highlighting. """
3107 to be Python source and will show it with syntax highlighting. """
3109
3108
3110 try:
3109 try:
3111 filename = get_py_filename(parameter_s)
3110 filename = get_py_filename(parameter_s)
3112 cont = file_read(filename)
3111 cont = file_read(filename)
3113 except IOError:
3112 except IOError:
3114 try:
3113 try:
3115 cont = eval(parameter_s,self.user_ns)
3114 cont = eval(parameter_s,self.user_ns)
3116 except NameError:
3115 except NameError:
3117 cont = None
3116 cont = None
3118 if cont is None:
3117 if cont is None:
3119 print "Error: no such file or variable"
3118 print "Error: no such file or variable"
3120 return
3119 return
3121
3120
3122 page.page(self.shell.pycolorize(cont))
3121 page.page(self.shell.pycolorize(cont))
3123
3122
3124 def _rerun_pasted(self):
3123 def _rerun_pasted(self):
3125 """ Rerun a previously pasted command.
3124 """ Rerun a previously pasted command.
3126 """
3125 """
3127 b = self.user_ns.get('pasted_block', None)
3126 b = self.user_ns.get('pasted_block', None)
3128 if b is None:
3127 if b is None:
3129 raise UsageError('No previous pasted block available')
3128 raise UsageError('No previous pasted block available')
3130 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3129 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3131 exec b in self.user_ns
3130 exec b in self.user_ns
3132
3131
3133 def _get_pasted_lines(self, sentinel):
3132 def _get_pasted_lines(self, sentinel):
3134 """ Yield pasted lines until the user enters the given sentinel value.
3133 """ Yield pasted lines until the user enters the given sentinel value.
3135 """
3134 """
3136 from IPython.core import interactiveshell
3135 from IPython.core import interactiveshell
3137 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3136 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3138 while True:
3137 while True:
3139 l = interactiveshell.raw_input_original(':')
3138 l = interactiveshell.raw_input_original(':')
3140 if l == sentinel:
3139 if l == sentinel:
3141 return
3140 return
3142 else:
3141 else:
3143 yield l
3142 yield l
3144
3143
3145 def _strip_pasted_lines_for_code(self, raw_lines):
3144 def _strip_pasted_lines_for_code(self, raw_lines):
3146 """ Strip non-code parts of a sequence of lines to return a block of
3145 """ Strip non-code parts of a sequence of lines to return a block of
3147 code.
3146 code.
3148 """
3147 """
3149 # Regular expressions that declare text we strip from the input:
3148 # Regular expressions that declare text we strip from the input:
3150 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3149 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3151 r'^\s*(\s?>)+', # Python input prompt
3150 r'^\s*(\s?>)+', # Python input prompt
3152 r'^\s*\.{3,}', # Continuation prompts
3151 r'^\s*\.{3,}', # Continuation prompts
3153 r'^\++',
3152 r'^\++',
3154 ]
3153 ]
3155
3154
3156 strip_from_start = map(re.compile,strip_re)
3155 strip_from_start = map(re.compile,strip_re)
3157
3156
3158 lines = []
3157 lines = []
3159 for l in raw_lines:
3158 for l in raw_lines:
3160 for pat in strip_from_start:
3159 for pat in strip_from_start:
3161 l = pat.sub('',l)
3160 l = pat.sub('',l)
3162 lines.append(l)
3161 lines.append(l)
3163
3162
3164 block = "\n".join(lines) + '\n'
3163 block = "\n".join(lines) + '\n'
3165 #print "block:\n",block
3164 #print "block:\n",block
3166 return block
3165 return block
3167
3166
3168 def _execute_block(self, block, par):
3167 def _execute_block(self, block, par):
3169 """ Execute a block, or store it in a variable, per the user's request.
3168 """ Execute a block, or store it in a variable, per the user's request.
3170 """
3169 """
3171 if not par:
3170 if not par:
3172 b = textwrap.dedent(block)
3171 b = textwrap.dedent(block)
3173 self.user_ns['pasted_block'] = b
3172 self.user_ns['pasted_block'] = b
3174 exec b in self.user_ns
3173 exec b in self.user_ns
3175 else:
3174 else:
3176 self.user_ns[par] = SList(block.splitlines())
3175 self.user_ns[par] = SList(block.splitlines())
3177 print "Block assigned to '%s'" % par
3176 print "Block assigned to '%s'" % par
3178
3177
3179 def magic_quickref(self,arg):
3178 def magic_quickref(self,arg):
3180 """ Show a quick reference sheet """
3179 """ Show a quick reference sheet """
3181 import IPython.core.usage
3180 import IPython.core.usage
3182 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3181 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3183
3182
3184 page.page(qr)
3183 page.page(qr)
3185
3184
3186 def magic_doctest_mode(self,parameter_s=''):
3185 def magic_doctest_mode(self,parameter_s=''):
3187 """Toggle doctest mode on and off.
3186 """Toggle doctest mode on and off.
3188
3187
3189 This mode is intended to make IPython behave as much as possible like a
3188 This mode is intended to make IPython behave as much as possible like a
3190 plain Python shell, from the perspective of how its prompts, exceptions
3189 plain Python shell, from the perspective of how its prompts, exceptions
3191 and output look. This makes it easy to copy and paste parts of a
3190 and output look. This makes it easy to copy and paste parts of a
3192 session into doctests. It does so by:
3191 session into doctests. It does so by:
3193
3192
3194 - Changing the prompts to the classic ``>>>`` ones.
3193 - Changing the prompts to the classic ``>>>`` ones.
3195 - Changing the exception reporting mode to 'Plain'.
3194 - Changing the exception reporting mode to 'Plain'.
3196 - Disabling pretty-printing of output.
3195 - Disabling pretty-printing of output.
3197
3196
3198 Note that IPython also supports the pasting of code snippets that have
3197 Note that IPython also supports the pasting of code snippets that have
3199 leading '>>>' and '...' prompts in them. This means that you can paste
3198 leading '>>>' and '...' prompts in them. This means that you can paste
3200 doctests from files or docstrings (even if they have leading
3199 doctests from files or docstrings (even if they have leading
3201 whitespace), and the code will execute correctly. You can then use
3200 whitespace), and the code will execute correctly. You can then use
3202 '%history -t' to see the translated history; this will give you the
3201 '%history -t' to see the translated history; this will give you the
3203 input after removal of all the leading prompts and whitespace, which
3202 input after removal of all the leading prompts and whitespace, which
3204 can be pasted back into an editor.
3203 can be pasted back into an editor.
3205
3204
3206 With these features, you can switch into this mode easily whenever you
3205 With these features, you can switch into this mode easily whenever you
3207 need to do testing and changes to doctests, without having to leave
3206 need to do testing and changes to doctests, without having to leave
3208 your existing IPython session.
3207 your existing IPython session.
3209 """
3208 """
3210
3209
3211 from IPython.utils.ipstruct import Struct
3210 from IPython.utils.ipstruct import Struct
3212
3211
3213 # Shorthands
3212 # Shorthands
3214 shell = self.shell
3213 shell = self.shell
3215 oc = shell.displayhook
3214 oc = shell.displayhook
3216 meta = shell.meta
3215 meta = shell.meta
3217 disp_formatter = self.shell.display_formatter
3216 disp_formatter = self.shell.display_formatter
3218 ptformatter = disp_formatter.formatters['text/plain']
3217 ptformatter = disp_formatter.formatters['text/plain']
3219 # dstore is a data store kept in the instance metadata bag to track any
3218 # dstore is a data store kept in the instance metadata bag to track any
3220 # changes we make, so we can undo them later.
3219 # changes we make, so we can undo them later.
3221 dstore = meta.setdefault('doctest_mode',Struct())
3220 dstore = meta.setdefault('doctest_mode',Struct())
3222 save_dstore = dstore.setdefault
3221 save_dstore = dstore.setdefault
3223
3222
3224 # save a few values we'll need to recover later
3223 # save a few values we'll need to recover later
3225 mode = save_dstore('mode',False)
3224 mode = save_dstore('mode',False)
3226 save_dstore('rc_pprint',ptformatter.pprint)
3225 save_dstore('rc_pprint',ptformatter.pprint)
3227 save_dstore('xmode',shell.InteractiveTB.mode)
3226 save_dstore('xmode',shell.InteractiveTB.mode)
3228 save_dstore('rc_separate_out',shell.separate_out)
3227 save_dstore('rc_separate_out',shell.separate_out)
3229 save_dstore('rc_separate_out2',shell.separate_out2)
3228 save_dstore('rc_separate_out2',shell.separate_out2)
3230 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3229 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3231 save_dstore('rc_separate_in',shell.separate_in)
3230 save_dstore('rc_separate_in',shell.separate_in)
3232 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3231 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3233
3232
3234 if mode == False:
3233 if mode == False:
3235 # turn on
3234 # turn on
3236 oc.prompt1.p_template = '>>> '
3235 oc.prompt1.p_template = '>>> '
3237 oc.prompt2.p_template = '... '
3236 oc.prompt2.p_template = '... '
3238 oc.prompt_out.p_template = ''
3237 oc.prompt_out.p_template = ''
3239
3238
3240 # Prompt separators like plain python
3239 # Prompt separators like plain python
3241 oc.input_sep = oc.prompt1.sep = ''
3240 oc.input_sep = oc.prompt1.sep = ''
3242 oc.output_sep = ''
3241 oc.output_sep = ''
3243 oc.output_sep2 = ''
3242 oc.output_sep2 = ''
3244
3243
3245 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3244 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3246 oc.prompt_out.pad_left = False
3245 oc.prompt_out.pad_left = False
3247
3246
3248 ptformatter.pprint = False
3247 ptformatter.pprint = False
3249 disp_formatter.plain_text_only = True
3248 disp_formatter.plain_text_only = True
3250
3249
3251 shell.magic_xmode('Plain')
3250 shell.magic_xmode('Plain')
3252 else:
3251 else:
3253 # turn off
3252 # turn off
3254 oc.prompt1.p_template = shell.prompt_in1
3253 oc.prompt1.p_template = shell.prompt_in1
3255 oc.prompt2.p_template = shell.prompt_in2
3254 oc.prompt2.p_template = shell.prompt_in2
3256 oc.prompt_out.p_template = shell.prompt_out
3255 oc.prompt_out.p_template = shell.prompt_out
3257
3256
3258 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3257 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3259
3258
3260 oc.output_sep = dstore.rc_separate_out
3259 oc.output_sep = dstore.rc_separate_out
3261 oc.output_sep2 = dstore.rc_separate_out2
3260 oc.output_sep2 = dstore.rc_separate_out2
3262
3261
3263 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3262 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3264 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3263 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3265
3264
3266 ptformatter.pprint = dstore.rc_pprint
3265 ptformatter.pprint = dstore.rc_pprint
3267 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3266 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3268
3267
3269 shell.magic_xmode(dstore.xmode)
3268 shell.magic_xmode(dstore.xmode)
3270
3269
3271 # Store new mode and inform
3270 # Store new mode and inform
3272 dstore.mode = bool(1-int(mode))
3271 dstore.mode = bool(1-int(mode))
3273 mode_label = ['OFF','ON'][dstore.mode]
3272 mode_label = ['OFF','ON'][dstore.mode]
3274 print 'Doctest mode is:', mode_label
3273 print 'Doctest mode is:', mode_label
3275
3274
3276 def magic_gui(self, parameter_s=''):
3275 def magic_gui(self, parameter_s=''):
3277 """Enable or disable IPython GUI event loop integration.
3276 """Enable or disable IPython GUI event loop integration.
3278
3277
3279 %gui [GUINAME]
3278 %gui [GUINAME]
3280
3279
3281 This magic replaces IPython's threaded shells that were activated
3280 This magic replaces IPython's threaded shells that were activated
3282 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3281 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3283 can now be enabled, disabled and swtiched at runtime and keyboard
3282 can now be enabled, disabled and swtiched at runtime and keyboard
3284 interrupts should work without any problems. The following toolkits
3283 interrupts should work without any problems. The following toolkits
3285 are supported: wxPython, PyQt4, PyGTK, and Tk::
3284 are supported: wxPython, PyQt4, PyGTK, and Tk::
3286
3285
3287 %gui wx # enable wxPython event loop integration
3286 %gui wx # enable wxPython event loop integration
3288 %gui qt4|qt # enable PyQt4 event loop integration
3287 %gui qt4|qt # enable PyQt4 event loop integration
3289 %gui gtk # enable PyGTK event loop integration
3288 %gui gtk # enable PyGTK event loop integration
3290 %gui tk # enable Tk event loop integration
3289 %gui tk # enable Tk event loop integration
3291 %gui # disable all event loop integration
3290 %gui # disable all event loop integration
3292
3291
3293 WARNING: after any of these has been called you can simply create
3292 WARNING: after any of these has been called you can simply create
3294 an application object, but DO NOT start the event loop yourself, as
3293 an application object, but DO NOT start the event loop yourself, as
3295 we have already handled that.
3294 we have already handled that.
3296 """
3295 """
3297 from IPython.lib.inputhook import enable_gui
3296 from IPython.lib.inputhook import enable_gui
3298 opts, arg = self.parse_options(parameter_s, '')
3297 opts, arg = self.parse_options(parameter_s, '')
3299 if arg=='': arg = None
3298 if arg=='': arg = None
3300 return enable_gui(arg)
3299 return enable_gui(arg)
3301
3300
3302 def magic_load_ext(self, module_str):
3301 def magic_load_ext(self, module_str):
3303 """Load an IPython extension by its module name."""
3302 """Load an IPython extension by its module name."""
3304 return self.extension_manager.load_extension(module_str)
3303 return self.extension_manager.load_extension(module_str)
3305
3304
3306 def magic_unload_ext(self, module_str):
3305 def magic_unload_ext(self, module_str):
3307 """Unload an IPython extension by its module name."""
3306 """Unload an IPython extension by its module name."""
3308 self.extension_manager.unload_extension(module_str)
3307 self.extension_manager.unload_extension(module_str)
3309
3308
3310 def magic_reload_ext(self, module_str):
3309 def magic_reload_ext(self, module_str):
3311 """Reload an IPython extension by its module name."""
3310 """Reload an IPython extension by its module name."""
3312 self.extension_manager.reload_extension(module_str)
3311 self.extension_manager.reload_extension(module_str)
3313
3312
3314 @testdec.skip_doctest
3313 @testdec.skip_doctest
3315 def magic_install_profiles(self, s):
3314 def magic_install_profiles(self, s):
3316 """Install the default IPython profiles into the .ipython dir.
3315 """Install the default IPython profiles into the .ipython dir.
3317
3316
3318 If the default profiles have already been installed, they will not
3317 If the default profiles have already been installed, they will not
3319 be overwritten. You can force overwriting them by using the ``-o``
3318 be overwritten. You can force overwriting them by using the ``-o``
3320 option::
3319 option::
3321
3320
3322 In [1]: %install_profiles -o
3321 In [1]: %install_profiles -o
3323 """
3322 """
3324 if '-o' in s:
3323 if '-o' in s:
3325 overwrite = True
3324 overwrite = True
3326 else:
3325 else:
3327 overwrite = False
3326 overwrite = False
3328 from IPython.config import profile
3327 from IPython.config import profile
3329 profile_dir = os.path.split(profile.__file__)[0]
3328 profile_dir = os.path.split(profile.__file__)[0]
3330 ipython_dir = self.ipython_dir
3329 ipython_dir = self.ipython_dir
3331 files = os.listdir(profile_dir)
3330 files = os.listdir(profile_dir)
3332
3331
3333 to_install = []
3332 to_install = []
3334 for f in files:
3333 for f in files:
3335 if f.startswith('ipython_config'):
3334 if f.startswith('ipython_config'):
3336 src = os.path.join(profile_dir, f)
3335 src = os.path.join(profile_dir, f)
3337 dst = os.path.join(ipython_dir, f)
3336 dst = os.path.join(ipython_dir, f)
3338 if (not os.path.isfile(dst)) or overwrite:
3337 if (not os.path.isfile(dst)) or overwrite:
3339 to_install.append((f, src, dst))
3338 to_install.append((f, src, dst))
3340 if len(to_install)>0:
3339 if len(to_install)>0:
3341 print "Installing profiles to: ", ipython_dir
3340 print "Installing profiles to: ", ipython_dir
3342 for (f, src, dst) in to_install:
3341 for (f, src, dst) in to_install:
3343 shutil.copy(src, dst)
3342 shutil.copy(src, dst)
3344 print " %s" % f
3343 print " %s" % f
3345
3344
3346 def magic_install_default_config(self, s):
3345 def magic_install_default_config(self, s):
3347 """Install IPython's default config file into the .ipython dir.
3346 """Install IPython's default config file into the .ipython dir.
3348
3347
3349 If the default config file (:file:`ipython_config.py`) is already
3348 If the default config file (:file:`ipython_config.py`) is already
3350 installed, it will not be overwritten. You can force overwriting
3349 installed, it will not be overwritten. You can force overwriting
3351 by using the ``-o`` option::
3350 by using the ``-o`` option::
3352
3351
3353 In [1]: %install_default_config
3352 In [1]: %install_default_config
3354 """
3353 """
3355 if '-o' in s:
3354 if '-o' in s:
3356 overwrite = True
3355 overwrite = True
3357 else:
3356 else:
3358 overwrite = False
3357 overwrite = False
3359 from IPython.config import default
3358 from IPython.config import default
3360 config_dir = os.path.split(default.__file__)[0]
3359 config_dir = os.path.split(default.__file__)[0]
3361 ipython_dir = self.ipython_dir
3360 ipython_dir = self.ipython_dir
3362 default_config_file_name = 'ipython_config.py'
3361 default_config_file_name = 'ipython_config.py'
3363 src = os.path.join(config_dir, default_config_file_name)
3362 src = os.path.join(config_dir, default_config_file_name)
3364 dst = os.path.join(ipython_dir, default_config_file_name)
3363 dst = os.path.join(ipython_dir, default_config_file_name)
3365 if (not os.path.isfile(dst)) or overwrite:
3364 if (not os.path.isfile(dst)) or overwrite:
3366 shutil.copy(src, dst)
3365 shutil.copy(src, dst)
3367 print "Installing default config file: %s" % dst
3366 print "Installing default config file: %s" % dst
3368
3367
3369 # Pylab support: simple wrappers that activate pylab, load gui input
3368 # Pylab support: simple wrappers that activate pylab, load gui input
3370 # handling and modify slightly %run
3369 # handling and modify slightly %run
3371
3370
3372 @testdec.skip_doctest
3371 @testdec.skip_doctest
3373 def _pylab_magic_run(self, parameter_s=''):
3372 def _pylab_magic_run(self, parameter_s=''):
3374 Magic.magic_run(self, parameter_s,
3373 Magic.magic_run(self, parameter_s,
3375 runner=mpl_runner(self.shell.safe_execfile))
3374 runner=mpl_runner(self.shell.safe_execfile))
3376
3375
3377 _pylab_magic_run.__doc__ = magic_run.__doc__
3376 _pylab_magic_run.__doc__ = magic_run.__doc__
3378
3377
3379 @testdec.skip_doctest
3378 @testdec.skip_doctest
3380 def magic_pylab(self, s):
3379 def magic_pylab(self, s):
3381 """Load numpy and matplotlib to work interactively.
3380 """Load numpy and matplotlib to work interactively.
3382
3381
3383 %pylab [GUINAME]
3382 %pylab [GUINAME]
3384
3383
3385 This function lets you activate pylab (matplotlib, numpy and
3384 This function lets you activate pylab (matplotlib, numpy and
3386 interactive support) at any point during an IPython session.
3385 interactive support) at any point during an IPython session.
3387
3386
3388 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3387 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3389 pylab and mlab, as well as all names from numpy and pylab.
3388 pylab and mlab, as well as all names from numpy and pylab.
3390
3389
3391 Parameters
3390 Parameters
3392 ----------
3391 ----------
3393 guiname : optional
3392 guiname : optional
3394 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or
3393 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or
3395 'tk'). If given, the corresponding Matplotlib backend is used,
3394 'tk'). If given, the corresponding Matplotlib backend is used,
3396 otherwise matplotlib's default (which you can override in your
3395 otherwise matplotlib's default (which you can override in your
3397 matplotlib config file) is used.
3396 matplotlib config file) is used.
3398
3397
3399 Examples
3398 Examples
3400 --------
3399 --------
3401 In this case, where the MPL default is TkAgg:
3400 In this case, where the MPL default is TkAgg:
3402 In [2]: %pylab
3401 In [2]: %pylab
3403
3402
3404 Welcome to pylab, a matplotlib-based Python environment.
3403 Welcome to pylab, a matplotlib-based Python environment.
3405 Backend in use: TkAgg
3404 Backend in use: TkAgg
3406 For more information, type 'help(pylab)'.
3405 For more information, type 'help(pylab)'.
3407
3406
3408 But you can explicitly request a different backend:
3407 But you can explicitly request a different backend:
3409 In [3]: %pylab qt
3408 In [3]: %pylab qt
3410
3409
3411 Welcome to pylab, a matplotlib-based Python environment.
3410 Welcome to pylab, a matplotlib-based Python environment.
3412 Backend in use: Qt4Agg
3411 Backend in use: Qt4Agg
3413 For more information, type 'help(pylab)'.
3412 For more information, type 'help(pylab)'.
3414 """
3413 """
3415 self.shell.enable_pylab(s)
3414 self.shell.enable_pylab(s)
3416
3415
3417 def magic_tb(self, s):
3416 def magic_tb(self, s):
3418 """Print the last traceback with the currently active exception mode.
3417 """Print the last traceback with the currently active exception mode.
3419
3418
3420 See %xmode for changing exception reporting modes."""
3419 See %xmode for changing exception reporting modes."""
3421 self.shell.showtraceback()
3420 self.shell.showtraceback()
3422
3421
3423 @testdec.skip_doctest
3422 @testdec.skip_doctest
3424 def magic_precision(self, s=''):
3423 def magic_precision(self, s=''):
3425 """Set floating point precision for pretty printing.
3424 """Set floating point precision for pretty printing.
3426
3425
3427 Can set either integer precision or a format string.
3426 Can set either integer precision or a format string.
3428
3427
3429 If numpy has been imported and precision is an int,
3428 If numpy has been imported and precision is an int,
3430 numpy display precision will also be set, via ``numpy.set_printoptions``.
3429 numpy display precision will also be set, via ``numpy.set_printoptions``.
3431
3430
3432 If no argument is given, defaults will be restored.
3431 If no argument is given, defaults will be restored.
3433
3432
3434 Examples
3433 Examples
3435 --------
3434 --------
3436 ::
3435 ::
3437
3436
3438 In [1]: from math import pi
3437 In [1]: from math import pi
3439
3438
3440 In [2]: %precision 3
3439 In [2]: %precision 3
3441 Out[2]: '%.3f'
3440 Out[2]: '%.3f'
3442
3441
3443 In [3]: pi
3442 In [3]: pi
3444 Out[3]: 3.142
3443 Out[3]: 3.142
3445
3444
3446 In [4]: %precision %i
3445 In [4]: %precision %i
3447 Out[4]: '%i'
3446 Out[4]: '%i'
3448
3447
3449 In [5]: pi
3448 In [5]: pi
3450 Out[5]: 3
3449 Out[5]: 3
3451
3450
3452 In [6]: %precision %e
3451 In [6]: %precision %e
3453 Out[6]: '%e'
3452 Out[6]: '%e'
3454
3453
3455 In [7]: pi**10
3454 In [7]: pi**10
3456 Out[7]: 9.364805e+04
3455 Out[7]: 9.364805e+04
3457
3456
3458 In [8]: %precision
3457 In [8]: %precision
3459 Out[8]: '%r'
3458 Out[8]: '%r'
3460
3459
3461 In [9]: pi**10
3460 In [9]: pi**10
3462 Out[9]: 93648.047476082982
3461 Out[9]: 93648.047476082982
3463
3462
3464 """
3463 """
3465
3464
3466 ptformatter = self.shell.display_formatter.formatters['text/plain']
3465 ptformatter = self.shell.display_formatter.formatters['text/plain']
3467 ptformatter.float_precision = s
3466 ptformatter.float_precision = s
3468 return ptformatter.float_format
3467 return ptformatter.float_format
3469
3468
3470 # end Magic
3469 # end Magic
@@ -1,891 +1,891 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 sys
25 import sys
26 import types
26 import types
27 from collections import namedtuple
27 from collections import namedtuple
28 from itertools import izip_longest
28 from itertools import izip_longest
29
29
30 # IPython's own
30 # IPython's own
31 from IPython.core import page
31 from IPython.core import page
32 from IPython.external.Itpl import itpl
32 from IPython.external.Itpl import itpl
33 from IPython.utils import PyColorize
33 from IPython.utils import PyColorize
34 import IPython.utils.io
34 from IPython.utils import io
35 from IPython.utils.text import indent
35 from IPython.utils.text import indent
36 from IPython.utils.wildcard import list_namespace
36 from IPython.utils.wildcard import list_namespace
37 from IPython.utils.coloransi import *
37 from IPython.utils.coloransi import *
38
38
39 #****************************************************************************
39 #****************************************************************************
40 # Builtin color schemes
40 # Builtin color schemes
41
41
42 Colors = TermColors # just a shorthand
42 Colors = TermColors # just a shorthand
43
43
44 # Build a few color schemes
44 # Build a few color schemes
45 NoColor = ColorScheme(
45 NoColor = ColorScheme(
46 'NoColor',{
46 'NoColor',{
47 'header' : Colors.NoColor,
47 'header' : Colors.NoColor,
48 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
48 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
49 } )
49 } )
50
50
51 LinuxColors = ColorScheme(
51 LinuxColors = ColorScheme(
52 'Linux',{
52 'Linux',{
53 'header' : Colors.LightRed,
53 'header' : Colors.LightRed,
54 'normal' : Colors.Normal # color off (usu. Colors.Normal)
54 'normal' : Colors.Normal # color off (usu. Colors.Normal)
55 } )
55 } )
56
56
57 LightBGColors = ColorScheme(
57 LightBGColors = ColorScheme(
58 'LightBG',{
58 'LightBG',{
59 'header' : Colors.Red,
59 'header' : Colors.Red,
60 'normal' : Colors.Normal # color off (usu. Colors.Normal)
60 'normal' : Colors.Normal # color off (usu. Colors.Normal)
61 } )
61 } )
62
62
63 # Build table of color schemes (needed by the parser)
63 # Build table of color schemes (needed by the parser)
64 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
64 InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
65 'Linux')
65 'Linux')
66
66
67 #****************************************************************************
67 #****************************************************************************
68 # Auxiliary functions and objects
68 # Auxiliary functions and objects
69
69
70 # See the messaging spec for the definition of all these fields. This list
70 # See the messaging spec for the definition of all these fields. This list
71 # effectively defines the order of display
71 # effectively defines the order of display
72 info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
72 info_fields = ['type_name', 'base_class', 'string_form', 'namespace',
73 'length', 'file', 'definition', 'docstring', 'source',
73 'length', 'file', 'definition', 'docstring', 'source',
74 'init_definition', 'class_docstring', 'init_docstring',
74 'init_definition', 'class_docstring', 'init_docstring',
75 'call_def', 'call_docstring',
75 'call_def', 'call_docstring',
76 # These won't be printed but will be used to determine how to
76 # These won't be printed but will be used to determine how to
77 # format the object
77 # format the object
78 'ismagic', 'isalias', 'argspec', 'found', 'name',
78 'ismagic', 'isalias', 'argspec', 'found', 'name',
79 ]
79 ]
80
80
81
81
82 def object_info(**kw):
82 def object_info(**kw):
83 """Make an object info dict with all fields present."""
83 """Make an object info dict with all fields present."""
84 infodict = dict(izip_longest(info_fields, [None]))
84 infodict = dict(izip_longest(info_fields, [None]))
85 infodict.update(kw)
85 infodict.update(kw)
86 return infodict
86 return infodict
87
87
88
88
89 def getdoc(obj):
89 def getdoc(obj):
90 """Stable wrapper around inspect.getdoc.
90 """Stable wrapper around inspect.getdoc.
91
91
92 This can't crash because of attribute problems.
92 This can't crash because of attribute problems.
93
93
94 It also attempts to call a getdoc() method on the given object. This
94 It also attempts to call a getdoc() method on the given object. This
95 allows objects which provide their docstrings via non-standard mechanisms
95 allows objects which provide their docstrings via non-standard mechanisms
96 (like Pyro proxies) to still be inspected by ipython's ? system."""
96 (like Pyro proxies) to still be inspected by ipython's ? system."""
97
97
98 ds = None # default return value
98 ds = None # default return value
99 try:
99 try:
100 ds = inspect.getdoc(obj)
100 ds = inspect.getdoc(obj)
101 except:
101 except:
102 # Harden against an inspect failure, which can occur with
102 # Harden against an inspect failure, which can occur with
103 # SWIG-wrapped extensions.
103 # SWIG-wrapped extensions.
104 pass
104 pass
105 # Allow objects to offer customized documentation via a getdoc method:
105 # Allow objects to offer customized documentation via a getdoc method:
106 try:
106 try:
107 ds2 = obj.getdoc()
107 ds2 = obj.getdoc()
108 except:
108 except:
109 pass
109 pass
110 else:
110 else:
111 # if we get extra info, we add it to the normal docstring.
111 # if we get extra info, we add it to the normal docstring.
112 if ds is None:
112 if ds is None:
113 ds = ds2
113 ds = ds2
114 else:
114 else:
115 ds = '%s\n%s' % (ds,ds2)
115 ds = '%s\n%s' % (ds,ds2)
116 return ds
116 return ds
117
117
118
118
119 def getsource(obj,is_binary=False):
119 def getsource(obj,is_binary=False):
120 """Wrapper around inspect.getsource.
120 """Wrapper around inspect.getsource.
121
121
122 This can be modified by other projects to provide customized source
122 This can be modified by other projects to provide customized source
123 extraction.
123 extraction.
124
124
125 Inputs:
125 Inputs:
126
126
127 - obj: an object whose source code we will attempt to extract.
127 - obj: an object whose source code we will attempt to extract.
128
128
129 Optional inputs:
129 Optional inputs:
130
130
131 - is_binary: whether the object is known to come from a binary source.
131 - is_binary: whether the object is known to come from a binary source.
132 This implementation will skip returning any output for binary objects, but
132 This implementation will skip returning any output for binary objects, but
133 custom extractors may know how to meaningfully process them."""
133 custom extractors may know how to meaningfully process them."""
134
134
135 if is_binary:
135 if is_binary:
136 return None
136 return None
137 else:
137 else:
138 try:
138 try:
139 src = inspect.getsource(obj)
139 src = inspect.getsource(obj)
140 except TypeError:
140 except TypeError:
141 if hasattr(obj,'__class__'):
141 if hasattr(obj,'__class__'):
142 src = inspect.getsource(obj.__class__)
142 src = inspect.getsource(obj.__class__)
143 return src
143 return src
144
144
145 def getargspec(obj):
145 def getargspec(obj):
146 """Get the names and default values of a function's arguments.
146 """Get the names and default values of a function's arguments.
147
147
148 A tuple of four things is returned: (args, varargs, varkw, defaults).
148 A tuple of four things is returned: (args, varargs, varkw, defaults).
149 'args' is a list of the argument names (it may contain nested lists).
149 'args' is a list of the argument names (it may contain nested lists).
150 'varargs' and 'varkw' are the names of the * and ** arguments or None.
150 'varargs' and 'varkw' are the names of the * and ** arguments or None.
151 'defaults' is an n-tuple of the default values of the last n arguments.
151 'defaults' is an n-tuple of the default values of the last n arguments.
152
152
153 Modified version of inspect.getargspec from the Python Standard
153 Modified version of inspect.getargspec from the Python Standard
154 Library."""
154 Library."""
155
155
156 if inspect.isfunction(obj):
156 if inspect.isfunction(obj):
157 func_obj = obj
157 func_obj = obj
158 elif inspect.ismethod(obj):
158 elif inspect.ismethod(obj):
159 func_obj = obj.im_func
159 func_obj = obj.im_func
160 elif hasattr(obj, '__call__'):
160 elif hasattr(obj, '__call__'):
161 func_obj = obj.__call__
161 func_obj = obj.__call__
162 else:
162 else:
163 raise TypeError('arg is not a Python function')
163 raise TypeError('arg is not a Python function')
164 args, varargs, varkw = inspect.getargs(func_obj.func_code)
164 args, varargs, varkw = inspect.getargs(func_obj.func_code)
165 return args, varargs, varkw, func_obj.func_defaults
165 return args, varargs, varkw, func_obj.func_defaults
166
166
167
167
168 def format_argspec(argspec):
168 def format_argspec(argspec):
169 """Format argspect, convenience wrapper around inspect's.
169 """Format argspect, convenience wrapper around inspect's.
170
170
171 This takes a dict instead of ordered arguments and calls
171 This takes a dict instead of ordered arguments and calls
172 inspect.format_argspec with the arguments in the necessary order.
172 inspect.format_argspec with the arguments in the necessary order.
173 """
173 """
174 return inspect.formatargspec(argspec['args'], argspec['varargs'],
174 return inspect.formatargspec(argspec['args'], argspec['varargs'],
175 argspec['varkw'], argspec['defaults'])
175 argspec['varkw'], argspec['defaults'])
176
176
177
177
178 def call_tip(oinfo, format_call=True):
178 def call_tip(oinfo, format_call=True):
179 """Extract call tip data from an oinfo dict.
179 """Extract call tip data from an oinfo dict.
180
180
181 Parameters
181 Parameters
182 ----------
182 ----------
183 oinfo : dict
183 oinfo : dict
184
184
185 format_call : bool, optional
185 format_call : bool, optional
186 If True, the call line is formatted and returned as a string. If not, a
186 If True, the call line is formatted and returned as a string. If not, a
187 tuple of (name, argspec) is returned.
187 tuple of (name, argspec) is returned.
188
188
189 Returns
189 Returns
190 -------
190 -------
191 call_info : None, str or (str, dict) tuple.
191 call_info : None, str or (str, dict) tuple.
192 When format_call is True, the whole call information is formattted as a
192 When format_call is True, the whole call information is formattted as a
193 single string. Otherwise, the object's name and its argspec dict are
193 single string. Otherwise, the object's name and its argspec dict are
194 returned. If no call information is available, None is returned.
194 returned. If no call information is available, None is returned.
195
195
196 docstring : str or None
196 docstring : str or None
197 The most relevant docstring for calling purposes is returned, if
197 The most relevant docstring for calling purposes is returned, if
198 available. The priority is: call docstring for callable instances, then
198 available. The priority is: call docstring for callable instances, then
199 constructor docstring for classes, then main object's docstring otherwise
199 constructor docstring for classes, then main object's docstring otherwise
200 (regular functions).
200 (regular functions).
201 """
201 """
202 # Get call definition
202 # Get call definition
203 argspec = oinfo['argspec']
203 argspec = oinfo['argspec']
204 if argspec is None:
204 if argspec is None:
205 call_line = None
205 call_line = None
206 else:
206 else:
207 # Callable objects will have 'self' as their first argument, prune
207 # Callable objects will have 'self' as their first argument, prune
208 # it out if it's there for clarity (since users do *not* pass an
208 # it out if it's there for clarity (since users do *not* pass an
209 # extra first argument explicitly).
209 # extra first argument explicitly).
210 try:
210 try:
211 has_self = argspec['args'][0] == 'self'
211 has_self = argspec['args'][0] == 'self'
212 except (KeyError, IndexError):
212 except (KeyError, IndexError):
213 pass
213 pass
214 else:
214 else:
215 if has_self:
215 if has_self:
216 argspec['args'] = argspec['args'][1:]
216 argspec['args'] = argspec['args'][1:]
217
217
218 call_line = oinfo['name']+format_argspec(argspec)
218 call_line = oinfo['name']+format_argspec(argspec)
219
219
220 # Now get docstring.
220 # Now get docstring.
221 # The priority is: call docstring, constructor docstring, main one.
221 # The priority is: call docstring, constructor docstring, main one.
222 doc = oinfo['call_docstring']
222 doc = oinfo['call_docstring']
223 if doc is None:
223 if doc is None:
224 doc = oinfo['init_docstring']
224 doc = oinfo['init_docstring']
225 if doc is None:
225 if doc is None:
226 doc = oinfo['docstring']
226 doc = oinfo['docstring']
227
227
228 return call_line, doc
228 return call_line, doc
229
229
230 #****************************************************************************
230 #****************************************************************************
231 # Class definitions
231 # Class definitions
232
232
233 class myStringIO(StringIO.StringIO):
233 class myStringIO(StringIO.StringIO):
234 """Adds a writeln method to normal StringIO."""
234 """Adds a writeln method to normal StringIO."""
235 def writeln(self,*arg,**kw):
235 def writeln(self,*arg,**kw):
236 """Does a write() and then a write('\n')"""
236 """Does a write() and then a write('\n')"""
237 self.write(*arg,**kw)
237 self.write(*arg,**kw)
238 self.write('\n')
238 self.write('\n')
239
239
240
240
241 class Inspector:
241 class Inspector:
242 def __init__(self, color_table=InspectColors,
242 def __init__(self, color_table=InspectColors,
243 code_color_table=PyColorize.ANSICodeColors,
243 code_color_table=PyColorize.ANSICodeColors,
244 scheme='NoColor',
244 scheme='NoColor',
245 str_detail_level=0):
245 str_detail_level=0):
246 self.color_table = color_table
246 self.color_table = color_table
247 self.parser = PyColorize.Parser(code_color_table,out='str')
247 self.parser = PyColorize.Parser(code_color_table,out='str')
248 self.format = self.parser.format
248 self.format = self.parser.format
249 self.str_detail_level = str_detail_level
249 self.str_detail_level = str_detail_level
250 self.set_active_scheme(scheme)
250 self.set_active_scheme(scheme)
251
251
252 def _getdef(self,obj,oname=''):
252 def _getdef(self,obj,oname=''):
253 """Return the definition header for any callable object.
253 """Return the definition header for any callable object.
254
254
255 If any exception is generated, None is returned instead and the
255 If any exception is generated, None is returned instead and the
256 exception is suppressed."""
256 exception is suppressed."""
257
257
258 try:
258 try:
259 # We need a plain string here, NOT unicode!
259 # We need a plain string here, NOT unicode!
260 hdef = oname + inspect.formatargspec(*getargspec(obj))
260 hdef = oname + inspect.formatargspec(*getargspec(obj))
261 return hdef.encode('ascii')
261 return hdef.encode('ascii')
262 except:
262 except:
263 return None
263 return None
264
264
265 def __head(self,h):
265 def __head(self,h):
266 """Return a header string with proper colors."""
266 """Return a header string with proper colors."""
267 return '%s%s%s' % (self.color_table.active_colors.header,h,
267 return '%s%s%s' % (self.color_table.active_colors.header,h,
268 self.color_table.active_colors.normal)
268 self.color_table.active_colors.normal)
269
269
270 def set_active_scheme(self,scheme):
270 def set_active_scheme(self,scheme):
271 self.color_table.set_active_scheme(scheme)
271 self.color_table.set_active_scheme(scheme)
272 self.parser.color_table.set_active_scheme(scheme)
272 self.parser.color_table.set_active_scheme(scheme)
273
273
274 def noinfo(self,msg,oname):
274 def noinfo(self,msg,oname):
275 """Generic message when no information is found."""
275 """Generic message when no information is found."""
276 print 'No %s found' % msg,
276 print 'No %s found' % msg,
277 if oname:
277 if oname:
278 print 'for %s' % oname
278 print 'for %s' % oname
279 else:
279 else:
280 print
280 print
281
281
282 def pdef(self,obj,oname=''):
282 def pdef(self,obj,oname=''):
283 """Print the definition header for any callable object.
283 """Print the definition header for any callable object.
284
284
285 If the object is a class, print the constructor information."""
285 If the object is a class, print the constructor information."""
286
286
287 if not callable(obj):
287 if not callable(obj):
288 print 'Object is not callable.'
288 print 'Object is not callable.'
289 return
289 return
290
290
291 header = ''
291 header = ''
292
292
293 if inspect.isclass(obj):
293 if inspect.isclass(obj):
294 header = self.__head('Class constructor information:\n')
294 header = self.__head('Class constructor information:\n')
295 obj = obj.__init__
295 obj = obj.__init__
296 elif type(obj) is types.InstanceType:
296 elif type(obj) is types.InstanceType:
297 obj = obj.__call__
297 obj = obj.__call__
298
298
299 output = self._getdef(obj,oname)
299 output = self._getdef(obj,oname)
300 if output is None:
300 if output is None:
301 self.noinfo('definition header',oname)
301 self.noinfo('definition header',oname)
302 else:
302 else:
303 print >>IPython.utils.io.Term.cout, header,self.format(output),
303 print >>io.stdout, header,self.format(output),
304
304
305 def pdoc(self,obj,oname='',formatter = None):
305 def pdoc(self,obj,oname='',formatter = None):
306 """Print the docstring for any object.
306 """Print the docstring for any object.
307
307
308 Optional:
308 Optional:
309 -formatter: a function to run the docstring through for specially
309 -formatter: a function to run the docstring through for specially
310 formatted docstrings."""
310 formatted docstrings."""
311
311
312 head = self.__head # so that itpl can find it even if private
312 head = self.__head # so that itpl can find it even if private
313 ds = getdoc(obj)
313 ds = getdoc(obj)
314 if formatter:
314 if formatter:
315 ds = formatter(ds)
315 ds = formatter(ds)
316 if inspect.isclass(obj):
316 if inspect.isclass(obj):
317 init_ds = getdoc(obj.__init__)
317 init_ds = getdoc(obj.__init__)
318 output = itpl('$head("Class Docstring:")\n'
318 output = itpl('$head("Class Docstring:")\n'
319 '$indent(ds)\n'
319 '$indent(ds)\n'
320 '$head("Constructor Docstring"):\n'
320 '$head("Constructor Docstring"):\n'
321 '$indent(init_ds)')
321 '$indent(init_ds)')
322 elif (type(obj) is types.InstanceType or isinstance(obj,object)) \
322 elif (type(obj) is types.InstanceType or isinstance(obj,object)) \
323 and hasattr(obj,'__call__'):
323 and hasattr(obj,'__call__'):
324 call_ds = getdoc(obj.__call__)
324 call_ds = getdoc(obj.__call__)
325 if call_ds:
325 if call_ds:
326 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
326 output = itpl('$head("Class Docstring:")\n$indent(ds)\n'
327 '$head("Calling Docstring:")\n$indent(call_ds)')
327 '$head("Calling Docstring:")\n$indent(call_ds)')
328 else:
328 else:
329 output = ds
329 output = ds
330 else:
330 else:
331 output = ds
331 output = ds
332 if output is None:
332 if output is None:
333 self.noinfo('documentation',oname)
333 self.noinfo('documentation',oname)
334 return
334 return
335 page.page(output)
335 page.page(output)
336
336
337 def psource(self,obj,oname=''):
337 def psource(self,obj,oname=''):
338 """Print the source code for an object."""
338 """Print the source code for an object."""
339
339
340 # Flush the source cache because inspect can return out-of-date source
340 # Flush the source cache because inspect can return out-of-date source
341 linecache.checkcache()
341 linecache.checkcache()
342 try:
342 try:
343 src = getsource(obj)
343 src = getsource(obj)
344 except:
344 except:
345 self.noinfo('source',oname)
345 self.noinfo('source',oname)
346 else:
346 else:
347 page.page(self.format(src))
347 page.page(self.format(src))
348
348
349 def pfile(self,obj,oname=''):
349 def pfile(self,obj,oname=''):
350 """Show the whole file where an object was defined."""
350 """Show the whole file where an object was defined."""
351
351
352 try:
352 try:
353 try:
353 try:
354 lineno = inspect.getsourcelines(obj)[1]
354 lineno = inspect.getsourcelines(obj)[1]
355 except TypeError:
355 except TypeError:
356 # For instances, try the class object like getsource() does
356 # For instances, try the class object like getsource() does
357 if hasattr(obj,'__class__'):
357 if hasattr(obj,'__class__'):
358 lineno = inspect.getsourcelines(obj.__class__)[1]
358 lineno = inspect.getsourcelines(obj.__class__)[1]
359 # Adjust the inspected object so getabsfile() below works
359 # Adjust the inspected object so getabsfile() below works
360 obj = obj.__class__
360 obj = obj.__class__
361 except:
361 except:
362 self.noinfo('file',oname)
362 self.noinfo('file',oname)
363 return
363 return
364
364
365 # We only reach this point if object was successfully queried
365 # We only reach this point if object was successfully queried
366
366
367 # run contents of file through pager starting at line
367 # run contents of file through pager starting at line
368 # where the object is defined
368 # where the object is defined
369 ofile = inspect.getabsfile(obj)
369 ofile = inspect.getabsfile(obj)
370
370
371 if (ofile.endswith('.so') or ofile.endswith('.dll')):
371 if (ofile.endswith('.so') or ofile.endswith('.dll')):
372 print 'File %r is binary, not printing.' % ofile
372 print 'File %r is binary, not printing.' % ofile
373 elif not os.path.isfile(ofile):
373 elif not os.path.isfile(ofile):
374 print 'File %r does not exist, not printing.' % ofile
374 print 'File %r does not exist, not printing.' % ofile
375 else:
375 else:
376 # Print only text files, not extension binaries. Note that
376 # Print only text files, not extension binaries. Note that
377 # getsourcelines returns lineno with 1-offset and page() uses
377 # getsourcelines returns lineno with 1-offset and page() uses
378 # 0-offset, so we must adjust.
378 # 0-offset, so we must adjust.
379 page.page(self.format(open(ofile).read()),lineno-1)
379 page.page(self.format(open(ofile).read()),lineno-1)
380
380
381 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
381 def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0):
382 """Show detailed information about an object.
382 """Show detailed information about an object.
383
383
384 Optional arguments:
384 Optional arguments:
385
385
386 - oname: name of the variable pointing to the object.
386 - oname: name of the variable pointing to the object.
387
387
388 - formatter: special formatter for docstrings (see pdoc)
388 - formatter: special formatter for docstrings (see pdoc)
389
389
390 - info: a structure with some information fields which may have been
390 - info: a structure with some information fields which may have been
391 precomputed already.
391 precomputed already.
392
392
393 - detail_level: if set to 1, more information is given.
393 - detail_level: if set to 1, more information is given.
394 """
394 """
395
395
396 obj_type = type(obj)
396 obj_type = type(obj)
397
397
398 header = self.__head
398 header = self.__head
399 if info is None:
399 if info is None:
400 ismagic = 0
400 ismagic = 0
401 isalias = 0
401 isalias = 0
402 ospace = ''
402 ospace = ''
403 else:
403 else:
404 ismagic = info.ismagic
404 ismagic = info.ismagic
405 isalias = info.isalias
405 isalias = info.isalias
406 ospace = info.namespace
406 ospace = info.namespace
407 # Get docstring, special-casing aliases:
407 # Get docstring, special-casing aliases:
408 if isalias:
408 if isalias:
409 if not callable(obj):
409 if not callable(obj):
410 try:
410 try:
411 ds = "Alias to the system command:\n %s" % obj[1]
411 ds = "Alias to the system command:\n %s" % obj[1]
412 except:
412 except:
413 ds = "Alias: " + str(obj)
413 ds = "Alias: " + str(obj)
414 else:
414 else:
415 ds = "Alias to " + str(obj)
415 ds = "Alias to " + str(obj)
416 if obj.__doc__:
416 if obj.__doc__:
417 ds += "\nDocstring:\n" + obj.__doc__
417 ds += "\nDocstring:\n" + obj.__doc__
418 else:
418 else:
419 ds = getdoc(obj)
419 ds = getdoc(obj)
420 if ds is None:
420 if ds is None:
421 ds = '<no docstring>'
421 ds = '<no docstring>'
422 if formatter is not None:
422 if formatter is not None:
423 ds = formatter(ds)
423 ds = formatter(ds)
424
424
425 # store output in a list which gets joined with \n at the end.
425 # store output in a list which gets joined with \n at the end.
426 out = myStringIO()
426 out = myStringIO()
427
427
428 string_max = 200 # max size of strings to show (snipped if longer)
428 string_max = 200 # max size of strings to show (snipped if longer)
429 shalf = int((string_max -5)/2)
429 shalf = int((string_max -5)/2)
430
430
431 if ismagic:
431 if ismagic:
432 obj_type_name = 'Magic function'
432 obj_type_name = 'Magic function'
433 elif isalias:
433 elif isalias:
434 obj_type_name = 'System alias'
434 obj_type_name = 'System alias'
435 else:
435 else:
436 obj_type_name = obj_type.__name__
436 obj_type_name = obj_type.__name__
437 out.writeln(header('Type:\t\t')+obj_type_name)
437 out.writeln(header('Type:\t\t')+obj_type_name)
438
438
439 try:
439 try:
440 bclass = obj.__class__
440 bclass = obj.__class__
441 out.writeln(header('Base Class:\t')+str(bclass))
441 out.writeln(header('Base Class:\t')+str(bclass))
442 except: pass
442 except: pass
443
443
444 # String form, but snip if too long in ? form (full in ??)
444 # String form, but snip if too long in ? form (full in ??)
445 if detail_level >= self.str_detail_level:
445 if detail_level >= self.str_detail_level:
446 try:
446 try:
447 ostr = str(obj)
447 ostr = str(obj)
448 str_head = 'String Form:'
448 str_head = 'String Form:'
449 if not detail_level and len(ostr)>string_max:
449 if not detail_level and len(ostr)>string_max:
450 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
450 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
451 ostr = ("\n" + " " * len(str_head.expandtabs())).\
451 ostr = ("\n" + " " * len(str_head.expandtabs())).\
452 join(q.strip() for q in ostr.split("\n"))
452 join(q.strip() for q in ostr.split("\n"))
453 if ostr.find('\n') > -1:
453 if ostr.find('\n') > -1:
454 # Print multi-line strings starting at the next line.
454 # Print multi-line strings starting at the next line.
455 str_sep = '\n'
455 str_sep = '\n'
456 else:
456 else:
457 str_sep = '\t'
457 str_sep = '\t'
458 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
458 out.writeln("%s%s%s" % (header(str_head),str_sep,ostr))
459 except:
459 except:
460 pass
460 pass
461
461
462 if ospace:
462 if ospace:
463 out.writeln(header('Namespace:\t')+ospace)
463 out.writeln(header('Namespace:\t')+ospace)
464
464
465 # Length (for strings and lists)
465 # Length (for strings and lists)
466 try:
466 try:
467 length = str(len(obj))
467 length = str(len(obj))
468 out.writeln(header('Length:\t\t')+length)
468 out.writeln(header('Length:\t\t')+length)
469 except: pass
469 except: pass
470
470
471 # Filename where object was defined
471 # Filename where object was defined
472 binary_file = False
472 binary_file = False
473 try:
473 try:
474 try:
474 try:
475 fname = inspect.getabsfile(obj)
475 fname = inspect.getabsfile(obj)
476 except TypeError:
476 except TypeError:
477 # For an instance, the file that matters is where its class was
477 # For an instance, the file that matters is where its class was
478 # declared.
478 # declared.
479 if hasattr(obj,'__class__'):
479 if hasattr(obj,'__class__'):
480 fname = inspect.getabsfile(obj.__class__)
480 fname = inspect.getabsfile(obj.__class__)
481 if fname.endswith('<string>'):
481 if fname.endswith('<string>'):
482 fname = 'Dynamically generated function. No source code available.'
482 fname = 'Dynamically generated function. No source code available.'
483 if (fname.endswith('.so') or fname.endswith('.dll')):
483 if (fname.endswith('.so') or fname.endswith('.dll')):
484 binary_file = True
484 binary_file = True
485 out.writeln(header('File:\t\t')+fname)
485 out.writeln(header('File:\t\t')+fname)
486 except:
486 except:
487 # if anything goes wrong, we don't want to show source, so it's as
487 # if anything goes wrong, we don't want to show source, so it's as
488 # if the file was binary
488 # if the file was binary
489 binary_file = True
489 binary_file = True
490
490
491 # reconstruct the function definition and print it:
491 # reconstruct the function definition and print it:
492 defln = self._getdef(obj,oname)
492 defln = self._getdef(obj,oname)
493 if defln:
493 if defln:
494 out.write(header('Definition:\t')+self.format(defln))
494 out.write(header('Definition:\t')+self.format(defln))
495
495
496 # Docstrings only in detail 0 mode, since source contains them (we
496 # Docstrings only in detail 0 mode, since source contains them (we
497 # avoid repetitions). If source fails, we add them back, see below.
497 # avoid repetitions). If source fails, we add them back, see below.
498 if ds and detail_level == 0:
498 if ds and detail_level == 0:
499 out.writeln(header('Docstring:\n') + indent(ds))
499 out.writeln(header('Docstring:\n') + indent(ds))
500
500
501 # Original source code for any callable
501 # Original source code for any callable
502 if detail_level:
502 if detail_level:
503 # Flush the source cache because inspect can return out-of-date
503 # Flush the source cache because inspect can return out-of-date
504 # source
504 # source
505 linecache.checkcache()
505 linecache.checkcache()
506 source_success = False
506 source_success = False
507 try:
507 try:
508 try:
508 try:
509 src = getsource(obj,binary_file)
509 src = getsource(obj,binary_file)
510 except TypeError:
510 except TypeError:
511 if hasattr(obj,'__class__'):
511 if hasattr(obj,'__class__'):
512 src = getsource(obj.__class__,binary_file)
512 src = getsource(obj.__class__,binary_file)
513 if src is not None:
513 if src is not None:
514 source = self.format(src)
514 source = self.format(src)
515 out.write(header('Source:\n')+source.rstrip()+'\n')
515 out.write(header('Source:\n')+source.rstrip()+'\n')
516 source_success = True
516 source_success = True
517 except Exception, msg:
517 except Exception, msg:
518 pass
518 pass
519
519
520 if ds and not source_success:
520 if ds and not source_success:
521 out.writeln(header('Docstring [source file open failed]:\n')
521 out.writeln(header('Docstring [source file open failed]:\n')
522 + indent(ds))
522 + indent(ds))
523
523
524 # Constructor docstring for classes
524 # Constructor docstring for classes
525 if inspect.isclass(obj):
525 if inspect.isclass(obj):
526 # reconstruct the function definition and print it:
526 # reconstruct the function definition and print it:
527 try:
527 try:
528 obj_init = obj.__init__
528 obj_init = obj.__init__
529 except AttributeError:
529 except AttributeError:
530 init_def = init_ds = None
530 init_def = init_ds = None
531 else:
531 else:
532 init_def = self._getdef(obj_init,oname)
532 init_def = self._getdef(obj_init,oname)
533 init_ds = getdoc(obj_init)
533 init_ds = getdoc(obj_init)
534 # Skip Python's auto-generated docstrings
534 # Skip Python's auto-generated docstrings
535 if init_ds and \
535 if init_ds and \
536 init_ds.startswith('x.__init__(...) initializes'):
536 init_ds.startswith('x.__init__(...) initializes'):
537 init_ds = None
537 init_ds = None
538
538
539 if init_def or init_ds:
539 if init_def or init_ds:
540 out.writeln(header('Constructor information:'))
540 out.writeln(header('Constructor information:'))
541 if init_def:
541 if init_def:
542 out.write(header('Definition:\t')+ self.format(init_def))
542 out.write(header('Definition:\t')+ self.format(init_def))
543 if init_ds:
543 if init_ds:
544 out.writeln(header('Docstring:\n') + indent(init_ds))
544 out.writeln(header('Docstring:\n') + indent(init_ds))
545 # and class docstring for instances:
545 # and class docstring for instances:
546 elif obj_type is types.InstanceType or \
546 elif obj_type is types.InstanceType or \
547 isinstance(obj,object):
547 isinstance(obj,object):
548
548
549 # First, check whether the instance docstring is identical to the
549 # First, check whether the instance docstring is identical to the
550 # class one, and print it separately if they don't coincide. In
550 # class one, and print it separately if they don't coincide. In
551 # most cases they will, but it's nice to print all the info for
551 # most cases they will, but it's nice to print all the info for
552 # objects which use instance-customized docstrings.
552 # objects which use instance-customized docstrings.
553 if ds:
553 if ds:
554 try:
554 try:
555 cls = getattr(obj,'__class__')
555 cls = getattr(obj,'__class__')
556 except:
556 except:
557 class_ds = None
557 class_ds = None
558 else:
558 else:
559 class_ds = getdoc(cls)
559 class_ds = getdoc(cls)
560 # Skip Python's auto-generated docstrings
560 # Skip Python's auto-generated docstrings
561 if class_ds and \
561 if class_ds and \
562 (class_ds.startswith('function(code, globals[,') or \
562 (class_ds.startswith('function(code, globals[,') or \
563 class_ds.startswith('instancemethod(function, instance,') or \
563 class_ds.startswith('instancemethod(function, instance,') or \
564 class_ds.startswith('module(name[,') ):
564 class_ds.startswith('module(name[,') ):
565 class_ds = None
565 class_ds = None
566 if class_ds and ds != class_ds:
566 if class_ds and ds != class_ds:
567 out.writeln(header('Class Docstring:\n') +
567 out.writeln(header('Class Docstring:\n') +
568 indent(class_ds))
568 indent(class_ds))
569
569
570 # Next, try to show constructor docstrings
570 # Next, try to show constructor docstrings
571 try:
571 try:
572 init_ds = getdoc(obj.__init__)
572 init_ds = getdoc(obj.__init__)
573 # Skip Python's auto-generated docstrings
573 # Skip Python's auto-generated docstrings
574 if init_ds and \
574 if init_ds and \
575 init_ds.startswith('x.__init__(...) initializes'):
575 init_ds.startswith('x.__init__(...) initializes'):
576 init_ds = None
576 init_ds = None
577 except AttributeError:
577 except AttributeError:
578 init_ds = None
578 init_ds = None
579 if init_ds:
579 if init_ds:
580 out.writeln(header('Constructor Docstring:\n') +
580 out.writeln(header('Constructor Docstring:\n') +
581 indent(init_ds))
581 indent(init_ds))
582
582
583 # Call form docstring for callable instances
583 # Call form docstring for callable instances
584 if hasattr(obj,'__call__'):
584 if hasattr(obj,'__call__'):
585 #out.writeln(header('Callable:\t')+'Yes')
585 #out.writeln(header('Callable:\t')+'Yes')
586 call_def = self._getdef(obj.__call__,oname)
586 call_def = self._getdef(obj.__call__,oname)
587 #if call_def is None:
587 #if call_def is None:
588 # out.writeln(header('Call def:\t')+
588 # out.writeln(header('Call def:\t')+
589 # 'Calling definition not available.')
589 # 'Calling definition not available.')
590 if call_def is not None:
590 if call_def is not None:
591 out.writeln(header('Call def:\t')+self.format(call_def))
591 out.writeln(header('Call def:\t')+self.format(call_def))
592 call_ds = getdoc(obj.__call__)
592 call_ds = getdoc(obj.__call__)
593 # Skip Python's auto-generated docstrings
593 # Skip Python's auto-generated docstrings
594 if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'):
594 if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'):
595 call_ds = None
595 call_ds = None
596 if call_ds:
596 if call_ds:
597 out.writeln(header('Call docstring:\n') + indent(call_ds))
597 out.writeln(header('Call docstring:\n') + indent(call_ds))
598
598
599 # Finally send to printer/pager
599 # Finally send to printer/pager
600 output = out.getvalue()
600 output = out.getvalue()
601 if output:
601 if output:
602 page.page(output)
602 page.page(output)
603 # end pinfo
603 # end pinfo
604
604
605 def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
605 def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
606 """Compute a dict with detailed information about an object.
606 """Compute a dict with detailed information about an object.
607
607
608 Optional arguments:
608 Optional arguments:
609
609
610 - oname: name of the variable pointing to the object.
610 - oname: name of the variable pointing to the object.
611
611
612 - formatter: special formatter for docstrings (see pdoc)
612 - formatter: special formatter for docstrings (see pdoc)
613
613
614 - info: a structure with some information fields which may have been
614 - info: a structure with some information fields which may have been
615 precomputed already.
615 precomputed already.
616
616
617 - detail_level: if set to 1, more information is given.
617 - detail_level: if set to 1, more information is given.
618 """
618 """
619
619
620 obj_type = type(obj)
620 obj_type = type(obj)
621
621
622 header = self.__head
622 header = self.__head
623 if info is None:
623 if info is None:
624 ismagic = 0
624 ismagic = 0
625 isalias = 0
625 isalias = 0
626 ospace = ''
626 ospace = ''
627 else:
627 else:
628 ismagic = info.ismagic
628 ismagic = info.ismagic
629 isalias = info.isalias
629 isalias = info.isalias
630 ospace = info.namespace
630 ospace = info.namespace
631
631
632 # Get docstring, special-casing aliases:
632 # Get docstring, special-casing aliases:
633 if isalias:
633 if isalias:
634 if not callable(obj):
634 if not callable(obj):
635 try:
635 try:
636 ds = "Alias to the system command:\n %s" % obj[1]
636 ds = "Alias to the system command:\n %s" % obj[1]
637 except:
637 except:
638 ds = "Alias: " + str(obj)
638 ds = "Alias: " + str(obj)
639 else:
639 else:
640 ds = "Alias to " + str(obj)
640 ds = "Alias to " + str(obj)
641 if obj.__doc__:
641 if obj.__doc__:
642 ds += "\nDocstring:\n" + obj.__doc__
642 ds += "\nDocstring:\n" + obj.__doc__
643 else:
643 else:
644 ds = getdoc(obj)
644 ds = getdoc(obj)
645 if ds is None:
645 if ds is None:
646 ds = '<no docstring>'
646 ds = '<no docstring>'
647 if formatter is not None:
647 if formatter is not None:
648 ds = formatter(ds)
648 ds = formatter(ds)
649
649
650 # store output in a dict, we initialize it here and fill it as we go
650 # store output in a dict, we initialize it here and fill it as we go
651 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic)
651 out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic)
652
652
653 string_max = 200 # max size of strings to show (snipped if longer)
653 string_max = 200 # max size of strings to show (snipped if longer)
654 shalf = int((string_max -5)/2)
654 shalf = int((string_max -5)/2)
655
655
656 if ismagic:
656 if ismagic:
657 obj_type_name = 'Magic function'
657 obj_type_name = 'Magic function'
658 elif isalias:
658 elif isalias:
659 obj_type_name = 'System alias'
659 obj_type_name = 'System alias'
660 else:
660 else:
661 obj_type_name = obj_type.__name__
661 obj_type_name = obj_type.__name__
662 out['type_name'] = obj_type_name
662 out['type_name'] = obj_type_name
663
663
664 try:
664 try:
665 bclass = obj.__class__
665 bclass = obj.__class__
666 out['base_class'] = str(bclass)
666 out['base_class'] = str(bclass)
667 except: pass
667 except: pass
668
668
669 # String form, but snip if too long in ? form (full in ??)
669 # String form, but snip if too long in ? form (full in ??)
670 if detail_level >= self.str_detail_level:
670 if detail_level >= self.str_detail_level:
671 try:
671 try:
672 ostr = str(obj)
672 ostr = str(obj)
673 str_head = 'string_form'
673 str_head = 'string_form'
674 if not detail_level and len(ostr)>string_max:
674 if not detail_level and len(ostr)>string_max:
675 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
675 ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:]
676 ostr = ("\n" + " " * len(str_head.expandtabs())).\
676 ostr = ("\n" + " " * len(str_head.expandtabs())).\
677 join(q.strip() for q in ostr.split("\n"))
677 join(q.strip() for q in ostr.split("\n"))
678 if ostr.find('\n') > -1:
678 if ostr.find('\n') > -1:
679 # Print multi-line strings starting at the next line.
679 # Print multi-line strings starting at the next line.
680 str_sep = '\n'
680 str_sep = '\n'
681 else:
681 else:
682 str_sep = '\t'
682 str_sep = '\t'
683 out[str_head] = ostr
683 out[str_head] = ostr
684 except:
684 except:
685 pass
685 pass
686
686
687 if ospace:
687 if ospace:
688 out['namespace'] = ospace
688 out['namespace'] = ospace
689
689
690 # Length (for strings and lists)
690 # Length (for strings and lists)
691 try:
691 try:
692 out['length'] = str(len(obj))
692 out['length'] = str(len(obj))
693 except: pass
693 except: pass
694
694
695 # Filename where object was defined
695 # Filename where object was defined
696 binary_file = False
696 binary_file = False
697 try:
697 try:
698 try:
698 try:
699 fname = inspect.getabsfile(obj)
699 fname = inspect.getabsfile(obj)
700 except TypeError:
700 except TypeError:
701 # For an instance, the file that matters is where its class was
701 # For an instance, the file that matters is where its class was
702 # declared.
702 # declared.
703 if hasattr(obj,'__class__'):
703 if hasattr(obj,'__class__'):
704 fname = inspect.getabsfile(obj.__class__)
704 fname = inspect.getabsfile(obj.__class__)
705 if fname.endswith('<string>'):
705 if fname.endswith('<string>'):
706 fname = 'Dynamically generated function. No source code available.'
706 fname = 'Dynamically generated function. No source code available.'
707 if (fname.endswith('.so') or fname.endswith('.dll')):
707 if (fname.endswith('.so') or fname.endswith('.dll')):
708 binary_file = True
708 binary_file = True
709 out['file'] = fname
709 out['file'] = fname
710 except:
710 except:
711 # if anything goes wrong, we don't want to show source, so it's as
711 # if anything goes wrong, we don't want to show source, so it's as
712 # if the file was binary
712 # if the file was binary
713 binary_file = True
713 binary_file = True
714
714
715 # reconstruct the function definition and print it:
715 # reconstruct the function definition and print it:
716 defln = self._getdef(obj, oname)
716 defln = self._getdef(obj, oname)
717 if defln:
717 if defln:
718 out['definition'] = self.format(defln)
718 out['definition'] = self.format(defln)
719
719
720 # Docstrings only in detail 0 mode, since source contains them (we
720 # Docstrings only in detail 0 mode, since source contains them (we
721 # avoid repetitions). If source fails, we add them back, see below.
721 # avoid repetitions). If source fails, we add them back, see below.
722 if ds and detail_level == 0:
722 if ds and detail_level == 0:
723 out['docstring'] = ds
723 out['docstring'] = ds
724
724
725 # Original source code for any callable
725 # Original source code for any callable
726 if detail_level:
726 if detail_level:
727 # Flush the source cache because inspect can return out-of-date
727 # Flush the source cache because inspect can return out-of-date
728 # source
728 # source
729 linecache.checkcache()
729 linecache.checkcache()
730 source_success = False
730 source_success = False
731 try:
731 try:
732 try:
732 try:
733 src = getsource(obj,binary_file)
733 src = getsource(obj,binary_file)
734 except TypeError:
734 except TypeError:
735 if hasattr(obj,'__class__'):
735 if hasattr(obj,'__class__'):
736 src = getsource(obj.__class__,binary_file)
736 src = getsource(obj.__class__,binary_file)
737 if src is not None:
737 if src is not None:
738 source = self.format(src)
738 source = self.format(src)
739 out['source'] = source.rstrip()
739 out['source'] = source.rstrip()
740 source_success = True
740 source_success = True
741 except Exception, msg:
741 except Exception, msg:
742 pass
742 pass
743
743
744 # Constructor docstring for classes
744 # Constructor docstring for classes
745 if inspect.isclass(obj):
745 if inspect.isclass(obj):
746 # reconstruct the function definition and print it:
746 # reconstruct the function definition and print it:
747 try:
747 try:
748 obj_init = obj.__init__
748 obj_init = obj.__init__
749 except AttributeError:
749 except AttributeError:
750 init_def = init_ds = None
750 init_def = init_ds = None
751 else:
751 else:
752 init_def = self._getdef(obj_init,oname)
752 init_def = self._getdef(obj_init,oname)
753 init_ds = getdoc(obj_init)
753 init_ds = getdoc(obj_init)
754 # Skip Python's auto-generated docstrings
754 # Skip Python's auto-generated docstrings
755 if init_ds and \
755 if init_ds and \
756 init_ds.startswith('x.__init__(...) initializes'):
756 init_ds.startswith('x.__init__(...) initializes'):
757 init_ds = None
757 init_ds = None
758
758
759 if init_def or init_ds:
759 if init_def or init_ds:
760 if init_def:
760 if init_def:
761 out['init_definition'] = self.format(init_def)
761 out['init_definition'] = self.format(init_def)
762 if init_ds:
762 if init_ds:
763 out['init_docstring'] = init_ds
763 out['init_docstring'] = init_ds
764
764
765 # and class docstring for instances:
765 # and class docstring for instances:
766 elif obj_type is types.InstanceType or \
766 elif obj_type is types.InstanceType or \
767 isinstance(obj, object):
767 isinstance(obj, object):
768 # First, check whether the instance docstring is identical to the
768 # First, check whether the instance docstring is identical to the
769 # class one, and print it separately if they don't coincide. In
769 # class one, and print it separately if they don't coincide. In
770 # most cases they will, but it's nice to print all the info for
770 # most cases they will, but it's nice to print all the info for
771 # objects which use instance-customized docstrings.
771 # objects which use instance-customized docstrings.
772 if ds:
772 if ds:
773 try:
773 try:
774 cls = getattr(obj,'__class__')
774 cls = getattr(obj,'__class__')
775 except:
775 except:
776 class_ds = None
776 class_ds = None
777 else:
777 else:
778 class_ds = getdoc(cls)
778 class_ds = getdoc(cls)
779 # Skip Python's auto-generated docstrings
779 # Skip Python's auto-generated docstrings
780 if class_ds and \
780 if class_ds and \
781 (class_ds.startswith('function(code, globals[,') or \
781 (class_ds.startswith('function(code, globals[,') or \
782 class_ds.startswith('instancemethod(function, instance,') or \
782 class_ds.startswith('instancemethod(function, instance,') or \
783 class_ds.startswith('module(name[,') ):
783 class_ds.startswith('module(name[,') ):
784 class_ds = None
784 class_ds = None
785 if class_ds and ds != class_ds:
785 if class_ds and ds != class_ds:
786 out['class_docstring'] = class_ds
786 out['class_docstring'] = class_ds
787
787
788 # Next, try to show constructor docstrings
788 # Next, try to show constructor docstrings
789 try:
789 try:
790 init_ds = getdoc(obj.__init__)
790 init_ds = getdoc(obj.__init__)
791 # Skip Python's auto-generated docstrings
791 # Skip Python's auto-generated docstrings
792 if init_ds and \
792 if init_ds and \
793 init_ds.startswith('x.__init__(...) initializes'):
793 init_ds.startswith('x.__init__(...) initializes'):
794 init_ds = None
794 init_ds = None
795 except AttributeError:
795 except AttributeError:
796 init_ds = None
796 init_ds = None
797 if init_ds:
797 if init_ds:
798 out['init_docstring'] = init_ds
798 out['init_docstring'] = init_ds
799
799
800 # Call form docstring for callable instances
800 # Call form docstring for callable instances
801 if hasattr(obj, '__call__'):
801 if hasattr(obj, '__call__'):
802 call_def = self._getdef(obj.__call__, oname)
802 call_def = self._getdef(obj.__call__, oname)
803 if call_def is not None:
803 if call_def is not None:
804 out['call_def'] = self.format(call_def)
804 out['call_def'] = self.format(call_def)
805 call_ds = getdoc(obj.__call__)
805 call_ds = getdoc(obj.__call__)
806 # Skip Python's auto-generated docstrings
806 # Skip Python's auto-generated docstrings
807 if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'):
807 if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'):
808 call_ds = None
808 call_ds = None
809 if call_ds:
809 if call_ds:
810 out['call_docstring'] = call_ds
810 out['call_docstring'] = call_ds
811
811
812 # Compute the object's argspec as a callable. The key is to decide
812 # Compute the object's argspec as a callable. The key is to decide
813 # whether to pull it from the object itself, from its __init__ or
813 # whether to pull it from the object itself, from its __init__ or
814 # from its __call__ method.
814 # from its __call__ method.
815
815
816 if inspect.isclass(obj):
816 if inspect.isclass(obj):
817 callable_obj = obj.__init__
817 callable_obj = obj.__init__
818 elif callable(obj):
818 elif callable(obj):
819 callable_obj = obj
819 callable_obj = obj
820 else:
820 else:
821 callable_obj = None
821 callable_obj = None
822
822
823 if callable_obj:
823 if callable_obj:
824 try:
824 try:
825 args, varargs, varkw, defaults = getargspec(callable_obj)
825 args, varargs, varkw, defaults = getargspec(callable_obj)
826 except (TypeError, AttributeError):
826 except (TypeError, AttributeError):
827 # For extensions/builtins we can't retrieve the argspec
827 # For extensions/builtins we can't retrieve the argspec
828 pass
828 pass
829 else:
829 else:
830 out['argspec'] = dict(args=args, varargs=varargs,
830 out['argspec'] = dict(args=args, varargs=varargs,
831 varkw=varkw, defaults=defaults)
831 varkw=varkw, defaults=defaults)
832
832
833 return object_info(**out)
833 return object_info(**out)
834
834
835
835
836 def psearch(self,pattern,ns_table,ns_search=[],
836 def psearch(self,pattern,ns_table,ns_search=[],
837 ignore_case=False,show_all=False):
837 ignore_case=False,show_all=False):
838 """Search namespaces with wildcards for objects.
838 """Search namespaces with wildcards for objects.
839
839
840 Arguments:
840 Arguments:
841
841
842 - pattern: string containing shell-like wildcards to use in namespace
842 - pattern: string containing shell-like wildcards to use in namespace
843 searches and optionally a type specification to narrow the search to
843 searches and optionally a type specification to narrow the search to
844 objects of that type.
844 objects of that type.
845
845
846 - ns_table: dict of name->namespaces for search.
846 - ns_table: dict of name->namespaces for search.
847
847
848 Optional arguments:
848 Optional arguments:
849
849
850 - ns_search: list of namespace names to include in search.
850 - ns_search: list of namespace names to include in search.
851
851
852 - ignore_case(False): make the search case-insensitive.
852 - ignore_case(False): make the search case-insensitive.
853
853
854 - show_all(False): show all names, including those starting with
854 - show_all(False): show all names, including those starting with
855 underscores.
855 underscores.
856 """
856 """
857 #print 'ps pattern:<%r>' % pattern # dbg
857 #print 'ps pattern:<%r>' % pattern # dbg
858
858
859 # defaults
859 # defaults
860 type_pattern = 'all'
860 type_pattern = 'all'
861 filter = ''
861 filter = ''
862
862
863 cmds = pattern.split()
863 cmds = pattern.split()
864 len_cmds = len(cmds)
864 len_cmds = len(cmds)
865 if len_cmds == 1:
865 if len_cmds == 1:
866 # Only filter pattern given
866 # Only filter pattern given
867 filter = cmds[0]
867 filter = cmds[0]
868 elif len_cmds == 2:
868 elif len_cmds == 2:
869 # Both filter and type specified
869 # Both filter and type specified
870 filter,type_pattern = cmds
870 filter,type_pattern = cmds
871 else:
871 else:
872 raise ValueError('invalid argument string for psearch: <%s>' %
872 raise ValueError('invalid argument string for psearch: <%s>' %
873 pattern)
873 pattern)
874
874
875 # filter search namespaces
875 # filter search namespaces
876 for name in ns_search:
876 for name in ns_search:
877 if name not in ns_table:
877 if name not in ns_table:
878 raise ValueError('invalid namespace <%s>. Valid names: %s' %
878 raise ValueError('invalid namespace <%s>. Valid names: %s' %
879 (name,ns_table.keys()))
879 (name,ns_table.keys()))
880
880
881 #print 'type_pattern:',type_pattern # dbg
881 #print 'type_pattern:',type_pattern # dbg
882 search_result = []
882 search_result = []
883 for ns_name in ns_search:
883 for ns_name in ns_search:
884 ns = ns_table[ns_name]
884 ns = ns_table[ns_name]
885 tmp_res = list(list_namespace(ns,type_pattern,filter,
885 tmp_res = list(list_namespace(ns,type_pattern,filter,
886 ignore_case=ignore_case,
886 ignore_case=ignore_case,
887 show_all=show_all))
887 show_all=show_all))
888 search_result.extend(tmp_res)
888 search_result.extend(tmp_res)
889 search_result.sort()
889 search_result.sort()
890
890
891 page.page('\n'.join(search_result))
891 page.page('\n'.join(search_result))
@@ -1,327 +1,327 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 import IPython.utils.io
39 from IPython.utils import io
40 from IPython.utils.process import system
40 from IPython.utils.process import system
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 >>IPython.utils.io.Term.cout, os.linesep.join(screens[0])
59 print >>io.stdout, 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 >>IPython.utils.io.Term.cout, last_escape + hunk
64 print >>io.stdout, 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 >>IPython.utils.io.Term.cout, last_escape + os.linesep.join(screens[-1])
70 print >>io.stdout, 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.splitlines()[start:]
113 str_lines = strng.splitlines()[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
144
145 # Curses modifies the stdout buffer size by default, which messes
145 # Curses modifies the stdout buffer size by default, which messes
146 # up Python's normal stdout buffering. This would manifest itself
146 # up Python's normal stdout buffering. This would manifest itself
147 # to IPython users as delayed printing on stdout after having used
147 # to IPython users as delayed printing on stdout after having used
148 # the pager.
148 # the pager.
149 #
149 #
150 # We can prevent this by manually setting the NCURSES_NO_SETBUF
150 # We can prevent this by manually setting the NCURSES_NO_SETBUF
151 # environment variable. For more details, see:
151 # environment variable. For more details, see:
152 # http://bugs.python.org/issue10144
152 # http://bugs.python.org/issue10144
153 NCURSES_NO_SETBUF = os.environ.get('NCURSES_NO_SETBUF', None)
153 NCURSES_NO_SETBUF = os.environ.get('NCURSES_NO_SETBUF', None)
154 os.environ['NCURSES_NO_SETBUF'] = ''
154 os.environ['NCURSES_NO_SETBUF'] = ''
155
155
156 # Proceed with curses initialization
156 # Proceed with curses initialization
157 scr = curses.initscr()
157 scr = curses.initscr()
158 screen_lines_real,screen_cols = scr.getmaxyx()
158 screen_lines_real,screen_cols = scr.getmaxyx()
159 curses.endwin()
159 curses.endwin()
160
160
161 # Restore environment
161 # Restore environment
162 if NCURSES_NO_SETBUF is None:
162 if NCURSES_NO_SETBUF is None:
163 del os.environ['NCURSES_NO_SETBUF']
163 del os.environ['NCURSES_NO_SETBUF']
164 else:
164 else:
165 os.environ['NCURSES_NO_SETBUF'] = NCURSES_NO_SETBUF
165 os.environ['NCURSES_NO_SETBUF'] = NCURSES_NO_SETBUF
166
166
167 # Restore terminal state in case endwin() didn't.
167 # Restore terminal state in case endwin() didn't.
168 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
168 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
169 # Now we have what we needed: the screen size in rows/columns
169 # Now we have what we needed: the screen size in rows/columns
170 screen_lines += screen_lines_real
170 screen_lines += screen_lines_real
171 #print '***Screen size:',screen_lines_real,'lines x',\
171 #print '***Screen size:',screen_lines_real,'lines x',\
172 #screen_cols,'columns.' # dbg
172 #screen_cols,'columns.' # dbg
173 else:
173 else:
174 screen_lines += screen_lines_def
174 screen_lines += screen_lines_def
175
175
176 #print 'numlines',numlines,'screenlines',screen_lines # dbg
176 #print 'numlines',numlines,'screenlines',screen_lines # dbg
177 if numlines <= screen_lines :
177 if numlines <= screen_lines :
178 #print '*** normal print' # dbg
178 #print '*** normal print' # dbg
179 print >>IPython.utils.io.Term.cout, str_toprint
179 print >>io.stdout, str_toprint
180 else:
180 else:
181 # Try to open pager and default to internal one if that fails.
181 # Try to open pager and default to internal one if that fails.
182 # All failure modes are tagged as 'retval=1', to match the return
182 # All failure modes are tagged as 'retval=1', to match the return
183 # value of a failed system command. If any intermediate attempt
183 # value of a failed system command. If any intermediate attempt
184 # sets retval to 1, at the end we resort to our own page_dumb() pager.
184 # sets retval to 1, at the end we resort to our own page_dumb() pager.
185 pager_cmd = get_pager_cmd(pager_cmd)
185 pager_cmd = get_pager_cmd(pager_cmd)
186 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
186 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
187 if os.name == 'nt':
187 if os.name == 'nt':
188 if pager_cmd.startswith('type'):
188 if pager_cmd.startswith('type'):
189 # The default WinXP 'type' command is failing on complex strings.
189 # The default WinXP 'type' command is failing on complex strings.
190 retval = 1
190 retval = 1
191 else:
191 else:
192 tmpname = tempfile.mktemp('.txt')
192 tmpname = tempfile.mktemp('.txt')
193 tmpfile = file(tmpname,'wt')
193 tmpfile = file(tmpname,'wt')
194 tmpfile.write(strng)
194 tmpfile.write(strng)
195 tmpfile.close()
195 tmpfile.close()
196 cmd = "%s < %s" % (pager_cmd,tmpname)
196 cmd = "%s < %s" % (pager_cmd,tmpname)
197 if os.system(cmd):
197 if os.system(cmd):
198 retval = 1
198 retval = 1
199 else:
199 else:
200 retval = None
200 retval = None
201 os.remove(tmpname)
201 os.remove(tmpname)
202 else:
202 else:
203 try:
203 try:
204 retval = None
204 retval = None
205 # if I use popen4, things hang. No idea why.
205 # if I use popen4, things hang. No idea why.
206 #pager,shell_out = os.popen4(pager_cmd)
206 #pager,shell_out = os.popen4(pager_cmd)
207 pager = os.popen(pager_cmd,'w')
207 pager = os.popen(pager_cmd,'w')
208 pager.write(strng)
208 pager.write(strng)
209 pager.close()
209 pager.close()
210 retval = pager.close() # success returns None
210 retval = pager.close() # success returns None
211 except IOError,msg: # broken pipe when user quits
211 except IOError,msg: # broken pipe when user quits
212 if msg.args == (32,'Broken pipe'):
212 if msg.args == (32,'Broken pipe'):
213 retval = None
213 retval = None
214 else:
214 else:
215 retval = 1
215 retval = 1
216 except OSError:
216 except OSError:
217 # Other strange problems, sometimes seen in Win2k/cygwin
217 # Other strange problems, sometimes seen in Win2k/cygwin
218 retval = 1
218 retval = 1
219 if retval is not None:
219 if retval is not None:
220 page_dumb(strng,screen_lines=screen_lines)
220 page_dumb(strng,screen_lines=screen_lines)
221
221
222
222
223 def page_file(fname, start=0, pager_cmd=None):
223 def page_file(fname, start=0, pager_cmd=None):
224 """Page a file, using an optional pager command and starting line.
224 """Page a file, using an optional pager command and starting line.
225 """
225 """
226
226
227 pager_cmd = get_pager_cmd(pager_cmd)
227 pager_cmd = get_pager_cmd(pager_cmd)
228 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
228 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
229
229
230 try:
230 try:
231 if os.environ['TERM'] in ['emacs','dumb']:
231 if os.environ['TERM'] in ['emacs','dumb']:
232 raise EnvironmentError
232 raise EnvironmentError
233 system(pager_cmd + ' ' + fname)
233 system(pager_cmd + ' ' + fname)
234 except:
234 except:
235 try:
235 try:
236 if start > 0:
236 if start > 0:
237 start -= 1
237 start -= 1
238 page(open(fname).read(),start)
238 page(open(fname).read(),start)
239 except:
239 except:
240 print 'Unable to show file',`fname`
240 print 'Unable to show file',`fname`
241
241
242
242
243 def get_pager_cmd(pager_cmd=None):
243 def get_pager_cmd(pager_cmd=None):
244 """Return a pager command.
244 """Return a pager command.
245
245
246 Makes some attempts at finding an OS-correct one.
246 Makes some attempts at finding an OS-correct one.
247 """
247 """
248 if os.name == 'posix':
248 if os.name == 'posix':
249 default_pager_cmd = 'less -r' # -r for color control sequences
249 default_pager_cmd = 'less -r' # -r for color control sequences
250 elif os.name in ['nt','dos']:
250 elif os.name in ['nt','dos']:
251 default_pager_cmd = 'type'
251 default_pager_cmd = 'type'
252
252
253 if pager_cmd is None:
253 if pager_cmd is None:
254 try:
254 try:
255 pager_cmd = os.environ['PAGER']
255 pager_cmd = os.environ['PAGER']
256 except:
256 except:
257 pager_cmd = default_pager_cmd
257 pager_cmd = default_pager_cmd
258 return pager_cmd
258 return pager_cmd
259
259
260
260
261 def get_pager_start(pager, start):
261 def get_pager_start(pager, start):
262 """Return the string for paging files with an offset.
262 """Return the string for paging files with an offset.
263
263
264 This is the '+N' argument which less and more (under Unix) accept.
264 This is the '+N' argument which less and more (under Unix) accept.
265 """
265 """
266
266
267 if pager in ['less','more']:
267 if pager in ['less','more']:
268 if start:
268 if start:
269 start_string = '+' + str(start)
269 start_string = '+' + str(start)
270 else:
270 else:
271 start_string = ''
271 start_string = ''
272 else:
272 else:
273 start_string = ''
273 start_string = ''
274 return start_string
274 return start_string
275
275
276
276
277 # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
277 # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
278 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
278 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
279 import msvcrt
279 import msvcrt
280 def page_more():
280 def page_more():
281 """ Smart pausing between pages
281 """ Smart pausing between pages
282
282
283 @return: True if need print more lines, False if quit
283 @return: True if need print more lines, False if quit
284 """
284 """
285 IPython.utils.io.Term.cout.write('---Return to continue, q to quit--- ')
285 io.stdout.write('---Return to continue, q to quit--- ')
286 ans = msvcrt.getch()
286 ans = msvcrt.getch()
287 if ans in ("q", "Q"):
287 if ans in ("q", "Q"):
288 result = False
288 result = False
289 else:
289 else:
290 result = True
290 result = True
291 IPython.utils.io.Term.cout.write("\b"*37 + " "*37 + "\b"*37)
291 io.stdout.write("\b"*37 + " "*37 + "\b"*37)
292 return result
292 return result
293 else:
293 else:
294 def page_more():
294 def page_more():
295 ans = raw_input('---Return to continue, q to quit--- ')
295 ans = raw_input('---Return to continue, q to quit--- ')
296 if ans.lower().startswith('q'):
296 if ans.lower().startswith('q'):
297 return False
297 return False
298 else:
298 else:
299 return True
299 return True
300
300
301
301
302 def snip_print(str,width = 75,print_full = 0,header = ''):
302 def snip_print(str,width = 75,print_full = 0,header = ''):
303 """Print a string snipping the midsection to fit in width.
303 """Print a string snipping the midsection to fit in width.
304
304
305 print_full: mode control:
305 print_full: mode control:
306 - 0: only snip long strings
306 - 0: only snip long strings
307 - 1: send to page() directly.
307 - 1: send to page() directly.
308 - 2: snip long strings and ask for full length viewing with page()
308 - 2: snip long strings and ask for full length viewing with page()
309 Return 1 if snipping was necessary, 0 otherwise."""
309 Return 1 if snipping was necessary, 0 otherwise."""
310
310
311 if print_full == 1:
311 if print_full == 1:
312 page(header+str)
312 page(header+str)
313 return 0
313 return 0
314
314
315 print header,
315 print header,
316 if len(str) < width:
316 if len(str) < width:
317 print str
317 print str
318 snip = 0
318 snip = 0
319 else:
319 else:
320 whalf = int((width -5)/2)
320 whalf = int((width -5)/2)
321 print str[:whalf] + ' <...> ' + str[-whalf:]
321 print str[:whalf] + ' <...> ' + str[-whalf:]
322 snip = 1
322 snip = 1
323 if snip and print_full == 2:
323 if snip and print_full == 2:
324 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
324 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
325 page(str)
325 page(str)
326 return snip
326 return snip
327
327
@@ -1,1014 +1,1013 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.macro import Macro
35 from IPython.core.macro import Macro
36 from IPython.core.splitinput import split_user_input
36 from IPython.core.splitinput import split_user_input
37 from IPython.core import page
37 from IPython.core import page
38
38
39 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance
39 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance
40 import IPython.utils.io
41 from IPython.utils.text import make_quoted_expr
40 from IPython.utils.text import make_quoted_expr
42 from IPython.utils.autoattr import auto_attr
41 from IPython.utils.autoattr import auto_attr
43
42
44 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
45 # Global utilities, errors and constants
44 # Global utilities, errors and constants
46 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
47
46
48 # Warning, these cannot be changed unless various regular expressions
47 # Warning, these cannot be changed unless various regular expressions
49 # 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.
50 ESC_SHELL = '!'
49 ESC_SHELL = '!'
51 ESC_SH_CAP = '!!'
50 ESC_SH_CAP = '!!'
52 ESC_HELP = '?'
51 ESC_HELP = '?'
53 ESC_MAGIC = '%'
52 ESC_MAGIC = '%'
54 ESC_QUOTE = ','
53 ESC_QUOTE = ','
55 ESC_QUOTE2 = ';'
54 ESC_QUOTE2 = ';'
56 ESC_PAREN = '/'
55 ESC_PAREN = '/'
57
56
58
57
59 class PrefilterError(Exception):
58 class PrefilterError(Exception):
60 pass
59 pass
61
60
62
61
63 # RegExp to identify potential function names
62 # RegExp to identify potential function names
64 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_.]*) *$')
65
64
66 # RegExp to exclude strings with this start from autocalling. In
65 # RegExp to exclude strings with this start from autocalling. In
67 # 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
68 # 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
69 # characters '!=()' don't need to be checked for, as the checkPythonChars
68 # characters '!=()' don't need to be checked for, as the checkPythonChars
70 # routine explicitely does so, to catch direct calls and rebindings of
69 # routine explicitely does so, to catch direct calls and rebindings of
71 # existing names.
70 # existing names.
72
71
73 # 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
74 # it affects the rest of the group in square brackets.
73 # it affects the rest of the group in square brackets.
75 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
74 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
76 r'|^is |^not |^in |^and |^or ')
75 r'|^is |^not |^in |^and |^or ')
77
76
78 # 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
79 # (experimental). For this to work, the line_split regexp would need
78 # (experimental). For this to work, the line_split regexp would need
80 # 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
81 # 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_.
82 #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_.\[\]]*) ?$')
83
82
84
83
85 # Handler Check Utilities
84 # Handler Check Utilities
86 def is_shadowed(identifier, ip):
85 def is_shadowed(identifier, ip):
87 """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
88 the alias and magic namespaces? Note that an identifier is different
87 the alias and magic namespaces? Note that an identifier is different
89 than ifun, because it can not contain a '.' character."""
88 than ifun, because it can not contain a '.' character."""
90 # This is much safer than calling ofind, which can change state
89 # This is much safer than calling ofind, which can change state
91 return (identifier in ip.user_ns \
90 return (identifier in ip.user_ns \
92 or identifier in ip.internal_ns \
91 or identifier in ip.internal_ns \
93 or identifier in ip.ns_table['builtin'])
92 or identifier in ip.ns_table['builtin'])
94
93
95
94
96 #-----------------------------------------------------------------------------
95 #-----------------------------------------------------------------------------
97 # The LineInfo class used throughout
96 # The LineInfo class used throughout
98 #-----------------------------------------------------------------------------
97 #-----------------------------------------------------------------------------
99
98
100
99
101 class LineInfo(object):
100 class LineInfo(object):
102 """A single line of input and associated info.
101 """A single line of input and associated info.
103
102
104 Includes the following as properties:
103 Includes the following as properties:
105
104
106 line
105 line
107 The original, raw line
106 The original, raw line
108
107
109 continue_prompt
108 continue_prompt
110 Is this line a continuation in a sequence of multiline input?
109 Is this line a continuation in a sequence of multiline input?
111
110
112 pre
111 pre
113 The initial esc character or whitespace.
112 The initial esc character or whitespace.
114
113
115 pre_char
114 pre_char
116 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.
117 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
118 always be a single character.
117 always be a single character.
119
118
120 pre_whitespace
119 pre_whitespace
121 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,
122 this is just ''.
121 this is just ''.
123
122
124 ifun
123 ifun
125 The 'function part', which is basically the maximal initial sequence
124 The 'function part', which is basically the maximal initial sequence
126 of valid python identifiers and the '.' character. This is what is
125 of valid python identifiers and the '.' character. This is what is
127 checked for alias and magic transformations, used for auto-calling,
126 checked for alias and magic transformations, used for auto-calling,
128 etc.
127 etc.
129
128
130 the_rest
129 the_rest
131 Everything else on the line.
130 Everything else on the line.
132 """
131 """
133 def __init__(self, line, continue_prompt):
132 def __init__(self, line, continue_prompt):
134 self.line = line
133 self.line = line
135 self.continue_prompt = continue_prompt
134 self.continue_prompt = continue_prompt
136 self.pre, self.ifun, self.the_rest = split_user_input(line)
135 self.pre, self.ifun, self.the_rest = split_user_input(line)
137
136
138 self.pre_char = self.pre.strip()
137 self.pre_char = self.pre.strip()
139 if self.pre_char:
138 if self.pre_char:
140 self.pre_whitespace = '' # No whitespace allowd before esc chars
139 self.pre_whitespace = '' # No whitespace allowd before esc chars
141 else:
140 else:
142 self.pre_whitespace = self.pre
141 self.pre_whitespace = self.pre
143
142
144 self._oinfo = None
143 self._oinfo = None
145
144
146 def ofind(self, ip):
145 def ofind(self, ip):
147 """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
148 namespaces for the given IPython InteractiveShell instance.
147 namespaces for the given IPython InteractiveShell instance.
149
148
150 Return a dict with keys: found,obj,ospace,ismagic
149 Return a dict with keys: found,obj,ospace,ismagic
151
150
152 Note: can cause state changes because of calling getattr, but should
151 Note: can cause state changes because of calling getattr, but should
153 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
154 other, less dangerous handlers.
153 other, less dangerous handlers.
155
154
156 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
157 without worrying about *further* damaging state.
156 without worrying about *further* damaging state.
158 """
157 """
159 if not self._oinfo:
158 if not self._oinfo:
160 # ip.shell._ofind is actually on the Magic class!
159 # ip.shell._ofind is actually on the Magic class!
161 self._oinfo = ip.shell._ofind(self.ifun)
160 self._oinfo = ip.shell._ofind(self.ifun)
162 return self._oinfo
161 return self._oinfo
163
162
164 def __str__(self):
163 def __str__(self):
165 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)
166
165
167
166
168 #-----------------------------------------------------------------------------
167 #-----------------------------------------------------------------------------
169 # Main Prefilter manager
168 # Main Prefilter manager
170 #-----------------------------------------------------------------------------
169 #-----------------------------------------------------------------------------
171
170
172
171
173 class PrefilterManager(Configurable):
172 class PrefilterManager(Configurable):
174 """Main prefilter component.
173 """Main prefilter component.
175
174
176 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
177 prefilter consumes lines of input and produces transformed lines of
176 prefilter consumes lines of input and produces transformed lines of
178 input.
177 input.
179
178
180 The iplementation consists of two phases:
179 The iplementation consists of two phases:
181
180
182 1. Transformers
181 1. Transformers
183 2. Checkers and handlers
182 2. Checkers and handlers
184
183
185 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
186 everything in the transformers.
185 everything in the transformers.
187
186
188 The transformers are instances of :class:`PrefilterTransformer` and have
187 The transformers are instances of :class:`PrefilterTransformer` and have
189 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
190 transformed line. The transformation can be accomplished using any
189 transformed line. The transformation can be accomplished using any
191 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
192 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
191 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
193
192
194 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,
195 which are instances of :class:`PrefilterChecker`. The line is passed to
194 which are instances of :class:`PrefilterChecker`. The line is passed to
196 the :meth:`check` method, which either returns `None` or a
195 the :meth:`check` method, which either returns `None` or a
197 :class:`PrefilterHandler` instance. If `None` is returned, the other
196 :class:`PrefilterHandler` instance. If `None` is returned, the other
198 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
197 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
199 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
200 handler and no further checkers are tried.
199 handler and no further checkers are tried.
201
200
202 Both transformers and checkers have a `priority` attribute, that determines
201 Both transformers and checkers have a `priority` attribute, that determines
203 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.
204
203
205 Both transformers and checkers also have `enabled` attribute, which is
204 Both transformers and checkers also have `enabled` attribute, which is
206 a boolean that determines if the instance is used.
205 a boolean that determines if the instance is used.
207
206
208 Users or developers can change the priority or enabled attribute of
207 Users or developers can change the priority or enabled attribute of
209 transformers or checkers, but they must call the :meth:`sort_checkers`
208 transformers or checkers, but they must call the :meth:`sort_checkers`
210 or :meth:`sort_transformers` method after changing the priority.
209 or :meth:`sort_transformers` method after changing the priority.
211 """
210 """
212
211
213 multi_line_specials = CBool(True, config=True)
212 multi_line_specials = CBool(True, config=True)
214 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
213 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
215
214
216 def __init__(self, shell=None, config=None):
215 def __init__(self, shell=None, config=None):
217 super(PrefilterManager, self).__init__(shell=shell, config=config)
216 super(PrefilterManager, self).__init__(shell=shell, config=config)
218 self.shell = shell
217 self.shell = shell
219 self.init_transformers()
218 self.init_transformers()
220 self.init_handlers()
219 self.init_handlers()
221 self.init_checkers()
220 self.init_checkers()
222
221
223 #-------------------------------------------------------------------------
222 #-------------------------------------------------------------------------
224 # API for managing transformers
223 # API for managing transformers
225 #-------------------------------------------------------------------------
224 #-------------------------------------------------------------------------
226
225
227 def init_transformers(self):
226 def init_transformers(self):
228 """Create the default transformers."""
227 """Create the default transformers."""
229 self._transformers = []
228 self._transformers = []
230 for transformer_cls in _default_transformers:
229 for transformer_cls in _default_transformers:
231 transformer_cls(
230 transformer_cls(
232 shell=self.shell, prefilter_manager=self, config=self.config
231 shell=self.shell, prefilter_manager=self, config=self.config
233 )
232 )
234
233
235 def sort_transformers(self):
234 def sort_transformers(self):
236 """Sort the transformers by priority.
235 """Sort the transformers by priority.
237
236
238 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.
239 The :meth:`register_transformer` method calls this automatically.
238 The :meth:`register_transformer` method calls this automatically.
240 """
239 """
241 self._transformers.sort(key=lambda x: x.priority)
240 self._transformers.sort(key=lambda x: x.priority)
242
241
243 @property
242 @property
244 def transformers(self):
243 def transformers(self):
245 """Return a list of checkers, sorted by priority."""
244 """Return a list of checkers, sorted by priority."""
246 return self._transformers
245 return self._transformers
247
246
248 def register_transformer(self, transformer):
247 def register_transformer(self, transformer):
249 """Register a transformer instance."""
248 """Register a transformer instance."""
250 if transformer not in self._transformers:
249 if transformer not in self._transformers:
251 self._transformers.append(transformer)
250 self._transformers.append(transformer)
252 self.sort_transformers()
251 self.sort_transformers()
253
252
254 def unregister_transformer(self, transformer):
253 def unregister_transformer(self, transformer):
255 """Unregister a transformer instance."""
254 """Unregister a transformer instance."""
256 if transformer in self._transformers:
255 if transformer in self._transformers:
257 self._transformers.remove(transformer)
256 self._transformers.remove(transformer)
258
257
259 #-------------------------------------------------------------------------
258 #-------------------------------------------------------------------------
260 # API for managing checkers
259 # API for managing checkers
261 #-------------------------------------------------------------------------
260 #-------------------------------------------------------------------------
262
261
263 def init_checkers(self):
262 def init_checkers(self):
264 """Create the default checkers."""
263 """Create the default checkers."""
265 self._checkers = []
264 self._checkers = []
266 for checker in _default_checkers:
265 for checker in _default_checkers:
267 checker(
266 checker(
268 shell=self.shell, prefilter_manager=self, config=self.config
267 shell=self.shell, prefilter_manager=self, config=self.config
269 )
268 )
270
269
271 def sort_checkers(self):
270 def sort_checkers(self):
272 """Sort the checkers by priority.
271 """Sort the checkers by priority.
273
272
274 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.
275 The :meth:`register_checker` method calls this automatically.
274 The :meth:`register_checker` method calls this automatically.
276 """
275 """
277 self._checkers.sort(key=lambda x: x.priority)
276 self._checkers.sort(key=lambda x: x.priority)
278
277
279 @property
278 @property
280 def checkers(self):
279 def checkers(self):
281 """Return a list of checkers, sorted by priority."""
280 """Return a list of checkers, sorted by priority."""
282 return self._checkers
281 return self._checkers
283
282
284 def register_checker(self, checker):
283 def register_checker(self, checker):
285 """Register a checker instance."""
284 """Register a checker instance."""
286 if checker not in self._checkers:
285 if checker not in self._checkers:
287 self._checkers.append(checker)
286 self._checkers.append(checker)
288 self.sort_checkers()
287 self.sort_checkers()
289
288
290 def unregister_checker(self, checker):
289 def unregister_checker(self, checker):
291 """Unregister a checker instance."""
290 """Unregister a checker instance."""
292 if checker in self._checkers:
291 if checker in self._checkers:
293 self._checkers.remove(checker)
292 self._checkers.remove(checker)
294
293
295 #-------------------------------------------------------------------------
294 #-------------------------------------------------------------------------
296 # API for managing checkers
295 # API for managing checkers
297 #-------------------------------------------------------------------------
296 #-------------------------------------------------------------------------
298
297
299 def init_handlers(self):
298 def init_handlers(self):
300 """Create the default handlers."""
299 """Create the default handlers."""
301 self._handlers = {}
300 self._handlers = {}
302 self._esc_handlers = {}
301 self._esc_handlers = {}
303 for handler in _default_handlers:
302 for handler in _default_handlers:
304 handler(
303 handler(
305 shell=self.shell, prefilter_manager=self, config=self.config
304 shell=self.shell, prefilter_manager=self, config=self.config
306 )
305 )
307
306
308 @property
307 @property
309 def handlers(self):
308 def handlers(self):
310 """Return a dict of all the handlers."""
309 """Return a dict of all the handlers."""
311 return self._handlers
310 return self._handlers
312
311
313 def register_handler(self, name, handler, esc_strings):
312 def register_handler(self, name, handler, esc_strings):
314 """Register a handler instance by name with esc_strings."""
313 """Register a handler instance by name with esc_strings."""
315 self._handlers[name] = handler
314 self._handlers[name] = handler
316 for esc_str in esc_strings:
315 for esc_str in esc_strings:
317 self._esc_handlers[esc_str] = handler
316 self._esc_handlers[esc_str] = handler
318
317
319 def unregister_handler(self, name, handler, esc_strings):
318 def unregister_handler(self, name, handler, esc_strings):
320 """Unregister a handler instance by name with esc_strings."""
319 """Unregister a handler instance by name with esc_strings."""
321 try:
320 try:
322 del self._handlers[name]
321 del self._handlers[name]
323 except KeyError:
322 except KeyError:
324 pass
323 pass
325 for esc_str in esc_strings:
324 for esc_str in esc_strings:
326 h = self._esc_handlers.get(esc_str)
325 h = self._esc_handlers.get(esc_str)
327 if h is handler:
326 if h is handler:
328 del self._esc_handlers[esc_str]
327 del self._esc_handlers[esc_str]
329
328
330 def get_handler_by_name(self, name):
329 def get_handler_by_name(self, name):
331 """Get a handler by its name."""
330 """Get a handler by its name."""
332 return self._handlers.get(name)
331 return self._handlers.get(name)
333
332
334 def get_handler_by_esc(self, esc_str):
333 def get_handler_by_esc(self, esc_str):
335 """Get a handler by its escape string."""
334 """Get a handler by its escape string."""
336 return self._esc_handlers.get(esc_str)
335 return self._esc_handlers.get(esc_str)
337
336
338 #-------------------------------------------------------------------------
337 #-------------------------------------------------------------------------
339 # Main prefiltering API
338 # Main prefiltering API
340 #-------------------------------------------------------------------------
339 #-------------------------------------------------------------------------
341
340
342 def prefilter_line_info(self, line_info):
341 def prefilter_line_info(self, line_info):
343 """Prefilter a line that has been converted to a LineInfo object.
342 """Prefilter a line that has been converted to a LineInfo object.
344
343
345 This implements the checker/handler part of the prefilter pipe.
344 This implements the checker/handler part of the prefilter pipe.
346 """
345 """
347 # print "prefilter_line_info: ", line_info
346 # print "prefilter_line_info: ", line_info
348 handler = self.find_handler(line_info)
347 handler = self.find_handler(line_info)
349 return handler.handle(line_info)
348 return handler.handle(line_info)
350
349
351 def find_handler(self, line_info):
350 def find_handler(self, line_info):
352 """Find a handler for the line_info by trying checkers."""
351 """Find a handler for the line_info by trying checkers."""
353 for checker in self.checkers:
352 for checker in self.checkers:
354 if checker.enabled:
353 if checker.enabled:
355 handler = checker.check(line_info)
354 handler = checker.check(line_info)
356 if handler:
355 if handler:
357 return handler
356 return handler
358 return self.get_handler_by_name('normal')
357 return self.get_handler_by_name('normal')
359
358
360 def transform_line(self, line, continue_prompt):
359 def transform_line(self, line, continue_prompt):
361 """Calls the enabled transformers in order of increasing priority."""
360 """Calls the enabled transformers in order of increasing priority."""
362 for transformer in self.transformers:
361 for transformer in self.transformers:
363 if transformer.enabled:
362 if transformer.enabled:
364 line = transformer.transform(line, continue_prompt)
363 line = transformer.transform(line, continue_prompt)
365 return line
364 return line
366
365
367 def prefilter_line(self, line, continue_prompt=False):
366 def prefilter_line(self, line, continue_prompt=False):
368 """Prefilter a single input line as text.
367 """Prefilter a single input line as text.
369
368
370 This method prefilters a single line of text by calling the
369 This method prefilters a single line of text by calling the
371 transformers and then the checkers/handlers.
370 transformers and then the checkers/handlers.
372 """
371 """
373
372
374 # print "prefilter_line: ", line, continue_prompt
373 # print "prefilter_line: ", line, continue_prompt
375 # All handlers *must* return a value, even if it's blank ('').
374 # All handlers *must* return a value, even if it's blank ('').
376
375
377 # save the line away in case we crash, so the post-mortem handler can
376 # save the line away in case we crash, so the post-mortem handler can
378 # record it
377 # record it
379 self.shell._last_input_line = line
378 self.shell._last_input_line = line
380
379
381 if not line:
380 if not line:
382 # Return immediately on purely empty lines, so that if the user
381 # Return immediately on purely empty lines, so that if the user
383 # previously typed some whitespace that started a continuation
382 # previously typed some whitespace that started a continuation
384 # prompt, he can break out of that loop with just an empty line.
383 # prompt, he can break out of that loop with just an empty line.
385 # This is how the default python prompt works.
384 # This is how the default python prompt works.
386 return ''
385 return ''
387
386
388 # At this point, we invoke our transformers.
387 # At this point, we invoke our transformers.
389 if not continue_prompt or (continue_prompt and self.multi_line_specials):
388 if not continue_prompt or (continue_prompt and self.multi_line_specials):
390 line = self.transform_line(line, continue_prompt)
389 line = self.transform_line(line, continue_prompt)
391
390
392 # Now we compute line_info for the checkers and handlers
391 # Now we compute line_info for the checkers and handlers
393 line_info = LineInfo(line, continue_prompt)
392 line_info = LineInfo(line, continue_prompt)
394
393
395 # the input history needs to track even empty lines
394 # the input history needs to track even empty lines
396 stripped = line.strip()
395 stripped = line.strip()
397
396
398 normal_handler = self.get_handler_by_name('normal')
397 normal_handler = self.get_handler_by_name('normal')
399 if not stripped:
398 if not stripped:
400 if not continue_prompt:
399 if not continue_prompt:
401 self.shell.displayhook.prompt_count -= 1
400 self.shell.displayhook.prompt_count -= 1
402
401
403 return normal_handler.handle(line_info)
402 return normal_handler.handle(line_info)
404
403
405 # special handlers are only allowed for single line statements
404 # special handlers are only allowed for single line statements
406 if continue_prompt and not self.multi_line_specials:
405 if continue_prompt and not self.multi_line_specials:
407 return normal_handler.handle(line_info)
406 return normal_handler.handle(line_info)
408
407
409 prefiltered = self.prefilter_line_info(line_info)
408 prefiltered = self.prefilter_line_info(line_info)
410 # print "prefiltered line: %r" % prefiltered
409 # print "prefiltered line: %r" % prefiltered
411 return prefiltered
410 return prefiltered
412
411
413 def prefilter_lines(self, lines, continue_prompt=False):
412 def prefilter_lines(self, lines, continue_prompt=False):
414 """Prefilter multiple input lines of text.
413 """Prefilter multiple input lines of text.
415
414
416 This is the main entry point for prefiltering multiple lines of
415 This is the main entry point for prefiltering multiple lines of
417 input. This simply calls :meth:`prefilter_line` for each line of
416 input. This simply calls :meth:`prefilter_line` for each line of
418 input.
417 input.
419
418
420 This covers cases where there are multiple lines in the user entry,
419 This covers cases where there are multiple lines in the user entry,
421 which is the case when the user goes back to a multiline history
420 which is the case when the user goes back to a multiline history
422 entry and presses enter.
421 entry and presses enter.
423 """
422 """
424 llines = lines.rstrip('\n').split('\n')
423 llines = lines.rstrip('\n').split('\n')
425 # We can get multiple lines in one shot, where multiline input 'blends'
424 # We can get multiple lines in one shot, where multiline input 'blends'
426 # into one line, in cases like recalling from the readline history
425 # into one line, in cases like recalling from the readline history
427 # buffer. We need to make sure that in such cases, we correctly
426 # buffer. We need to make sure that in such cases, we correctly
428 # communicate downstream which line is first and which are continuation
427 # communicate downstream which line is first and which are continuation
429 # ones.
428 # ones.
430 if len(llines) > 1:
429 if len(llines) > 1:
431 out = '\n'.join([self.prefilter_line(line, lnum>0)
430 out = '\n'.join([self.prefilter_line(line, lnum>0)
432 for lnum, line in enumerate(llines) ])
431 for lnum, line in enumerate(llines) ])
433 else:
432 else:
434 out = self.prefilter_line(llines[0], continue_prompt)
433 out = self.prefilter_line(llines[0], continue_prompt)
435
434
436 return out
435 return out
437
436
438 #-----------------------------------------------------------------------------
437 #-----------------------------------------------------------------------------
439 # Prefilter transformers
438 # Prefilter transformers
440 #-----------------------------------------------------------------------------
439 #-----------------------------------------------------------------------------
441
440
442
441
443 class PrefilterTransformer(Configurable):
442 class PrefilterTransformer(Configurable):
444 """Transform a line of user input."""
443 """Transform a line of user input."""
445
444
446 priority = Int(100, config=True)
445 priority = Int(100, config=True)
447 # Transformers don't currently use shell or prefilter_manager, but as we
446 # Transformers don't currently use shell or prefilter_manager, but as we
448 # move away from checkers and handlers, they will need them.
447 # move away from checkers and handlers, they will need them.
449 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
448 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
450 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
449 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
451 enabled = Bool(True, config=True)
450 enabled = Bool(True, config=True)
452
451
453 def __init__(self, shell=None, prefilter_manager=None, config=None):
452 def __init__(self, shell=None, prefilter_manager=None, config=None):
454 super(PrefilterTransformer, self).__init__(
453 super(PrefilterTransformer, self).__init__(
455 shell=shell, prefilter_manager=prefilter_manager, config=config
454 shell=shell, prefilter_manager=prefilter_manager, config=config
456 )
455 )
457 self.prefilter_manager.register_transformer(self)
456 self.prefilter_manager.register_transformer(self)
458
457
459 def transform(self, line, continue_prompt):
458 def transform(self, line, continue_prompt):
460 """Transform a line, returning the new one."""
459 """Transform a line, returning the new one."""
461 return None
460 return None
462
461
463 def __repr__(self):
462 def __repr__(self):
464 return "<%s(priority=%r, enabled=%r)>" % (
463 return "<%s(priority=%r, enabled=%r)>" % (
465 self.__class__.__name__, self.priority, self.enabled)
464 self.__class__.__name__, self.priority, self.enabled)
466
465
467
466
468 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
467 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
469 r'\s*=\s*!(?P<cmd>.*)')
468 r'\s*=\s*!(?P<cmd>.*)')
470
469
471
470
472 class AssignSystemTransformer(PrefilterTransformer):
471 class AssignSystemTransformer(PrefilterTransformer):
473 """Handle the `files = !ls` syntax."""
472 """Handle the `files = !ls` syntax."""
474
473
475 priority = Int(100, config=True)
474 priority = Int(100, config=True)
476
475
477 def transform(self, line, continue_prompt):
476 def transform(self, line, continue_prompt):
478 m = _assign_system_re.match(line)
477 m = _assign_system_re.match(line)
479 if m is not None:
478 if m is not None:
480 cmd = m.group('cmd')
479 cmd = m.group('cmd')
481 lhs = m.group('lhs')
480 lhs = m.group('lhs')
482 expr = make_quoted_expr("sc =%s" % cmd)
481 expr = make_quoted_expr("sc =%s" % cmd)
483 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
482 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
484 return new_line
483 return new_line
485 return line
484 return line
486
485
487
486
488 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
487 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
489 r'\s*=\s*%(?P<cmd>.*)')
488 r'\s*=\s*%(?P<cmd>.*)')
490
489
491 class AssignMagicTransformer(PrefilterTransformer):
490 class AssignMagicTransformer(PrefilterTransformer):
492 """Handle the `a = %who` syntax."""
491 """Handle the `a = %who` syntax."""
493
492
494 priority = Int(200, config=True)
493 priority = Int(200, config=True)
495
494
496 def transform(self, line, continue_prompt):
495 def transform(self, line, continue_prompt):
497 m = _assign_magic_re.match(line)
496 m = _assign_magic_re.match(line)
498 if m is not None:
497 if m is not None:
499 cmd = m.group('cmd')
498 cmd = m.group('cmd')
500 lhs = m.group('lhs')
499 lhs = m.group('lhs')
501 expr = make_quoted_expr(cmd)
500 expr = make_quoted_expr(cmd)
502 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
501 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
503 return new_line
502 return new_line
504 return line
503 return line
505
504
506
505
507 _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )')
506 _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )')
508
507
509 class PyPromptTransformer(PrefilterTransformer):
508 class PyPromptTransformer(PrefilterTransformer):
510 """Handle inputs that start with '>>> ' syntax."""
509 """Handle inputs that start with '>>> ' syntax."""
511
510
512 priority = Int(50, config=True)
511 priority = Int(50, config=True)
513
512
514 def transform(self, line, continue_prompt):
513 def transform(self, line, continue_prompt):
515
514
516 if not line or line.isspace() or line.strip() == '...':
515 if not line or line.isspace() or line.strip() == '...':
517 # This allows us to recognize multiple input prompts separated by
516 # This allows us to recognize multiple input prompts separated by
518 # blank lines and pasted in a single chunk, very common when
517 # blank lines and pasted in a single chunk, very common when
519 # pasting doctests or long tutorial passages.
518 # pasting doctests or long tutorial passages.
520 return ''
519 return ''
521 m = _classic_prompt_re.match(line)
520 m = _classic_prompt_re.match(line)
522 if m:
521 if m:
523 return line[len(m.group(0)):]
522 return line[len(m.group(0)):]
524 else:
523 else:
525 return line
524 return line
526
525
527
526
528 _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
527 _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
529
528
530 class IPyPromptTransformer(PrefilterTransformer):
529 class IPyPromptTransformer(PrefilterTransformer):
531 """Handle inputs that start classic IPython prompt syntax."""
530 """Handle inputs that start classic IPython prompt syntax."""
532
531
533 priority = Int(50, config=True)
532 priority = Int(50, config=True)
534
533
535 def transform(self, line, continue_prompt):
534 def transform(self, line, continue_prompt):
536
535
537 if not line or line.isspace() or line.strip() == '...':
536 if not line or line.isspace() or line.strip() == '...':
538 # This allows us to recognize multiple input prompts separated by
537 # This allows us to recognize multiple input prompts separated by
539 # blank lines and pasted in a single chunk, very common when
538 # blank lines and pasted in a single chunk, very common when
540 # pasting doctests or long tutorial passages.
539 # pasting doctests or long tutorial passages.
541 return ''
540 return ''
542 m = _ipy_prompt_re.match(line)
541 m = _ipy_prompt_re.match(line)
543 if m:
542 if m:
544 return line[len(m.group(0)):]
543 return line[len(m.group(0)):]
545 else:
544 else:
546 return line
545 return line
547
546
548 #-----------------------------------------------------------------------------
547 #-----------------------------------------------------------------------------
549 # Prefilter checkers
548 # Prefilter checkers
550 #-----------------------------------------------------------------------------
549 #-----------------------------------------------------------------------------
551
550
552
551
553 class PrefilterChecker(Configurable):
552 class PrefilterChecker(Configurable):
554 """Inspect an input line and return a handler for that line."""
553 """Inspect an input line and return a handler for that line."""
555
554
556 priority = Int(100, config=True)
555 priority = Int(100, config=True)
557 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
556 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
558 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
557 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
559 enabled = Bool(True, config=True)
558 enabled = Bool(True, config=True)
560
559
561 def __init__(self, shell=None, prefilter_manager=None, config=None):
560 def __init__(self, shell=None, prefilter_manager=None, config=None):
562 super(PrefilterChecker, self).__init__(
561 super(PrefilterChecker, self).__init__(
563 shell=shell, prefilter_manager=prefilter_manager, config=config
562 shell=shell, prefilter_manager=prefilter_manager, config=config
564 )
563 )
565 self.prefilter_manager.register_checker(self)
564 self.prefilter_manager.register_checker(self)
566
565
567 def check(self, line_info):
566 def check(self, line_info):
568 """Inspect line_info and return a handler instance or None."""
567 """Inspect line_info and return a handler instance or None."""
569 return None
568 return None
570
569
571 def __repr__(self):
570 def __repr__(self):
572 return "<%s(priority=%r, enabled=%r)>" % (
571 return "<%s(priority=%r, enabled=%r)>" % (
573 self.__class__.__name__, self.priority, self.enabled)
572 self.__class__.__name__, self.priority, self.enabled)
574
573
575
574
576 class EmacsChecker(PrefilterChecker):
575 class EmacsChecker(PrefilterChecker):
577
576
578 priority = Int(100, config=True)
577 priority = Int(100, config=True)
579 enabled = Bool(False, config=True)
578 enabled = Bool(False, config=True)
580
579
581 def check(self, line_info):
580 def check(self, line_info):
582 "Emacs ipython-mode tags certain input lines."
581 "Emacs ipython-mode tags certain input lines."
583 if line_info.line.endswith('# PYTHON-MODE'):
582 if line_info.line.endswith('# PYTHON-MODE'):
584 return self.prefilter_manager.get_handler_by_name('emacs')
583 return self.prefilter_manager.get_handler_by_name('emacs')
585 else:
584 else:
586 return None
585 return None
587
586
588
587
589 class ShellEscapeChecker(PrefilterChecker):
588 class ShellEscapeChecker(PrefilterChecker):
590
589
591 priority = Int(200, config=True)
590 priority = Int(200, config=True)
592
591
593 def check(self, line_info):
592 def check(self, line_info):
594 if line_info.line.lstrip().startswith(ESC_SHELL):
593 if line_info.line.lstrip().startswith(ESC_SHELL):
595 return self.prefilter_manager.get_handler_by_name('shell')
594 return self.prefilter_manager.get_handler_by_name('shell')
596
595
597
596
598 class MacroChecker(PrefilterChecker):
597 class MacroChecker(PrefilterChecker):
599
598
600 priority = Int(250, config=True)
599 priority = Int(250, config=True)
601
600
602 def check(self, line_info):
601 def check(self, line_info):
603 obj = self.shell.user_ns.get(line_info.ifun)
602 obj = self.shell.user_ns.get(line_info.ifun)
604 if isinstance(obj, Macro):
603 if isinstance(obj, Macro):
605 return self.prefilter_manager.get_handler_by_name('macro')
604 return self.prefilter_manager.get_handler_by_name('macro')
606 else:
605 else:
607 return None
606 return None
608
607
609
608
610 class IPyAutocallChecker(PrefilterChecker):
609 class IPyAutocallChecker(PrefilterChecker):
611
610
612 priority = Int(300, config=True)
611 priority = Int(300, config=True)
613
612
614 def check(self, line_info):
613 def check(self, line_info):
615 "Instances of IPyAutocall in user_ns get autocalled immediately"
614 "Instances of IPyAutocall in user_ns get autocalled immediately"
616 obj = self.shell.user_ns.get(line_info.ifun, None)
615 obj = self.shell.user_ns.get(line_info.ifun, None)
617 if isinstance(obj, IPyAutocall):
616 if isinstance(obj, IPyAutocall):
618 obj.set_ip(self.shell)
617 obj.set_ip(self.shell)
619 return self.prefilter_manager.get_handler_by_name('auto')
618 return self.prefilter_manager.get_handler_by_name('auto')
620 else:
619 else:
621 return None
620 return None
622
621
623
622
624 class MultiLineMagicChecker(PrefilterChecker):
623 class MultiLineMagicChecker(PrefilterChecker):
625
624
626 priority = Int(400, config=True)
625 priority = Int(400, config=True)
627
626
628 def check(self, line_info):
627 def check(self, line_info):
629 "Allow ! and !! in multi-line statements if multi_line_specials is on"
628 "Allow ! and !! in multi-line statements if multi_line_specials is on"
630 # Note that this one of the only places we check the first character of
629 # Note that this one of the only places we check the first character of
631 # ifun and *not* the pre_char. Also note that the below test matches
630 # ifun and *not* the pre_char. Also note that the below test matches
632 # both ! and !!.
631 # both ! and !!.
633 if line_info.continue_prompt \
632 if line_info.continue_prompt \
634 and self.prefilter_manager.multi_line_specials:
633 and self.prefilter_manager.multi_line_specials:
635 if line_info.ifun.startswith(ESC_MAGIC):
634 if line_info.ifun.startswith(ESC_MAGIC):
636 return self.prefilter_manager.get_handler_by_name('magic')
635 return self.prefilter_manager.get_handler_by_name('magic')
637 else:
636 else:
638 return None
637 return None
639
638
640
639
641 class EscCharsChecker(PrefilterChecker):
640 class EscCharsChecker(PrefilterChecker):
642
641
643 priority = Int(500, config=True)
642 priority = Int(500, config=True)
644
643
645 def check(self, line_info):
644 def check(self, line_info):
646 """Check for escape character and return either a handler to handle it,
645 """Check for escape character and return either a handler to handle it,
647 or None if there is no escape char."""
646 or None if there is no escape char."""
648 if line_info.line[-1] == ESC_HELP \
647 if line_info.line[-1] == ESC_HELP \
649 and line_info.pre_char != ESC_SHELL \
648 and line_info.pre_char != ESC_SHELL \
650 and line_info.pre_char != ESC_SH_CAP:
649 and line_info.pre_char != ESC_SH_CAP:
651 # the ? can be at the end, but *not* for either kind of shell escape,
650 # the ? can be at the end, but *not* for either kind of shell escape,
652 # because a ? can be a vaild final char in a shell cmd
651 # because a ? can be a vaild final char in a shell cmd
653 return self.prefilter_manager.get_handler_by_name('help')
652 return self.prefilter_manager.get_handler_by_name('help')
654 else:
653 else:
655 # This returns None like it should if no handler exists
654 # This returns None like it should if no handler exists
656 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
655 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
657
656
658
657
659 class AssignmentChecker(PrefilterChecker):
658 class AssignmentChecker(PrefilterChecker):
660
659
661 priority = Int(600, config=True)
660 priority = Int(600, config=True)
662
661
663 def check(self, line_info):
662 def check(self, line_info):
664 """Check to see if user is assigning to a var for the first time, in
663 """Check to see if user is assigning to a var for the first time, in
665 which case we want to avoid any sort of automagic / autocall games.
664 which case we want to avoid any sort of automagic / autocall games.
666
665
667 This allows users to assign to either alias or magic names true python
666 This allows users to assign to either alias or magic names true python
668 variables (the magic/alias systems always take second seat to true
667 variables (the magic/alias systems always take second seat to true
669 python code). E.g. ls='hi', or ls,that=1,2"""
668 python code). E.g. ls='hi', or ls,that=1,2"""
670 if line_info.the_rest:
669 if line_info.the_rest:
671 if line_info.the_rest[0] in '=,':
670 if line_info.the_rest[0] in '=,':
672 return self.prefilter_manager.get_handler_by_name('normal')
671 return self.prefilter_manager.get_handler_by_name('normal')
673 else:
672 else:
674 return None
673 return None
675
674
676
675
677 class AutoMagicChecker(PrefilterChecker):
676 class AutoMagicChecker(PrefilterChecker):
678
677
679 priority = Int(700, config=True)
678 priority = Int(700, config=True)
680
679
681 def check(self, line_info):
680 def check(self, line_info):
682 """If the ifun is magic, and automagic is on, run it. Note: normal,
681 """If the ifun is magic, and automagic is on, run it. Note: normal,
683 non-auto magic would already have been triggered via '%' in
682 non-auto magic would already have been triggered via '%' in
684 check_esc_chars. This just checks for automagic. Also, before
683 check_esc_chars. This just checks for automagic. Also, before
685 triggering the magic handler, make sure that there is nothing in the
684 triggering the magic handler, make sure that there is nothing in the
686 user namespace which could shadow it."""
685 user namespace which could shadow it."""
687 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
686 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
688 return None
687 return None
689
688
690 # We have a likely magic method. Make sure we should actually call it.
689 # We have a likely magic method. Make sure we should actually call it.
691 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
690 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
692 return None
691 return None
693
692
694 head = line_info.ifun.split('.',1)[0]
693 head = line_info.ifun.split('.',1)[0]
695 if is_shadowed(head, self.shell):
694 if is_shadowed(head, self.shell):
696 return None
695 return None
697
696
698 return self.prefilter_manager.get_handler_by_name('magic')
697 return self.prefilter_manager.get_handler_by_name('magic')
699
698
700
699
701 class AliasChecker(PrefilterChecker):
700 class AliasChecker(PrefilterChecker):
702
701
703 priority = Int(800, config=True)
702 priority = Int(800, config=True)
704
703
705 def check(self, line_info):
704 def check(self, line_info):
706 "Check if the initital identifier on the line is an alias."
705 "Check if the initital identifier on the line is an alias."
707 # Note: aliases can not contain '.'
706 # Note: aliases can not contain '.'
708 head = line_info.ifun.split('.',1)[0]
707 head = line_info.ifun.split('.',1)[0]
709 if line_info.ifun not in self.shell.alias_manager \
708 if line_info.ifun not in self.shell.alias_manager \
710 or head not in self.shell.alias_manager \
709 or head not in self.shell.alias_manager \
711 or is_shadowed(head, self.shell):
710 or is_shadowed(head, self.shell):
712 return None
711 return None
713
712
714 return self.prefilter_manager.get_handler_by_name('alias')
713 return self.prefilter_manager.get_handler_by_name('alias')
715
714
716
715
717 class PythonOpsChecker(PrefilterChecker):
716 class PythonOpsChecker(PrefilterChecker):
718
717
719 priority = Int(900, config=True)
718 priority = Int(900, config=True)
720
719
721 def check(self, line_info):
720 def check(self, line_info):
722 """If the 'rest' of the line begins with a function call or pretty much
721 """If the 'rest' of the line begins with a function call or pretty much
723 any python operator, we should simply execute the line (regardless of
722 any python operator, we should simply execute the line (regardless of
724 whether or not there's a possible autocall expansion). This avoids
723 whether or not there's a possible autocall expansion). This avoids
725 spurious (and very confusing) geattr() accesses."""
724 spurious (and very confusing) geattr() accesses."""
726 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
725 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
727 return self.prefilter_manager.get_handler_by_name('normal')
726 return self.prefilter_manager.get_handler_by_name('normal')
728 else:
727 else:
729 return None
728 return None
730
729
731
730
732 class AutocallChecker(PrefilterChecker):
731 class AutocallChecker(PrefilterChecker):
733
732
734 priority = Int(1000, config=True)
733 priority = Int(1000, config=True)
735
734
736 def check(self, line_info):
735 def check(self, line_info):
737 "Check if the initial word/function is callable and autocall is on."
736 "Check if the initial word/function is callable and autocall is on."
738 if not self.shell.autocall:
737 if not self.shell.autocall:
739 return None
738 return None
740
739
741 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
740 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
742 if not oinfo['found']:
741 if not oinfo['found']:
743 return None
742 return None
744
743
745 if callable(oinfo['obj']) \
744 if callable(oinfo['obj']) \
746 and (not re_exclude_auto.match(line_info.the_rest)) \
745 and (not re_exclude_auto.match(line_info.the_rest)) \
747 and re_fun_name.match(line_info.ifun):
746 and re_fun_name.match(line_info.ifun):
748 return self.prefilter_manager.get_handler_by_name('auto')
747 return self.prefilter_manager.get_handler_by_name('auto')
749 else:
748 else:
750 return None
749 return None
751
750
752
751
753 #-----------------------------------------------------------------------------
752 #-----------------------------------------------------------------------------
754 # Prefilter handlers
753 # Prefilter handlers
755 #-----------------------------------------------------------------------------
754 #-----------------------------------------------------------------------------
756
755
757
756
758 class PrefilterHandler(Configurable):
757 class PrefilterHandler(Configurable):
759
758
760 handler_name = Str('normal')
759 handler_name = Str('normal')
761 esc_strings = List([])
760 esc_strings = List([])
762 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
761 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
763 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
762 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
764
763
765 def __init__(self, shell=None, prefilter_manager=None, config=None):
764 def __init__(self, shell=None, prefilter_manager=None, config=None):
766 super(PrefilterHandler, self).__init__(
765 super(PrefilterHandler, self).__init__(
767 shell=shell, prefilter_manager=prefilter_manager, config=config
766 shell=shell, prefilter_manager=prefilter_manager, config=config
768 )
767 )
769 self.prefilter_manager.register_handler(
768 self.prefilter_manager.register_handler(
770 self.handler_name,
769 self.handler_name,
771 self,
770 self,
772 self.esc_strings
771 self.esc_strings
773 )
772 )
774
773
775 def handle(self, line_info):
774 def handle(self, line_info):
776 # print "normal: ", line_info
775 # print "normal: ", line_info
777 """Handle normal input lines. Use as a template for handlers."""
776 """Handle normal input lines. Use as a template for handlers."""
778
777
779 # With autoindent on, we need some way to exit the input loop, and I
778 # With autoindent on, we need some way to exit the input loop, and I
780 # don't want to force the user to have to backspace all the way to
779 # don't want to force the user to have to backspace all the way to
781 # clear the line. The rule will be in this case, that either two
780 # clear the line. The rule will be in this case, that either two
782 # lines of pure whitespace in a row, or a line of pure whitespace but
781 # lines of pure whitespace in a row, or a line of pure whitespace but
783 # of a size different to the indent level, will exit the input loop.
782 # of a size different to the indent level, will exit the input loop.
784 line = line_info.line
783 line = line_info.line
785 continue_prompt = line_info.continue_prompt
784 continue_prompt = line_info.continue_prompt
786
785
787 if (continue_prompt and
786 if (continue_prompt and
788 self.shell.autoindent and
787 self.shell.autoindent and
789 line.isspace() and
788 line.isspace() and
790 0 < abs(len(line) - self.shell.indent_current_nsp) <= 2):
789 0 < abs(len(line) - self.shell.indent_current_nsp) <= 2):
791 line = ''
790 line = ''
792
791
793 return line
792 return line
794
793
795 def __str__(self):
794 def __str__(self):
796 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
795 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
797
796
798
797
799 class AliasHandler(PrefilterHandler):
798 class AliasHandler(PrefilterHandler):
800
799
801 handler_name = Str('alias')
800 handler_name = Str('alias')
802
801
803 def handle(self, line_info):
802 def handle(self, line_info):
804 """Handle alias input lines. """
803 """Handle alias input lines. """
805 transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
804 transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
806 # pre is needed, because it carries the leading whitespace. Otherwise
805 # pre is needed, because it carries the leading whitespace. Otherwise
807 # aliases won't work in indented sections.
806 # aliases won't work in indented sections.
808 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
807 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
809 make_quoted_expr(transformed))
808 make_quoted_expr(transformed))
810
809
811 return line_out
810 return line_out
812
811
813
812
814 class ShellEscapeHandler(PrefilterHandler):
813 class ShellEscapeHandler(PrefilterHandler):
815
814
816 handler_name = Str('shell')
815 handler_name = Str('shell')
817 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
816 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
818
817
819 def handle(self, line_info):
818 def handle(self, line_info):
820 """Execute the line in a shell, empty return value"""
819 """Execute the line in a shell, empty return value"""
821 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
820 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
822
821
823 line = line_info.line
822 line = line_info.line
824 if line.lstrip().startswith(ESC_SH_CAP):
823 if line.lstrip().startswith(ESC_SH_CAP):
825 # rewrite LineInfo's line, ifun and the_rest to properly hold the
824 # rewrite LineInfo's line, ifun and the_rest to properly hold the
826 # call to %sx and the actual command to be executed, so
825 # call to %sx and the actual command to be executed, so
827 # handle_magic can work correctly. Note that this works even if
826 # handle_magic can work correctly. Note that this works even if
828 # the line is indented, so it handles multi_line_specials
827 # the line is indented, so it handles multi_line_specials
829 # properly.
828 # properly.
830 new_rest = line.lstrip()[2:]
829 new_rest = line.lstrip()[2:]
831 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
830 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
832 line_info.ifun = 'sx'
831 line_info.ifun = 'sx'
833 line_info.the_rest = new_rest
832 line_info.the_rest = new_rest
834 return magic_handler.handle(line_info)
833 return magic_handler.handle(line_info)
835 else:
834 else:
836 cmd = line.lstrip().lstrip(ESC_SHELL)
835 cmd = line.lstrip().lstrip(ESC_SHELL)
837 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
836 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
838 make_quoted_expr(cmd))
837 make_quoted_expr(cmd))
839 return line_out
838 return line_out
840
839
841
840
842 class MacroHandler(PrefilterHandler):
841 class MacroHandler(PrefilterHandler):
843 handler_name = Str("macro")
842 handler_name = Str("macro")
844
843
845 def handle(self, line_info):
844 def handle(self, line_info):
846 obj = self.shell.user_ns.get(line_info.ifun)
845 obj = self.shell.user_ns.get(line_info.ifun)
847 pre_space = line_info.pre_whitespace
846 pre_space = line_info.pre_whitespace
848 line_sep = "\n" + pre_space
847 line_sep = "\n" + pre_space
849 return pre_space + line_sep.join(obj.value.splitlines())
848 return pre_space + line_sep.join(obj.value.splitlines())
850
849
851
850
852 class MagicHandler(PrefilterHandler):
851 class MagicHandler(PrefilterHandler):
853
852
854 handler_name = Str('magic')
853 handler_name = Str('magic')
855 esc_strings = List([ESC_MAGIC])
854 esc_strings = List([ESC_MAGIC])
856
855
857 def handle(self, line_info):
856 def handle(self, line_info):
858 """Execute magic functions."""
857 """Execute magic functions."""
859 ifun = line_info.ifun
858 ifun = line_info.ifun
860 the_rest = line_info.the_rest
859 the_rest = line_info.the_rest
861 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
860 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
862 make_quoted_expr(ifun + " " + the_rest))
861 make_quoted_expr(ifun + " " + the_rest))
863 return cmd
862 return cmd
864
863
865
864
866 class AutoHandler(PrefilterHandler):
865 class AutoHandler(PrefilterHandler):
867
866
868 handler_name = Str('auto')
867 handler_name = Str('auto')
869 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
868 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
870
869
871 def handle(self, line_info):
870 def handle(self, line_info):
872 """Handle lines which can be auto-executed, quoting if requested."""
871 """Handle lines which can be auto-executed, quoting if requested."""
873 line = line_info.line
872 line = line_info.line
874 ifun = line_info.ifun
873 ifun = line_info.ifun
875 the_rest = line_info.the_rest
874 the_rest = line_info.the_rest
876 pre = line_info.pre
875 pre = line_info.pre
877 continue_prompt = line_info.continue_prompt
876 continue_prompt = line_info.continue_prompt
878 obj = line_info.ofind(self)['obj']
877 obj = line_info.ofind(self)['obj']
879 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
878 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
880
879
881 # This should only be active for single-line input!
880 # This should only be active for single-line input!
882 if continue_prompt:
881 if continue_prompt:
883 return line
882 return line
884
883
885 force_auto = isinstance(obj, IPyAutocall)
884 force_auto = isinstance(obj, IPyAutocall)
886 auto_rewrite = getattr(obj, 'rewrite', True)
885 auto_rewrite = getattr(obj, 'rewrite', True)
887
886
888 if pre == ESC_QUOTE:
887 if pre == ESC_QUOTE:
889 # Auto-quote splitting on whitespace
888 # Auto-quote splitting on whitespace
890 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
889 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
891 elif pre == ESC_QUOTE2:
890 elif pre == ESC_QUOTE2:
892 # Auto-quote whole string
891 # Auto-quote whole string
893 newcmd = '%s("%s")' % (ifun,the_rest)
892 newcmd = '%s("%s")' % (ifun,the_rest)
894 elif pre == ESC_PAREN:
893 elif pre == ESC_PAREN:
895 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
894 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
896 else:
895 else:
897 # Auto-paren.
896 # Auto-paren.
898 # We only apply it to argument-less calls if the autocall
897 # We only apply it to argument-less calls if the autocall
899 # parameter is set to 2. We only need to check that autocall is <
898 # parameter is set to 2. We only need to check that autocall is <
900 # 2, since this function isn't called unless it's at least 1.
899 # 2, since this function isn't called unless it's at least 1.
901 if not the_rest and (self.shell.autocall < 2) and not force_auto:
900 if not the_rest and (self.shell.autocall < 2) and not force_auto:
902 newcmd = '%s %s' % (ifun,the_rest)
901 newcmd = '%s %s' % (ifun,the_rest)
903 auto_rewrite = False
902 auto_rewrite = False
904 else:
903 else:
905 if not force_auto and the_rest.startswith('['):
904 if not force_auto and the_rest.startswith('['):
906 if hasattr(obj,'__getitem__'):
905 if hasattr(obj,'__getitem__'):
907 # Don't autocall in this case: item access for an object
906 # Don't autocall in this case: item access for an object
908 # which is BOTH callable and implements __getitem__.
907 # which is BOTH callable and implements __getitem__.
909 newcmd = '%s %s' % (ifun,the_rest)
908 newcmd = '%s %s' % (ifun,the_rest)
910 auto_rewrite = False
909 auto_rewrite = False
911 else:
910 else:
912 # if the object doesn't support [] access, go ahead and
911 # if the object doesn't support [] access, go ahead and
913 # autocall
912 # autocall
914 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
913 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
915 elif the_rest.endswith(';'):
914 elif the_rest.endswith(';'):
916 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
915 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
917 else:
916 else:
918 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
917 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
919
918
920 if auto_rewrite:
919 if auto_rewrite:
921 self.shell.auto_rewrite_input(newcmd)
920 self.shell.auto_rewrite_input(newcmd)
922
921
923 return newcmd
922 return newcmd
924
923
925
924
926 class HelpHandler(PrefilterHandler):
925 class HelpHandler(PrefilterHandler):
927
926
928 handler_name = Str('help')
927 handler_name = Str('help')
929 esc_strings = List([ESC_HELP])
928 esc_strings = List([ESC_HELP])
930
929
931 def handle(self, line_info):
930 def handle(self, line_info):
932 """Try to get some help for the object.
931 """Try to get some help for the object.
933
932
934 obj? or ?obj -> basic information.
933 obj? or ?obj -> basic information.
935 obj?? or ??obj -> more details.
934 obj?? or ??obj -> more details.
936 """
935 """
937 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
936 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
938 line = line_info.line
937 line = line_info.line
939 # We need to make sure that we don't process lines which would be
938 # We need to make sure that we don't process lines which would be
940 # otherwise valid python, such as "x=1 # what?"
939 # otherwise valid python, such as "x=1 # what?"
941 try:
940 try:
942 codeop.compile_command(line)
941 codeop.compile_command(line)
943 except SyntaxError:
942 except SyntaxError:
944 # We should only handle as help stuff which is NOT valid syntax
943 # We should only handle as help stuff which is NOT valid syntax
945 if line[0]==ESC_HELP:
944 if line[0]==ESC_HELP:
946 line = line[1:]
945 line = line[1:]
947 elif line[-1]==ESC_HELP:
946 elif line[-1]==ESC_HELP:
948 line = line[:-1]
947 line = line[:-1]
949 if line:
948 if line:
950 #print 'line:<%r>' % line # dbg
949 #print 'line:<%r>' % line # dbg
951 self.shell.magic_pinfo(line)
950 self.shell.magic_pinfo(line)
952 else:
951 else:
953 self.shell.show_usage()
952 self.shell.show_usage()
954 return '' # Empty string is needed here!
953 return '' # Empty string is needed here!
955 except:
954 except:
956 raise
955 raise
957 # Pass any other exceptions through to the normal handler
956 # Pass any other exceptions through to the normal handler
958 return normal_handler.handle(line_info)
957 return normal_handler.handle(line_info)
959 else:
958 else:
960 # If the code compiles ok, we should handle it normally
959 # If the code compiles ok, we should handle it normally
961 return normal_handler.handle(line_info)
960 return normal_handler.handle(line_info)
962
961
963
962
964 class EmacsHandler(PrefilterHandler):
963 class EmacsHandler(PrefilterHandler):
965
964
966 handler_name = Str('emacs')
965 handler_name = Str('emacs')
967 esc_strings = List([])
966 esc_strings = List([])
968
967
969 def handle(self, line_info):
968 def handle(self, line_info):
970 """Handle input lines marked by python-mode."""
969 """Handle input lines marked by python-mode."""
971
970
972 # Currently, nothing is done. Later more functionality can be added
971 # Currently, nothing is done. Later more functionality can be added
973 # here if needed.
972 # here if needed.
974
973
975 # The input cache shouldn't be updated
974 # The input cache shouldn't be updated
976 return line_info.line
975 return line_info.line
977
976
978
977
979 #-----------------------------------------------------------------------------
978 #-----------------------------------------------------------------------------
980 # Defaults
979 # Defaults
981 #-----------------------------------------------------------------------------
980 #-----------------------------------------------------------------------------
982
981
983
982
984 _default_transformers = [
983 _default_transformers = [
985 AssignSystemTransformer,
984 AssignSystemTransformer,
986 AssignMagicTransformer,
985 AssignMagicTransformer,
987 PyPromptTransformer,
986 PyPromptTransformer,
988 IPyPromptTransformer,
987 IPyPromptTransformer,
989 ]
988 ]
990
989
991 _default_checkers = [
990 _default_checkers = [
992 EmacsChecker,
991 EmacsChecker,
993 ShellEscapeChecker,
992 ShellEscapeChecker,
994 MacroChecker,
993 MacroChecker,
995 IPyAutocallChecker,
994 IPyAutocallChecker,
996 MultiLineMagicChecker,
995 MultiLineMagicChecker,
997 EscCharsChecker,
996 EscCharsChecker,
998 AssignmentChecker,
997 AssignmentChecker,
999 AutoMagicChecker,
998 AutoMagicChecker,
1000 AliasChecker,
999 AliasChecker,
1001 PythonOpsChecker,
1000 PythonOpsChecker,
1002 AutocallChecker
1001 AutocallChecker
1003 ]
1002 ]
1004
1003
1005 _default_handlers = [
1004 _default_handlers = [
1006 PrefilterHandler,
1005 PrefilterHandler,
1007 AliasHandler,
1006 AliasHandler,
1008 ShellEscapeHandler,
1007 ShellEscapeHandler,
1009 MacroHandler,
1008 MacroHandler,
1010 MagicHandler,
1009 MagicHandler,
1011 AutoHandler,
1010 AutoHandler,
1012 HelpHandler,
1011 HelpHandler,
1013 EmacsHandler
1012 EmacsHandler
1014 ]
1013 ]
@@ -1,1243 +1,1243 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 sys
80 import sys
81 import time
81 import time
82 import tokenize
82 import tokenize
83 import traceback
83 import traceback
84 import types
84 import types
85
85
86 # For purposes of monkeypatching inspect to fix a bug in it.
86 # For purposes of monkeypatching inspect to fix a bug in it.
87 from inspect import getsourcefile, getfile, getmodule,\
87 from inspect import getsourcefile, getfile, getmodule,\
88 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
88 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
89
89
90 # IPython's own modules
90 # IPython's own modules
91 # Modified pdb which doesn't damage IPython's readline handling
91 # Modified pdb which doesn't damage IPython's readline handling
92 from IPython.core import debugger, ipapi
92 from IPython.core import debugger, ipapi
93 from IPython.core.display_trap import DisplayTrap
93 from IPython.core.display_trap import DisplayTrap
94 from IPython.core.excolors import exception_colors
94 from IPython.core.excolors import exception_colors
95 from IPython.utils import PyColorize
95 from IPython.utils import PyColorize
96 from IPython.utils import io
96 from IPython.utils import io
97 from IPython.utils.data import uniq_stable
97 from IPython.utils.data import uniq_stable
98 from IPython.utils.warn import info, error
98 from IPython.utils.warn import info, error
99
99
100 # Globals
100 # Globals
101 # amount of space to put line numbers before verbose tracebacks
101 # amount of space to put line numbers before verbose tracebacks
102 INDENT_SIZE = 8
102 INDENT_SIZE = 8
103
103
104 # Default color scheme. This is used, for example, by the traceback
104 # Default color scheme. This is used, for example, by the traceback
105 # formatter. When running in an actual IPython instance, the user's rc.colors
105 # formatter. When running in an actual IPython instance, the user's rc.colors
106 # value is used, but havinga module global makes this functionality available
106 # value is used, but havinga module global makes this functionality available
107 # to users of ultratb who are NOT running inside ipython.
107 # to users of ultratb who are NOT running inside ipython.
108 DEFAULT_SCHEME = 'NoColor'
108 DEFAULT_SCHEME = 'NoColor'
109
109
110 #---------------------------------------------------------------------------
110 #---------------------------------------------------------------------------
111 # Code begins
111 # Code begins
112
112
113 # Utility functions
113 # Utility functions
114 def inspect_error():
114 def inspect_error():
115 """Print a message about internal inspect errors.
115 """Print a message about internal inspect errors.
116
116
117 These are unfortunately quite common."""
117 These are unfortunately quite common."""
118
118
119 error('Internal Python error in the inspect module.\n'
119 error('Internal Python error in the inspect module.\n'
120 'Below is the traceback from this internal error.\n')
120 'Below is the traceback from this internal error.\n')
121
121
122
122
123 def findsource(object):
123 def findsource(object):
124 """Return the entire source file and starting line number for an object.
124 """Return the entire source file and starting line number for an object.
125
125
126 The argument may be a module, class, method, function, traceback, frame,
126 The argument may be a module, class, method, function, traceback, frame,
127 or code object. The source code is returned as a list of all the lines
127 or code object. The source code is returned as a list of all the lines
128 in the file and the line number indexes a line in that list. An IOError
128 in the file and the line number indexes a line in that list. An IOError
129 is raised if the source code cannot be retrieved.
129 is raised if the source code cannot be retrieved.
130
130
131 FIXED version with which we monkeypatch the stdlib to work around a bug."""
131 FIXED version with which we monkeypatch the stdlib to work around a bug."""
132
132
133 file = getsourcefile(object) or getfile(object)
133 file = getsourcefile(object) or getfile(object)
134 # If the object is a frame, then trying to get the globals dict from its
134 # If the object is a frame, then trying to get the globals dict from its
135 # module won't work. Instead, the frame object itself has the globals
135 # module won't work. Instead, the frame object itself has the globals
136 # dictionary.
136 # dictionary.
137 globals_dict = None
137 globals_dict = None
138 if inspect.isframe(object):
138 if inspect.isframe(object):
139 # XXX: can this ever be false?
139 # XXX: can this ever be false?
140 globals_dict = object.f_globals
140 globals_dict = object.f_globals
141 else:
141 else:
142 module = getmodule(object, file)
142 module = getmodule(object, file)
143 if module:
143 if module:
144 globals_dict = module.__dict__
144 globals_dict = module.__dict__
145 lines = linecache.getlines(file, globals_dict)
145 lines = linecache.getlines(file, globals_dict)
146 if not lines:
146 if not lines:
147 raise IOError('could not get source code')
147 raise IOError('could not get source code')
148
148
149 if ismodule(object):
149 if ismodule(object):
150 return lines, 0
150 return lines, 0
151
151
152 if isclass(object):
152 if isclass(object):
153 name = object.__name__
153 name = object.__name__
154 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
154 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
155 # make some effort to find the best matching class definition:
155 # make some effort to find the best matching class definition:
156 # use the one with the least indentation, which is the one
156 # use the one with the least indentation, which is the one
157 # that's most probably not inside a function definition.
157 # that's most probably not inside a function definition.
158 candidates = []
158 candidates = []
159 for i in range(len(lines)):
159 for i in range(len(lines)):
160 match = pat.match(lines[i])
160 match = pat.match(lines[i])
161 if match:
161 if match:
162 # if it's at toplevel, it's already the best one
162 # if it's at toplevel, it's already the best one
163 if lines[i][0] == 'c':
163 if lines[i][0] == 'c':
164 return lines, i
164 return lines, i
165 # else add whitespace to candidate list
165 # else add whitespace to candidate list
166 candidates.append((match.group(1), i))
166 candidates.append((match.group(1), i))
167 if candidates:
167 if candidates:
168 # this will sort by whitespace, and by line number,
168 # this will sort by whitespace, and by line number,
169 # less whitespace first
169 # less whitespace first
170 candidates.sort()
170 candidates.sort()
171 return lines, candidates[0][1]
171 return lines, candidates[0][1]
172 else:
172 else:
173 raise IOError('could not find class definition')
173 raise IOError('could not find class definition')
174
174
175 if ismethod(object):
175 if ismethod(object):
176 object = object.im_func
176 object = object.im_func
177 if isfunction(object):
177 if isfunction(object):
178 object = object.func_code
178 object = object.func_code
179 if istraceback(object):
179 if istraceback(object):
180 object = object.tb_frame
180 object = object.tb_frame
181 if isframe(object):
181 if isframe(object):
182 object = object.f_code
182 object = object.f_code
183 if iscode(object):
183 if iscode(object):
184 if not hasattr(object, 'co_firstlineno'):
184 if not hasattr(object, 'co_firstlineno'):
185 raise IOError('could not find function definition')
185 raise IOError('could not find function definition')
186 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
186 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
187 pmatch = pat.match
187 pmatch = pat.match
188 # fperez - fix: sometimes, co_firstlineno can give a number larger than
188 # fperez - fix: sometimes, co_firstlineno can give a number larger than
189 # the length of lines, which causes an error. Safeguard against that.
189 # the length of lines, which causes an error. Safeguard against that.
190 lnum = min(object.co_firstlineno,len(lines))-1
190 lnum = min(object.co_firstlineno,len(lines))-1
191 while lnum > 0:
191 while lnum > 0:
192 if pmatch(lines[lnum]): break
192 if pmatch(lines[lnum]): break
193 lnum -= 1
193 lnum -= 1
194
194
195 return lines, lnum
195 return lines, lnum
196 raise IOError('could not find code object')
196 raise IOError('could not find code object')
197
197
198 # Monkeypatch inspect to apply our bugfix. This code only works with py25
198 # Monkeypatch inspect to apply our bugfix. This code only works with py25
199 if sys.version_info[:2] >= (2,5):
199 if sys.version_info[:2] >= (2,5):
200 inspect.findsource = findsource
200 inspect.findsource = findsource
201
201
202 def fix_frame_records_filenames(records):
202 def fix_frame_records_filenames(records):
203 """Try to fix the filenames in each record from inspect.getinnerframes().
203 """Try to fix the filenames in each record from inspect.getinnerframes().
204
204
205 Particularly, modules loaded from within zip files have useless filenames
205 Particularly, modules loaded from within zip files have useless filenames
206 attached to their code object, and inspect.getinnerframes() just uses it.
206 attached to their code object, and inspect.getinnerframes() just uses it.
207 """
207 """
208 fixed_records = []
208 fixed_records = []
209 for frame, filename, line_no, func_name, lines, index in records:
209 for frame, filename, line_no, func_name, lines, index in records:
210 # Look inside the frame's globals dictionary for __file__, which should
210 # Look inside the frame's globals dictionary for __file__, which should
211 # be better.
211 # be better.
212 better_fn = frame.f_globals.get('__file__', None)
212 better_fn = frame.f_globals.get('__file__', None)
213 if isinstance(better_fn, str):
213 if isinstance(better_fn, str):
214 # Check the type just in case someone did something weird with
214 # Check the type just in case someone did something weird with
215 # __file__. It might also be None if the error occurred during
215 # __file__. It might also be None if the error occurred during
216 # import.
216 # import.
217 filename = better_fn
217 filename = better_fn
218 fixed_records.append((frame, filename, line_no, func_name, lines, index))
218 fixed_records.append((frame, filename, line_no, func_name, lines, index))
219 return fixed_records
219 return fixed_records
220
220
221
221
222 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
222 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
223 import linecache
223 import linecache
224 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
224 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
225
225
226 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
226 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
227
227
228 # If the error is at the console, don't build any context, since it would
228 # If the error is at the console, don't build any context, since it would
229 # otherwise produce 5 blank lines printed out (there is no file at the
229 # otherwise produce 5 blank lines printed out (there is no file at the
230 # console)
230 # console)
231 rec_check = records[tb_offset:]
231 rec_check = records[tb_offset:]
232 try:
232 try:
233 rname = rec_check[0][1]
233 rname = rec_check[0][1]
234 if rname == '<ipython console>' or rname.endswith('<string>'):
234 if rname == '<ipython console>' or rname.endswith('<string>'):
235 return rec_check
235 return rec_check
236 except IndexError:
236 except IndexError:
237 pass
237 pass
238
238
239 aux = traceback.extract_tb(etb)
239 aux = traceback.extract_tb(etb)
240 assert len(records) == len(aux)
240 assert len(records) == len(aux)
241 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
241 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
242 maybeStart = lnum-1 - context//2
242 maybeStart = lnum-1 - context//2
243 start = max(maybeStart, 0)
243 start = max(maybeStart, 0)
244 end = start + context
244 end = start + context
245 lines = linecache.getlines(file)[start:end]
245 lines = linecache.getlines(file)[start:end]
246 buf = list(records[i])
246 buf = list(records[i])
247 buf[LNUM_POS] = lnum
247 buf[LNUM_POS] = lnum
248 buf[INDEX_POS] = lnum - 1 - start
248 buf[INDEX_POS] = lnum - 1 - start
249 buf[LINES_POS] = lines
249 buf[LINES_POS] = lines
250 records[i] = tuple(buf)
250 records[i] = tuple(buf)
251 return records[tb_offset:]
251 return records[tb_offset:]
252
252
253 # Helper function -- largely belongs to VerboseTB, but we need the same
253 # Helper function -- largely belongs to VerboseTB, but we need the same
254 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
254 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
255 # can be recognized properly by ipython.el's py-traceback-line-re
255 # can be recognized properly by ipython.el's py-traceback-line-re
256 # (SyntaxErrors have to be treated specially because they have no traceback)
256 # (SyntaxErrors have to be treated specially because they have no traceback)
257
257
258 _parser = PyColorize.Parser()
258 _parser = PyColorize.Parser()
259
259
260 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
260 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
261 numbers_width = INDENT_SIZE - 1
261 numbers_width = INDENT_SIZE - 1
262 res = []
262 res = []
263 i = lnum - index
263 i = lnum - index
264
264
265 # This lets us get fully syntax-highlighted tracebacks.
265 # This lets us get fully syntax-highlighted tracebacks.
266 if scheme is None:
266 if scheme is None:
267 ipinst = ipapi.get()
267 ipinst = ipapi.get()
268 if ipinst is not None:
268 if ipinst is not None:
269 scheme = ipinst.colors
269 scheme = ipinst.colors
270 else:
270 else:
271 scheme = DEFAULT_SCHEME
271 scheme = DEFAULT_SCHEME
272
272
273 _line_format = _parser.format2
273 _line_format = _parser.format2
274
274
275 for line in lines:
275 for line in lines:
276 # FIXME: we need to ensure the source is a pure string at this point,
276 # FIXME: we need to ensure the source is a pure string at this point,
277 # else the coloring code makes a royal mess. This is in need of a
277 # else the coloring code makes a royal mess. This is in need of a
278 # serious refactoring, so that all of the ultratb and PyColorize code
278 # serious refactoring, so that all of the ultratb and PyColorize code
279 # is unicode-safe. So for now this is rather an ugly hack, but
279 # is unicode-safe. So for now this is rather an ugly hack, but
280 # necessary to at least have readable tracebacks. Improvements welcome!
280 # necessary to at least have readable tracebacks. Improvements welcome!
281 if type(line)==unicode:
281 if type(line)==unicode:
282 line = line.encode('utf-8', 'replace')
282 line = line.encode('utf-8', 'replace')
283
283
284 new_line, err = _line_format(line, 'str', scheme)
284 new_line, err = _line_format(line, 'str', scheme)
285 if not err: line = new_line
285 if not err: line = new_line
286
286
287 if i == lnum:
287 if i == lnum:
288 # This is the line with the error
288 # This is the line with the error
289 pad = numbers_width - len(str(i))
289 pad = numbers_width - len(str(i))
290 if pad >= 3:
290 if pad >= 3:
291 marker = '-'*(pad-3) + '-> '
291 marker = '-'*(pad-3) + '-> '
292 elif pad == 2:
292 elif pad == 2:
293 marker = '> '
293 marker = '> '
294 elif pad == 1:
294 elif pad == 1:
295 marker = '>'
295 marker = '>'
296 else:
296 else:
297 marker = ''
297 marker = ''
298 num = marker + str(i)
298 num = marker + str(i)
299 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
299 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
300 Colors.line, line, Colors.Normal)
300 Colors.line, line, Colors.Normal)
301 else:
301 else:
302 num = '%*s' % (numbers_width,i)
302 num = '%*s' % (numbers_width,i)
303 line = '%s%s%s %s' %(Colors.lineno, num,
303 line = '%s%s%s %s' %(Colors.lineno, num,
304 Colors.Normal, line)
304 Colors.Normal, line)
305
305
306 res.append(line)
306 res.append(line)
307 if lvals and i == lnum:
307 if lvals and i == lnum:
308 res.append(lvals + '\n')
308 res.append(lvals + '\n')
309 i = i + 1
309 i = i + 1
310 return res
310 return res
311
311
312
312
313 #---------------------------------------------------------------------------
313 #---------------------------------------------------------------------------
314 # Module classes
314 # Module classes
315 class TBTools(object):
315 class TBTools(object):
316 """Basic tools used by all traceback printer classes."""
316 """Basic tools used by all traceback printer classes."""
317
317
318 # Number of frames to skip when reporting tracebacks
318 # Number of frames to skip when reporting tracebacks
319 tb_offset = 0
319 tb_offset = 0
320
320
321 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None):
321 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None):
322 # Whether to call the interactive pdb debugger after printing
322 # Whether to call the interactive pdb debugger after printing
323 # tracebacks or not
323 # tracebacks or not
324 self.call_pdb = call_pdb
324 self.call_pdb = call_pdb
325
325
326 # Output stream to write to. Note that we store the original value in
326 # Output stream to write to. Note that we store the original value in
327 # a private attribute and then make the public ostream a property, so
327 # a private attribute and then make the public ostream a property, so
328 # that we can delay accessing io.Term.cout until runtime. The way
328 # that we can delay accessing io.stdout until runtime. The way
329 # things are written now, the Term.cout object is dynamically managed
329 # things are written now, the io.stdout object is dynamically managed
330 # so a reference to it should NEVER be stored statically. This
330 # so a reference to it should NEVER be stored statically. This
331 # property approach confines this detail to a single location, and all
331 # property approach confines this detail to a single location, and all
332 # subclasses can simply access self.ostream for writing.
332 # subclasses can simply access self.ostream for writing.
333 self._ostream = ostream
333 self._ostream = ostream
334
334
335 # Create color table
335 # Create color table
336 self.color_scheme_table = exception_colors()
336 self.color_scheme_table = exception_colors()
337
337
338 self.set_colors(color_scheme)
338 self.set_colors(color_scheme)
339 self.old_scheme = color_scheme # save initial value for toggles
339 self.old_scheme = color_scheme # save initial value for toggles
340
340
341 if call_pdb:
341 if call_pdb:
342 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
342 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
343 else:
343 else:
344 self.pdb = None
344 self.pdb = None
345
345
346 def _get_ostream(self):
346 def _get_ostream(self):
347 """Output stream that exceptions are written to.
347 """Output stream that exceptions are written to.
348
348
349 Valid values are:
349 Valid values are:
350
350
351 - None: the default, which means that IPython will dynamically resolve
351 - None: the default, which means that IPython will dynamically resolve
352 to io.Term.cout. This ensures compatibility with most tools, including
352 to io.stdout. This ensures compatibility with most tools, including
353 Windows (where plain stdout doesn't recognize ANSI escapes).
353 Windows (where plain stdout doesn't recognize ANSI escapes).
354
354
355 - Any object with 'write' and 'flush' attributes.
355 - Any object with 'write' and 'flush' attributes.
356 """
356 """
357 return io.Term.cout if self._ostream is None else self._ostream
357 return io.stdout if self._ostream is None else self._ostream
358
358
359 def _set_ostream(self, val):
359 def _set_ostream(self, val):
360 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
360 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
361 self._ostream = val
361 self._ostream = val
362
362
363 ostream = property(_get_ostream, _set_ostream)
363 ostream = property(_get_ostream, _set_ostream)
364
364
365 def set_colors(self,*args,**kw):
365 def set_colors(self,*args,**kw):
366 """Shorthand access to the color table scheme selector method."""
366 """Shorthand access to the color table scheme selector method."""
367
367
368 # Set own color table
368 # Set own color table
369 self.color_scheme_table.set_active_scheme(*args,**kw)
369 self.color_scheme_table.set_active_scheme(*args,**kw)
370 # for convenience, set Colors to the active scheme
370 # for convenience, set Colors to the active scheme
371 self.Colors = self.color_scheme_table.active_colors
371 self.Colors = self.color_scheme_table.active_colors
372 # Also set colors of debugger
372 # Also set colors of debugger
373 if hasattr(self,'pdb') and self.pdb is not None:
373 if hasattr(self,'pdb') and self.pdb is not None:
374 self.pdb.set_colors(*args,**kw)
374 self.pdb.set_colors(*args,**kw)
375
375
376 def color_toggle(self):
376 def color_toggle(self):
377 """Toggle between the currently active color scheme and NoColor."""
377 """Toggle between the currently active color scheme and NoColor."""
378
378
379 if self.color_scheme_table.active_scheme_name == 'NoColor':
379 if self.color_scheme_table.active_scheme_name == 'NoColor':
380 self.color_scheme_table.set_active_scheme(self.old_scheme)
380 self.color_scheme_table.set_active_scheme(self.old_scheme)
381 self.Colors = self.color_scheme_table.active_colors
381 self.Colors = self.color_scheme_table.active_colors
382 else:
382 else:
383 self.old_scheme = self.color_scheme_table.active_scheme_name
383 self.old_scheme = self.color_scheme_table.active_scheme_name
384 self.color_scheme_table.set_active_scheme('NoColor')
384 self.color_scheme_table.set_active_scheme('NoColor')
385 self.Colors = self.color_scheme_table.active_colors
385 self.Colors = self.color_scheme_table.active_colors
386
386
387 def stb2text(self, stb):
387 def stb2text(self, stb):
388 """Convert a structured traceback (a list) to a string."""
388 """Convert a structured traceback (a list) to a string."""
389 return '\n'.join(stb)
389 return '\n'.join(stb)
390
390
391 def text(self, etype, value, tb, tb_offset=None, context=5):
391 def text(self, etype, value, tb, tb_offset=None, context=5):
392 """Return formatted traceback.
392 """Return formatted traceback.
393
393
394 Subclasses may override this if they add extra arguments.
394 Subclasses may override this if they add extra arguments.
395 """
395 """
396 tb_list = self.structured_traceback(etype, value, tb,
396 tb_list = self.structured_traceback(etype, value, tb,
397 tb_offset, context)
397 tb_offset, context)
398 return self.stb2text(tb_list)
398 return self.stb2text(tb_list)
399
399
400 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
400 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
401 context=5, mode=None):
401 context=5, mode=None):
402 """Return a list of traceback frames.
402 """Return a list of traceback frames.
403
403
404 Must be implemented by each class.
404 Must be implemented by each class.
405 """
405 """
406 raise NotImplementedError()
406 raise NotImplementedError()
407
407
408
408
409 #---------------------------------------------------------------------------
409 #---------------------------------------------------------------------------
410 class ListTB(TBTools):
410 class ListTB(TBTools):
411 """Print traceback information from a traceback list, with optional color.
411 """Print traceback information from a traceback list, with optional color.
412
412
413 Calling: requires 3 arguments:
413 Calling: requires 3 arguments:
414 (etype, evalue, elist)
414 (etype, evalue, elist)
415 as would be obtained by:
415 as would be obtained by:
416 etype, evalue, tb = sys.exc_info()
416 etype, evalue, tb = sys.exc_info()
417 if tb:
417 if tb:
418 elist = traceback.extract_tb(tb)
418 elist = traceback.extract_tb(tb)
419 else:
419 else:
420 elist = None
420 elist = None
421
421
422 It can thus be used by programs which need to process the traceback before
422 It can thus be used by programs which need to process the traceback before
423 printing (such as console replacements based on the code module from the
423 printing (such as console replacements based on the code module from the
424 standard library).
424 standard library).
425
425
426 Because they are meant to be called without a full traceback (only a
426 Because they are meant to be called without a full traceback (only a
427 list), instances of this class can't call the interactive pdb debugger."""
427 list), instances of this class can't call the interactive pdb debugger."""
428
428
429 def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None):
429 def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None):
430 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
430 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
431 ostream=ostream)
431 ostream=ostream)
432
432
433 def __call__(self, etype, value, elist):
433 def __call__(self, etype, value, elist):
434 self.ostream.flush()
434 self.ostream.flush()
435 self.ostream.write(self.text(etype, value, elist))
435 self.ostream.write(self.text(etype, value, elist))
436 self.ostream.write('\n')
436 self.ostream.write('\n')
437
437
438 def structured_traceback(self, etype, value, elist, tb_offset=None,
438 def structured_traceback(self, etype, value, elist, tb_offset=None,
439 context=5):
439 context=5):
440 """Return a color formatted string with the traceback info.
440 """Return a color formatted string with the traceback info.
441
441
442 Parameters
442 Parameters
443 ----------
443 ----------
444 etype : exception type
444 etype : exception type
445 Type of the exception raised.
445 Type of the exception raised.
446
446
447 value : object
447 value : object
448 Data stored in the exception
448 Data stored in the exception
449
449
450 elist : list
450 elist : list
451 List of frames, see class docstring for details.
451 List of frames, see class docstring for details.
452
452
453 tb_offset : int, optional
453 tb_offset : int, optional
454 Number of frames in the traceback to skip. If not given, the
454 Number of frames in the traceback to skip. If not given, the
455 instance value is used (set in constructor).
455 instance value is used (set in constructor).
456
456
457 context : int, optional
457 context : int, optional
458 Number of lines of context information to print.
458 Number of lines of context information to print.
459
459
460 Returns
460 Returns
461 -------
461 -------
462 String with formatted exception.
462 String with formatted exception.
463 """
463 """
464 tb_offset = self.tb_offset if tb_offset is None else tb_offset
464 tb_offset = self.tb_offset if tb_offset is None else tb_offset
465 Colors = self.Colors
465 Colors = self.Colors
466 out_list = []
466 out_list = []
467 if elist:
467 if elist:
468
468
469 if tb_offset and len(elist) > tb_offset:
469 if tb_offset and len(elist) > tb_offset:
470 elist = elist[tb_offset:]
470 elist = elist[tb_offset:]
471
471
472 out_list.append('Traceback %s(most recent call last)%s:' %
472 out_list.append('Traceback %s(most recent call last)%s:' %
473 (Colors.normalEm, Colors.Normal) + '\n')
473 (Colors.normalEm, Colors.Normal) + '\n')
474 out_list.extend(self._format_list(elist))
474 out_list.extend(self._format_list(elist))
475 # The exception info should be a single entry in the list.
475 # The exception info should be a single entry in the list.
476 lines = ''.join(self._format_exception_only(etype, value))
476 lines = ''.join(self._format_exception_only(etype, value))
477 out_list.append(lines)
477 out_list.append(lines)
478
478
479 # Note: this code originally read:
479 # Note: this code originally read:
480
480
481 ## for line in lines[:-1]:
481 ## for line in lines[:-1]:
482 ## out_list.append(" "+line)
482 ## out_list.append(" "+line)
483 ## out_list.append(lines[-1])
483 ## out_list.append(lines[-1])
484
484
485 # This means it was indenting everything but the last line by a little
485 # This means it was indenting everything but the last line by a little
486 # bit. I've disabled this for now, but if we see ugliness somewhre we
486 # bit. I've disabled this for now, but if we see ugliness somewhre we
487 # can restore it.
487 # can restore it.
488
488
489 return out_list
489 return out_list
490
490
491 def _format_list(self, extracted_list):
491 def _format_list(self, extracted_list):
492 """Format a list of traceback entry tuples for printing.
492 """Format a list of traceback entry tuples for printing.
493
493
494 Given a list of tuples as returned by extract_tb() or
494 Given a list of tuples as returned by extract_tb() or
495 extract_stack(), return a list of strings ready for printing.
495 extract_stack(), return a list of strings ready for printing.
496 Each string in the resulting list corresponds to the item with the
496 Each string in the resulting list corresponds to the item with the
497 same index in the argument list. Each string ends in a newline;
497 same index in the argument list. Each string ends in a newline;
498 the strings may contain internal newlines as well, for those items
498 the strings may contain internal newlines as well, for those items
499 whose source text line is not None.
499 whose source text line is not None.
500
500
501 Lifted almost verbatim from traceback.py
501 Lifted almost verbatim from traceback.py
502 """
502 """
503
503
504 Colors = self.Colors
504 Colors = self.Colors
505 list = []
505 list = []
506 for filename, lineno, name, line in extracted_list[:-1]:
506 for filename, lineno, name, line in extracted_list[:-1]:
507 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
507 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
508 (Colors.filename, filename, Colors.Normal,
508 (Colors.filename, filename, Colors.Normal,
509 Colors.lineno, lineno, Colors.Normal,
509 Colors.lineno, lineno, Colors.Normal,
510 Colors.name, name, Colors.Normal)
510 Colors.name, name, Colors.Normal)
511 if line:
511 if line:
512 item = item + ' %s\n' % line.strip()
512 item = item + ' %s\n' % line.strip()
513 list.append(item)
513 list.append(item)
514 # Emphasize the last entry
514 # Emphasize the last entry
515 filename, lineno, name, line = extracted_list[-1]
515 filename, lineno, name, line = extracted_list[-1]
516 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
516 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
517 (Colors.normalEm,
517 (Colors.normalEm,
518 Colors.filenameEm, filename, Colors.normalEm,
518 Colors.filenameEm, filename, Colors.normalEm,
519 Colors.linenoEm, lineno, Colors.normalEm,
519 Colors.linenoEm, lineno, Colors.normalEm,
520 Colors.nameEm, name, Colors.normalEm,
520 Colors.nameEm, name, Colors.normalEm,
521 Colors.Normal)
521 Colors.Normal)
522 if line:
522 if line:
523 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
523 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
524 Colors.Normal)
524 Colors.Normal)
525 list.append(item)
525 list.append(item)
526 #from pprint import pformat; print 'LISTTB', pformat(list) # dbg
526 #from pprint import pformat; print 'LISTTB', pformat(list) # dbg
527 return list
527 return list
528
528
529 def _format_exception_only(self, etype, value):
529 def _format_exception_only(self, etype, value):
530 """Format the exception part of a traceback.
530 """Format the exception part of a traceback.
531
531
532 The arguments are the exception type and value such as given by
532 The arguments are the exception type and value such as given by
533 sys.exc_info()[:2]. The return value is a list of strings, each ending
533 sys.exc_info()[:2]. The return value is a list of strings, each ending
534 in a newline. Normally, the list contains a single string; however,
534 in a newline. Normally, the list contains a single string; however,
535 for SyntaxError exceptions, it contains several lines that (when
535 for SyntaxError exceptions, it contains several lines that (when
536 printed) display detailed information about where the syntax error
536 printed) display detailed information about where the syntax error
537 occurred. The message indicating which exception occurred is the
537 occurred. The message indicating which exception occurred is the
538 always last string in the list.
538 always last string in the list.
539
539
540 Also lifted nearly verbatim from traceback.py
540 Also lifted nearly verbatim from traceback.py
541 """
541 """
542
542
543 have_filedata = False
543 have_filedata = False
544 Colors = self.Colors
544 Colors = self.Colors
545 list = []
545 list = []
546 try:
546 try:
547 stype = Colors.excName + etype.__name__ + Colors.Normal
547 stype = Colors.excName + etype.__name__ + Colors.Normal
548 except AttributeError:
548 except AttributeError:
549 stype = etype # String exceptions don't get special coloring
549 stype = etype # String exceptions don't get special coloring
550 if value is None:
550 if value is None:
551 list.append( str(stype) + '\n')
551 list.append( str(stype) + '\n')
552 else:
552 else:
553 if etype is SyntaxError:
553 if etype is SyntaxError:
554 try:
554 try:
555 msg, (filename, lineno, offset, line) = value
555 msg, (filename, lineno, offset, line) = value
556 except:
556 except:
557 have_filedata = False
557 have_filedata = False
558 else:
558 else:
559 have_filedata = True
559 have_filedata = True
560 #print 'filename is',filename # dbg
560 #print 'filename is',filename # dbg
561 if not filename: filename = "<string>"
561 if not filename: filename = "<string>"
562 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
562 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
563 (Colors.normalEm,
563 (Colors.normalEm,
564 Colors.filenameEm, filename, Colors.normalEm,
564 Colors.filenameEm, filename, Colors.normalEm,
565 Colors.linenoEm, lineno, Colors.Normal ))
565 Colors.linenoEm, lineno, Colors.Normal ))
566 if line is not None:
566 if line is not None:
567 i = 0
567 i = 0
568 while i < len(line) and line[i].isspace():
568 while i < len(line) and line[i].isspace():
569 i = i+1
569 i = i+1
570 list.append('%s %s%s\n' % (Colors.line,
570 list.append('%s %s%s\n' % (Colors.line,
571 line.strip(),
571 line.strip(),
572 Colors.Normal))
572 Colors.Normal))
573 if offset is not None:
573 if offset is not None:
574 s = ' '
574 s = ' '
575 for c in line[i:offset-1]:
575 for c in line[i:offset-1]:
576 if c.isspace():
576 if c.isspace():
577 s = s + c
577 s = s + c
578 else:
578 else:
579 s = s + ' '
579 s = s + ' '
580 list.append('%s%s^%s\n' % (Colors.caret, s,
580 list.append('%s%s^%s\n' % (Colors.caret, s,
581 Colors.Normal) )
581 Colors.Normal) )
582 value = msg
582 value = msg
583 s = self._some_str(value)
583 s = self._some_str(value)
584 if s:
584 if s:
585 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
585 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
586 Colors.Normal, s))
586 Colors.Normal, s))
587 else:
587 else:
588 list.append('%s\n' % str(stype))
588 list.append('%s\n' % str(stype))
589
589
590 # sync with user hooks
590 # sync with user hooks
591 if have_filedata:
591 if have_filedata:
592 ipinst = ipapi.get()
592 ipinst = ipapi.get()
593 if ipinst is not None:
593 if ipinst is not None:
594 ipinst.hooks.synchronize_with_editor(filename, lineno, 0)
594 ipinst.hooks.synchronize_with_editor(filename, lineno, 0)
595
595
596 return list
596 return list
597
597
598 def get_exception_only(self, etype, value):
598 def get_exception_only(self, etype, value):
599 """Only print the exception type and message, without a traceback.
599 """Only print the exception type and message, without a traceback.
600
600
601 Parameters
601 Parameters
602 ----------
602 ----------
603 etype : exception type
603 etype : exception type
604 value : exception value
604 value : exception value
605 """
605 """
606 return ListTB.structured_traceback(self, etype, value, [])
606 return ListTB.structured_traceback(self, etype, value, [])
607
607
608
608
609 def show_exception_only(self, etype, evalue):
609 def show_exception_only(self, etype, evalue):
610 """Only print the exception type and message, without a traceback.
610 """Only print the exception type and message, without a traceback.
611
611
612 Parameters
612 Parameters
613 ----------
613 ----------
614 etype : exception type
614 etype : exception type
615 value : exception value
615 value : exception value
616 """
616 """
617 # This method needs to use __call__ from *this* class, not the one from
617 # This method needs to use __call__ from *this* class, not the one from
618 # a subclass whose signature or behavior may be different
618 # a subclass whose signature or behavior may be different
619 ostream = self.ostream
619 ostream = self.ostream
620 ostream.flush()
620 ostream.flush()
621 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
621 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
622 ostream.flush()
622 ostream.flush()
623
623
624 def _some_str(self, value):
624 def _some_str(self, value):
625 # Lifted from traceback.py
625 # Lifted from traceback.py
626 try:
626 try:
627 return str(value)
627 return str(value)
628 except:
628 except:
629 return '<unprintable %s object>' % type(value).__name__
629 return '<unprintable %s object>' % type(value).__name__
630
630
631 #----------------------------------------------------------------------------
631 #----------------------------------------------------------------------------
632 class VerboseTB(TBTools):
632 class VerboseTB(TBTools):
633 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
633 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
634 of HTML. Requires inspect and pydoc. Crazy, man.
634 of HTML. Requires inspect and pydoc. Crazy, man.
635
635
636 Modified version which optionally strips the topmost entries from the
636 Modified version which optionally strips the topmost entries from the
637 traceback, to be used with alternate interpreters (because their own code
637 traceback, to be used with alternate interpreters (because their own code
638 would appear in the traceback)."""
638 would appear in the traceback)."""
639
639
640 def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None,
640 def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None,
641 tb_offset=0, long_header=False, include_vars=True,
641 tb_offset=0, long_header=False, include_vars=True,
642 check_cache=None):
642 check_cache=None):
643 """Specify traceback offset, headers and color scheme.
643 """Specify traceback offset, headers and color scheme.
644
644
645 Define how many frames to drop from the tracebacks. Calling it with
645 Define how many frames to drop from the tracebacks. Calling it with
646 tb_offset=1 allows use of this handler in interpreters which will have
646 tb_offset=1 allows use of this handler in interpreters which will have
647 their own code at the top of the traceback (VerboseTB will first
647 their own code at the top of the traceback (VerboseTB will first
648 remove that frame before printing the traceback info)."""
648 remove that frame before printing the traceback info)."""
649 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
649 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
650 ostream=ostream)
650 ostream=ostream)
651 self.tb_offset = tb_offset
651 self.tb_offset = tb_offset
652 self.long_header = long_header
652 self.long_header = long_header
653 self.include_vars = include_vars
653 self.include_vars = include_vars
654 # By default we use linecache.checkcache, but the user can provide a
654 # By default we use linecache.checkcache, but the user can provide a
655 # different check_cache implementation. This is used by the IPython
655 # different check_cache implementation. This is used by the IPython
656 # kernel to provide tracebacks for interactive code that is cached,
656 # kernel to provide tracebacks for interactive code that is cached,
657 # by a compiler instance that flushes the linecache but preserves its
657 # by a compiler instance that flushes the linecache but preserves its
658 # own code cache.
658 # own code cache.
659 if check_cache is None:
659 if check_cache is None:
660 check_cache = linecache.checkcache
660 check_cache = linecache.checkcache
661 self.check_cache = check_cache
661 self.check_cache = check_cache
662
662
663 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
663 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
664 context=5):
664 context=5):
665 """Return a nice text document describing the traceback."""
665 """Return a nice text document describing the traceback."""
666
666
667 tb_offset = self.tb_offset if tb_offset is None else tb_offset
667 tb_offset = self.tb_offset if tb_offset is None else tb_offset
668
668
669 # some locals
669 # some locals
670 try:
670 try:
671 etype = etype.__name__
671 etype = etype.__name__
672 except AttributeError:
672 except AttributeError:
673 pass
673 pass
674 Colors = self.Colors # just a shorthand + quicker name lookup
674 Colors = self.Colors # just a shorthand + quicker name lookup
675 ColorsNormal = Colors.Normal # used a lot
675 ColorsNormal = Colors.Normal # used a lot
676 col_scheme = self.color_scheme_table.active_scheme_name
676 col_scheme = self.color_scheme_table.active_scheme_name
677 indent = ' '*INDENT_SIZE
677 indent = ' '*INDENT_SIZE
678 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
678 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
679 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
679 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
680 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
680 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
681
681
682 # some internal-use functions
682 # some internal-use functions
683 def text_repr(value):
683 def text_repr(value):
684 """Hopefully pretty robust repr equivalent."""
684 """Hopefully pretty robust repr equivalent."""
685 # this is pretty horrible but should always return *something*
685 # this is pretty horrible but should always return *something*
686 try:
686 try:
687 return pydoc.text.repr(value)
687 return pydoc.text.repr(value)
688 except KeyboardInterrupt:
688 except KeyboardInterrupt:
689 raise
689 raise
690 except:
690 except:
691 try:
691 try:
692 return repr(value)
692 return repr(value)
693 except KeyboardInterrupt:
693 except KeyboardInterrupt:
694 raise
694 raise
695 except:
695 except:
696 try:
696 try:
697 # all still in an except block so we catch
697 # all still in an except block so we catch
698 # getattr raising
698 # getattr raising
699 name = getattr(value, '__name__', None)
699 name = getattr(value, '__name__', None)
700 if name:
700 if name:
701 # ick, recursion
701 # ick, recursion
702 return text_repr(name)
702 return text_repr(name)
703 klass = getattr(value, '__class__', None)
703 klass = getattr(value, '__class__', None)
704 if klass:
704 if klass:
705 return '%s instance' % text_repr(klass)
705 return '%s instance' % text_repr(klass)
706 except KeyboardInterrupt:
706 except KeyboardInterrupt:
707 raise
707 raise
708 except:
708 except:
709 return 'UNRECOVERABLE REPR FAILURE'
709 return 'UNRECOVERABLE REPR FAILURE'
710 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
710 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
711 def nullrepr(value, repr=text_repr): return ''
711 def nullrepr(value, repr=text_repr): return ''
712
712
713 # meat of the code begins
713 # meat of the code begins
714 try:
714 try:
715 etype = etype.__name__
715 etype = etype.__name__
716 except AttributeError:
716 except AttributeError:
717 pass
717 pass
718
718
719 if self.long_header:
719 if self.long_header:
720 # Header with the exception type, python version, and date
720 # Header with the exception type, python version, and date
721 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
721 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
722 date = time.ctime(time.time())
722 date = time.ctime(time.time())
723
723
724 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
724 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
725 exc, ' '*(75-len(str(etype))-len(pyver)),
725 exc, ' '*(75-len(str(etype))-len(pyver)),
726 pyver, date.rjust(75) )
726 pyver, date.rjust(75) )
727 head += "\nA problem occured executing Python code. Here is the sequence of function"\
727 head += "\nA problem occured executing Python code. Here is the sequence of function"\
728 "\ncalls leading up to the error, with the most recent (innermost) call last."
728 "\ncalls leading up to the error, with the most recent (innermost) call last."
729 else:
729 else:
730 # Simplified header
730 # Simplified header
731 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
731 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
732 'Traceback (most recent call last)'.\
732 'Traceback (most recent call last)'.\
733 rjust(75 - len(str(etype)) ) )
733 rjust(75 - len(str(etype)) ) )
734 frames = []
734 frames = []
735 # Flush cache before calling inspect. This helps alleviate some of the
735 # Flush cache before calling inspect. This helps alleviate some of the
736 # problems with python 2.3's inspect.py.
736 # problems with python 2.3's inspect.py.
737 ##self.check_cache()
737 ##self.check_cache()
738 # Drop topmost frames if requested
738 # Drop topmost frames if requested
739 try:
739 try:
740 # Try the default getinnerframes and Alex's: Alex's fixes some
740 # Try the default getinnerframes and Alex's: Alex's fixes some
741 # problems, but it generates empty tracebacks for console errors
741 # problems, but it generates empty tracebacks for console errors
742 # (5 blanks lines) where none should be returned.
742 # (5 blanks lines) where none should be returned.
743 #records = inspect.getinnerframes(etb, context)[tb_offset:]
743 #records = inspect.getinnerframes(etb, context)[tb_offset:]
744 #print 'python records:', records # dbg
744 #print 'python records:', records # dbg
745 records = _fixed_getinnerframes(etb, context, tb_offset)
745 records = _fixed_getinnerframes(etb, context, tb_offset)
746 #print 'alex records:', records # dbg
746 #print 'alex records:', records # dbg
747 except:
747 except:
748
748
749 # FIXME: I've been getting many crash reports from python 2.3
749 # FIXME: I've been getting many crash reports from python 2.3
750 # users, traceable to inspect.py. If I can find a small test-case
750 # users, traceable to inspect.py. If I can find a small test-case
751 # to reproduce this, I should either write a better workaround or
751 # to reproduce this, I should either write a better workaround or
752 # file a bug report against inspect (if that's the real problem).
752 # file a bug report against inspect (if that's the real problem).
753 # So far, I haven't been able to find an isolated example to
753 # So far, I haven't been able to find an isolated example to
754 # reproduce the problem.
754 # reproduce the problem.
755 inspect_error()
755 inspect_error()
756 traceback.print_exc(file=self.ostream)
756 traceback.print_exc(file=self.ostream)
757 info('\nUnfortunately, your original traceback can not be constructed.\n')
757 info('\nUnfortunately, your original traceback can not be constructed.\n')
758 return ''
758 return ''
759
759
760 # build some color string templates outside these nested loops
760 # build some color string templates outside these nested loops
761 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
761 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
762 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
762 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
763 ColorsNormal)
763 ColorsNormal)
764 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
764 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
765 (Colors.vName, Colors.valEm, ColorsNormal)
765 (Colors.vName, Colors.valEm, ColorsNormal)
766 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
766 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
767 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
767 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
768 Colors.vName, ColorsNormal)
768 Colors.vName, ColorsNormal)
769 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
769 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
770 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
770 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
771 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
771 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
772 ColorsNormal)
772 ColorsNormal)
773
773
774 # now, loop over all records printing context and info
774 # now, loop over all records printing context and info
775 abspath = os.path.abspath
775 abspath = os.path.abspath
776 for frame, file, lnum, func, lines, index in records:
776 for frame, file, lnum, func, lines, index in records:
777 #print '*** record:',file,lnum,func,lines,index # dbg
777 #print '*** record:',file,lnum,func,lines,index # dbg
778 try:
778 try:
779 file = file and abspath(file) or '?'
779 file = file and abspath(file) or '?'
780 except OSError:
780 except OSError:
781 # if file is '<console>' or something not in the filesystem,
781 # if file is '<console>' or something not in the filesystem,
782 # the abspath call will throw an OSError. Just ignore it and
782 # the abspath call will throw an OSError. Just ignore it and
783 # keep the original file string.
783 # keep the original file string.
784 pass
784 pass
785 link = tpl_link % file
785 link = tpl_link % file
786 try:
786 try:
787 args, varargs, varkw, locals = inspect.getargvalues(frame)
787 args, varargs, varkw, locals = inspect.getargvalues(frame)
788 except:
788 except:
789 # This can happen due to a bug in python2.3. We should be
789 # This can happen due to a bug in python2.3. We should be
790 # able to remove this try/except when 2.4 becomes a
790 # able to remove this try/except when 2.4 becomes a
791 # requirement. Bug details at http://python.org/sf/1005466
791 # requirement. Bug details at http://python.org/sf/1005466
792 inspect_error()
792 inspect_error()
793 traceback.print_exc(file=self.ostream)
793 traceback.print_exc(file=self.ostream)
794 info("\nIPython's exception reporting continues...\n")
794 info("\nIPython's exception reporting continues...\n")
795
795
796 if func == '?':
796 if func == '?':
797 call = ''
797 call = ''
798 else:
798 else:
799 # Decide whether to include variable details or not
799 # Decide whether to include variable details or not
800 var_repr = self.include_vars and eqrepr or nullrepr
800 var_repr = self.include_vars and eqrepr or nullrepr
801 try:
801 try:
802 call = tpl_call % (func,inspect.formatargvalues(args,
802 call = tpl_call % (func,inspect.formatargvalues(args,
803 varargs, varkw,
803 varargs, varkw,
804 locals,formatvalue=var_repr))
804 locals,formatvalue=var_repr))
805 except KeyError:
805 except KeyError:
806 # This happens in situations like errors inside generator
806 # This happens in situations like errors inside generator
807 # expressions, where local variables are listed in the
807 # expressions, where local variables are listed in the
808 # line, but can't be extracted from the frame. I'm not
808 # line, but can't be extracted from the frame. I'm not
809 # 100% sure this isn't actually a bug in inspect itself,
809 # 100% sure this isn't actually a bug in inspect itself,
810 # but since there's no info for us to compute with, the
810 # but since there's no info for us to compute with, the
811 # best we can do is report the failure and move on. Here
811 # best we can do is report the failure and move on. Here
812 # we must *not* call any traceback construction again,
812 # we must *not* call any traceback construction again,
813 # because that would mess up use of %debug later on. So we
813 # because that would mess up use of %debug later on. So we
814 # simply report the failure and move on. The only
814 # simply report the failure and move on. The only
815 # limitation will be that this frame won't have locals
815 # limitation will be that this frame won't have locals
816 # listed in the call signature. Quite subtle problem...
816 # listed in the call signature. Quite subtle problem...
817 # I can't think of a good way to validate this in a unit
817 # I can't think of a good way to validate this in a unit
818 # test, but running a script consisting of:
818 # test, but running a script consisting of:
819 # dict( (k,v.strip()) for (k,v) in range(10) )
819 # dict( (k,v.strip()) for (k,v) in range(10) )
820 # will illustrate the error, if this exception catch is
820 # will illustrate the error, if this exception catch is
821 # disabled.
821 # disabled.
822 call = tpl_call_fail % func
822 call = tpl_call_fail % func
823
823
824 # Initialize a list of names on the current line, which the
824 # Initialize a list of names on the current line, which the
825 # tokenizer below will populate.
825 # tokenizer below will populate.
826 names = []
826 names = []
827
827
828 def tokeneater(token_type, token, start, end, line):
828 def tokeneater(token_type, token, start, end, line):
829 """Stateful tokeneater which builds dotted names.
829 """Stateful tokeneater which builds dotted names.
830
830
831 The list of names it appends to (from the enclosing scope) can
831 The list of names it appends to (from the enclosing scope) can
832 contain repeated composite names. This is unavoidable, since
832 contain repeated composite names. This is unavoidable, since
833 there is no way to disambguate partial dotted structures until
833 there is no way to disambguate partial dotted structures until
834 the full list is known. The caller is responsible for pruning
834 the full list is known. The caller is responsible for pruning
835 the final list of duplicates before using it."""
835 the final list of duplicates before using it."""
836
836
837 # build composite names
837 # build composite names
838 if token == '.':
838 if token == '.':
839 try:
839 try:
840 names[-1] += '.'
840 names[-1] += '.'
841 # store state so the next token is added for x.y.z names
841 # store state so the next token is added for x.y.z names
842 tokeneater.name_cont = True
842 tokeneater.name_cont = True
843 return
843 return
844 except IndexError:
844 except IndexError:
845 pass
845 pass
846 if token_type == tokenize.NAME and token not in keyword.kwlist:
846 if token_type == tokenize.NAME and token not in keyword.kwlist:
847 if tokeneater.name_cont:
847 if tokeneater.name_cont:
848 # Dotted names
848 # Dotted names
849 names[-1] += token
849 names[-1] += token
850 tokeneater.name_cont = False
850 tokeneater.name_cont = False
851 else:
851 else:
852 # Regular new names. We append everything, the caller
852 # Regular new names. We append everything, the caller
853 # will be responsible for pruning the list later. It's
853 # will be responsible for pruning the list later. It's
854 # very tricky to try to prune as we go, b/c composite
854 # very tricky to try to prune as we go, b/c composite
855 # names can fool us. The pruning at the end is easy
855 # names can fool us. The pruning at the end is easy
856 # to do (or the caller can print a list with repeated
856 # to do (or the caller can print a list with repeated
857 # names if so desired.
857 # names if so desired.
858 names.append(token)
858 names.append(token)
859 elif token_type == tokenize.NEWLINE:
859 elif token_type == tokenize.NEWLINE:
860 raise IndexError
860 raise IndexError
861 # we need to store a bit of state in the tokenizer to build
861 # we need to store a bit of state in the tokenizer to build
862 # dotted names
862 # dotted names
863 tokeneater.name_cont = False
863 tokeneater.name_cont = False
864
864
865 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
865 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
866 line = getline(file, lnum[0])
866 line = getline(file, lnum[0])
867 lnum[0] += 1
867 lnum[0] += 1
868 return line
868 return line
869
869
870 # Build the list of names on this line of code where the exception
870 # Build the list of names on this line of code where the exception
871 # occurred.
871 # occurred.
872 try:
872 try:
873 # This builds the names list in-place by capturing it from the
873 # This builds the names list in-place by capturing it from the
874 # enclosing scope.
874 # enclosing scope.
875 tokenize.tokenize(linereader, tokeneater)
875 tokenize.tokenize(linereader, tokeneater)
876 except IndexError:
876 except IndexError:
877 # signals exit of tokenizer
877 # signals exit of tokenizer
878 pass
878 pass
879 except tokenize.TokenError,msg:
879 except tokenize.TokenError,msg:
880 _m = ("An unexpected error occurred while tokenizing input\n"
880 _m = ("An unexpected error occurred while tokenizing input\n"
881 "The following traceback may be corrupted or invalid\n"
881 "The following traceback may be corrupted or invalid\n"
882 "The error message is: %s\n" % msg)
882 "The error message is: %s\n" % msg)
883 error(_m)
883 error(_m)
884
884
885 # prune names list of duplicates, but keep the right order
885 # prune names list of duplicates, but keep the right order
886 unique_names = uniq_stable(names)
886 unique_names = uniq_stable(names)
887
887
888 # Start loop over vars
888 # Start loop over vars
889 lvals = []
889 lvals = []
890 if self.include_vars:
890 if self.include_vars:
891 for name_full in unique_names:
891 for name_full in unique_names:
892 name_base = name_full.split('.',1)[0]
892 name_base = name_full.split('.',1)[0]
893 if name_base in frame.f_code.co_varnames:
893 if name_base in frame.f_code.co_varnames:
894 if locals.has_key(name_base):
894 if locals.has_key(name_base):
895 try:
895 try:
896 value = repr(eval(name_full,locals))
896 value = repr(eval(name_full,locals))
897 except:
897 except:
898 value = undefined
898 value = undefined
899 else:
899 else:
900 value = undefined
900 value = undefined
901 name = tpl_local_var % name_full
901 name = tpl_local_var % name_full
902 else:
902 else:
903 if frame.f_globals.has_key(name_base):
903 if frame.f_globals.has_key(name_base):
904 try:
904 try:
905 value = repr(eval(name_full,frame.f_globals))
905 value = repr(eval(name_full,frame.f_globals))
906 except:
906 except:
907 value = undefined
907 value = undefined
908 else:
908 else:
909 value = undefined
909 value = undefined
910 name = tpl_global_var % name_full
910 name = tpl_global_var % name_full
911 lvals.append(tpl_name_val % (name,value))
911 lvals.append(tpl_name_val % (name,value))
912 if lvals:
912 if lvals:
913 lvals = '%s%s' % (indent,em_normal.join(lvals))
913 lvals = '%s%s' % (indent,em_normal.join(lvals))
914 else:
914 else:
915 lvals = ''
915 lvals = ''
916
916
917 level = '%s %s\n' % (link,call)
917 level = '%s %s\n' % (link,call)
918
918
919 if index is None:
919 if index is None:
920 frames.append(level)
920 frames.append(level)
921 else:
921 else:
922 frames.append('%s%s' % (level,''.join(
922 frames.append('%s%s' % (level,''.join(
923 _format_traceback_lines(lnum,index,lines,Colors,lvals,
923 _format_traceback_lines(lnum,index,lines,Colors,lvals,
924 col_scheme))))
924 col_scheme))))
925
925
926 # Get (safely) a string form of the exception info
926 # Get (safely) a string form of the exception info
927 try:
927 try:
928 etype_str,evalue_str = map(str,(etype,evalue))
928 etype_str,evalue_str = map(str,(etype,evalue))
929 except:
929 except:
930 # User exception is improperly defined.
930 # User exception is improperly defined.
931 etype,evalue = str,sys.exc_info()[:2]
931 etype,evalue = str,sys.exc_info()[:2]
932 etype_str,evalue_str = map(str,(etype,evalue))
932 etype_str,evalue_str = map(str,(etype,evalue))
933 # ... and format it
933 # ... and format it
934 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
934 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
935 ColorsNormal, evalue_str)]
935 ColorsNormal, evalue_str)]
936 if type(evalue) is types.InstanceType:
936 if type(evalue) is types.InstanceType:
937 try:
937 try:
938 names = [w for w in dir(evalue) if isinstance(w, basestring)]
938 names = [w for w in dir(evalue) if isinstance(w, basestring)]
939 except:
939 except:
940 # Every now and then, an object with funny inernals blows up
940 # Every now and then, an object with funny inernals blows up
941 # when dir() is called on it. We do the best we can to report
941 # when dir() is called on it. We do the best we can to report
942 # the problem and continue
942 # the problem and continue
943 _m = '%sException reporting error (object with broken dir())%s:'
943 _m = '%sException reporting error (object with broken dir())%s:'
944 exception.append(_m % (Colors.excName,ColorsNormal))
944 exception.append(_m % (Colors.excName,ColorsNormal))
945 etype_str,evalue_str = map(str,sys.exc_info()[:2])
945 etype_str,evalue_str = map(str,sys.exc_info()[:2])
946 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
946 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
947 ColorsNormal, evalue_str))
947 ColorsNormal, evalue_str))
948 names = []
948 names = []
949 for name in names:
949 for name in names:
950 value = text_repr(getattr(evalue, name))
950 value = text_repr(getattr(evalue, name))
951 exception.append('\n%s%s = %s' % (indent, name, value))
951 exception.append('\n%s%s = %s' % (indent, name, value))
952
952
953 # vds: >>
953 # vds: >>
954 if records:
954 if records:
955 filepath, lnum = records[-1][1:3]
955 filepath, lnum = records[-1][1:3]
956 #print "file:", str(file), "linenb", str(lnum) # dbg
956 #print "file:", str(file), "linenb", str(lnum) # dbg
957 filepath = os.path.abspath(filepath)
957 filepath = os.path.abspath(filepath)
958 ipinst = ipapi.get()
958 ipinst = ipapi.get()
959 if ipinst is not None:
959 if ipinst is not None:
960 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
960 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
961 # vds: <<
961 # vds: <<
962
962
963 # return all our info assembled as a single string
963 # return all our info assembled as a single string
964 # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
964 # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
965 return [head] + frames + [''.join(exception[0])]
965 return [head] + frames + [''.join(exception[0])]
966
966
967 def debugger(self,force=False):
967 def debugger(self,force=False):
968 """Call up the pdb debugger if desired, always clean up the tb
968 """Call up the pdb debugger if desired, always clean up the tb
969 reference.
969 reference.
970
970
971 Keywords:
971 Keywords:
972
972
973 - force(False): by default, this routine checks the instance call_pdb
973 - force(False): by default, this routine checks the instance call_pdb
974 flag and does not actually invoke the debugger if the flag is false.
974 flag and does not actually invoke the debugger if the flag is false.
975 The 'force' option forces the debugger to activate even if the flag
975 The 'force' option forces the debugger to activate even if the flag
976 is false.
976 is false.
977
977
978 If the call_pdb flag is set, the pdb interactive debugger is
978 If the call_pdb flag is set, the pdb interactive debugger is
979 invoked. In all cases, the self.tb reference to the current traceback
979 invoked. In all cases, the self.tb reference to the current traceback
980 is deleted to prevent lingering references which hamper memory
980 is deleted to prevent lingering references which hamper memory
981 management.
981 management.
982
982
983 Note that each call to pdb() does an 'import readline', so if your app
983 Note that each call to pdb() does an 'import readline', so if your app
984 requires a special setup for the readline completers, you'll have to
984 requires a special setup for the readline completers, you'll have to
985 fix that by hand after invoking the exception handler."""
985 fix that by hand after invoking the exception handler."""
986
986
987 if force or self.call_pdb:
987 if force or self.call_pdb:
988 if self.pdb is None:
988 if self.pdb is None:
989 self.pdb = debugger.Pdb(
989 self.pdb = debugger.Pdb(
990 self.color_scheme_table.active_scheme_name)
990 self.color_scheme_table.active_scheme_name)
991 # the system displayhook may have changed, restore the original
991 # the system displayhook may have changed, restore the original
992 # for pdb
992 # for pdb
993 display_trap = DisplayTrap(hook=sys.__displayhook__)
993 display_trap = DisplayTrap(hook=sys.__displayhook__)
994 with display_trap:
994 with display_trap:
995 self.pdb.reset()
995 self.pdb.reset()
996 # Find the right frame so we don't pop up inside ipython itself
996 # Find the right frame so we don't pop up inside ipython itself
997 if hasattr(self,'tb') and self.tb is not None:
997 if hasattr(self,'tb') and self.tb is not None:
998 etb = self.tb
998 etb = self.tb
999 else:
999 else:
1000 etb = self.tb = sys.last_traceback
1000 etb = self.tb = sys.last_traceback
1001 while self.tb is not None and self.tb.tb_next is not None:
1001 while self.tb is not None and self.tb.tb_next is not None:
1002 self.tb = self.tb.tb_next
1002 self.tb = self.tb.tb_next
1003 if etb and etb.tb_next:
1003 if etb and etb.tb_next:
1004 etb = etb.tb_next
1004 etb = etb.tb_next
1005 self.pdb.botframe = etb.tb_frame
1005 self.pdb.botframe = etb.tb_frame
1006 self.pdb.interaction(self.tb.tb_frame, self.tb)
1006 self.pdb.interaction(self.tb.tb_frame, self.tb)
1007
1007
1008 if hasattr(self,'tb'):
1008 if hasattr(self,'tb'):
1009 del self.tb
1009 del self.tb
1010
1010
1011 def handler(self, info=None):
1011 def handler(self, info=None):
1012 (etype, evalue, etb) = info or sys.exc_info()
1012 (etype, evalue, etb) = info or sys.exc_info()
1013 self.tb = etb
1013 self.tb = etb
1014 ostream = self.ostream
1014 ostream = self.ostream
1015 ostream.flush()
1015 ostream.flush()
1016 ostream.write(self.text(etype, evalue, etb))
1016 ostream.write(self.text(etype, evalue, etb))
1017 ostream.write('\n')
1017 ostream.write('\n')
1018 ostream.flush()
1018 ostream.flush()
1019
1019
1020 # Changed so an instance can just be called as VerboseTB_inst() and print
1020 # Changed so an instance can just be called as VerboseTB_inst() and print
1021 # out the right info on its own.
1021 # out the right info on its own.
1022 def __call__(self, etype=None, evalue=None, etb=None):
1022 def __call__(self, etype=None, evalue=None, etb=None):
1023 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1023 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1024 if etb is None:
1024 if etb is None:
1025 self.handler()
1025 self.handler()
1026 else:
1026 else:
1027 self.handler((etype, evalue, etb))
1027 self.handler((etype, evalue, etb))
1028 try:
1028 try:
1029 self.debugger()
1029 self.debugger()
1030 except KeyboardInterrupt:
1030 except KeyboardInterrupt:
1031 print "\nKeyboardInterrupt"
1031 print "\nKeyboardInterrupt"
1032
1032
1033 #----------------------------------------------------------------------------
1033 #----------------------------------------------------------------------------
1034 class FormattedTB(VerboseTB, ListTB):
1034 class FormattedTB(VerboseTB, ListTB):
1035 """Subclass ListTB but allow calling with a traceback.
1035 """Subclass ListTB but allow calling with a traceback.
1036
1036
1037 It can thus be used as a sys.excepthook for Python > 2.1.
1037 It can thus be used as a sys.excepthook for Python > 2.1.
1038
1038
1039 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1039 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1040
1040
1041 Allows a tb_offset to be specified. This is useful for situations where
1041 Allows a tb_offset to be specified. This is useful for situations where
1042 one needs to remove a number of topmost frames from the traceback (such as
1042 one needs to remove a number of topmost frames from the traceback (such as
1043 occurs with python programs that themselves execute other python code,
1043 occurs with python programs that themselves execute other python code,
1044 like Python shells). """
1044 like Python shells). """
1045
1045
1046 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1046 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1047 ostream=None,
1047 ostream=None,
1048 tb_offset=0, long_header=False, include_vars=False,
1048 tb_offset=0, long_header=False, include_vars=False,
1049 check_cache=None):
1049 check_cache=None):
1050
1050
1051 # NEVER change the order of this list. Put new modes at the end:
1051 # NEVER change the order of this list. Put new modes at the end:
1052 self.valid_modes = ['Plain','Context','Verbose']
1052 self.valid_modes = ['Plain','Context','Verbose']
1053 self.verbose_modes = self.valid_modes[1:3]
1053 self.verbose_modes = self.valid_modes[1:3]
1054
1054
1055 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1055 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1056 ostream=ostream, tb_offset=tb_offset,
1056 ostream=ostream, tb_offset=tb_offset,
1057 long_header=long_header, include_vars=include_vars,
1057 long_header=long_header, include_vars=include_vars,
1058 check_cache=check_cache)
1058 check_cache=check_cache)
1059
1059
1060 # Different types of tracebacks are joined with different separators to
1060 # Different types of tracebacks are joined with different separators to
1061 # form a single string. They are taken from this dict
1061 # form a single string. They are taken from this dict
1062 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1062 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1063 # set_mode also sets the tb_join_char attribute
1063 # set_mode also sets the tb_join_char attribute
1064 self.set_mode(mode)
1064 self.set_mode(mode)
1065
1065
1066 def _extract_tb(self,tb):
1066 def _extract_tb(self,tb):
1067 if tb:
1067 if tb:
1068 return traceback.extract_tb(tb)
1068 return traceback.extract_tb(tb)
1069 else:
1069 else:
1070 return None
1070 return None
1071
1071
1072 def structured_traceback(self, etype, value, tb, tb_offset=None, context=5):
1072 def structured_traceback(self, etype, value, tb, tb_offset=None, context=5):
1073 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1073 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1074 mode = self.mode
1074 mode = self.mode
1075 if mode in self.verbose_modes:
1075 if mode in self.verbose_modes:
1076 # Verbose modes need a full traceback
1076 # Verbose modes need a full traceback
1077 return VerboseTB.structured_traceback(
1077 return VerboseTB.structured_traceback(
1078 self, etype, value, tb, tb_offset, context
1078 self, etype, value, tb, tb_offset, context
1079 )
1079 )
1080 else:
1080 else:
1081 # We must check the source cache because otherwise we can print
1081 # We must check the source cache because otherwise we can print
1082 # out-of-date source code.
1082 # out-of-date source code.
1083 self.check_cache()
1083 self.check_cache()
1084 # Now we can extract and format the exception
1084 # Now we can extract and format the exception
1085 elist = self._extract_tb(tb)
1085 elist = self._extract_tb(tb)
1086 return ListTB.structured_traceback(
1086 return ListTB.structured_traceback(
1087 self, etype, value, elist, tb_offset, context
1087 self, etype, value, elist, tb_offset, context
1088 )
1088 )
1089
1089
1090 def stb2text(self, stb):
1090 def stb2text(self, stb):
1091 """Convert a structured traceback (a list) to a string."""
1091 """Convert a structured traceback (a list) to a string."""
1092 return self.tb_join_char.join(stb)
1092 return self.tb_join_char.join(stb)
1093
1093
1094
1094
1095 def set_mode(self,mode=None):
1095 def set_mode(self,mode=None):
1096 """Switch to the desired mode.
1096 """Switch to the desired mode.
1097
1097
1098 If mode is not specified, cycles through the available modes."""
1098 If mode is not specified, cycles through the available modes."""
1099
1099
1100 if not mode:
1100 if not mode:
1101 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
1101 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
1102 len(self.valid_modes)
1102 len(self.valid_modes)
1103 self.mode = self.valid_modes[new_idx]
1103 self.mode = self.valid_modes[new_idx]
1104 elif mode not in self.valid_modes:
1104 elif mode not in self.valid_modes:
1105 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
1105 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
1106 'Valid modes: '+str(self.valid_modes)
1106 'Valid modes: '+str(self.valid_modes)
1107 else:
1107 else:
1108 self.mode = mode
1108 self.mode = mode
1109 # include variable details only in 'Verbose' mode
1109 # include variable details only in 'Verbose' mode
1110 self.include_vars = (self.mode == self.valid_modes[2])
1110 self.include_vars = (self.mode == self.valid_modes[2])
1111 # Set the join character for generating text tracebacks
1111 # Set the join character for generating text tracebacks
1112 self.tb_join_char = self._join_chars[self.mode]
1112 self.tb_join_char = self._join_chars[self.mode]
1113
1113
1114 # some convenient shorcuts
1114 # some convenient shorcuts
1115 def plain(self):
1115 def plain(self):
1116 self.set_mode(self.valid_modes[0])
1116 self.set_mode(self.valid_modes[0])
1117
1117
1118 def context(self):
1118 def context(self):
1119 self.set_mode(self.valid_modes[1])
1119 self.set_mode(self.valid_modes[1])
1120
1120
1121 def verbose(self):
1121 def verbose(self):
1122 self.set_mode(self.valid_modes[2])
1122 self.set_mode(self.valid_modes[2])
1123
1123
1124 #----------------------------------------------------------------------------
1124 #----------------------------------------------------------------------------
1125 class AutoFormattedTB(FormattedTB):
1125 class AutoFormattedTB(FormattedTB):
1126 """A traceback printer which can be called on the fly.
1126 """A traceback printer which can be called on the fly.
1127
1127
1128 It will find out about exceptions by itself.
1128 It will find out about exceptions by itself.
1129
1129
1130 A brief example:
1130 A brief example:
1131
1131
1132 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1132 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1133 try:
1133 try:
1134 ...
1134 ...
1135 except:
1135 except:
1136 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1136 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1137 """
1137 """
1138
1138
1139 def __call__(self,etype=None,evalue=None,etb=None,
1139 def __call__(self,etype=None,evalue=None,etb=None,
1140 out=None,tb_offset=None):
1140 out=None,tb_offset=None):
1141 """Print out a formatted exception traceback.
1141 """Print out a formatted exception traceback.
1142
1142
1143 Optional arguments:
1143 Optional arguments:
1144 - out: an open file-like object to direct output to.
1144 - out: an open file-like object to direct output to.
1145
1145
1146 - tb_offset: the number of frames to skip over in the stack, on a
1146 - tb_offset: the number of frames to skip over in the stack, on a
1147 per-call basis (this overrides temporarily the instance's tb_offset
1147 per-call basis (this overrides temporarily the instance's tb_offset
1148 given at initialization time. """
1148 given at initialization time. """
1149
1149
1150
1150
1151 if out is None:
1151 if out is None:
1152 out = self.ostream
1152 out = self.ostream
1153 out.flush()
1153 out.flush()
1154 out.write(self.text(etype, evalue, etb, tb_offset))
1154 out.write(self.text(etype, evalue, etb, tb_offset))
1155 out.write('\n')
1155 out.write('\n')
1156 out.flush()
1156 out.flush()
1157 # FIXME: we should remove the auto pdb behavior from here and leave
1157 # FIXME: we should remove the auto pdb behavior from here and leave
1158 # that to the clients.
1158 # that to the clients.
1159 try:
1159 try:
1160 self.debugger()
1160 self.debugger()
1161 except KeyboardInterrupt:
1161 except KeyboardInterrupt:
1162 print "\nKeyboardInterrupt"
1162 print "\nKeyboardInterrupt"
1163
1163
1164 def structured_traceback(self, etype=None, value=None, tb=None,
1164 def structured_traceback(self, etype=None, value=None, tb=None,
1165 tb_offset=None, context=5):
1165 tb_offset=None, context=5):
1166 if etype is None:
1166 if etype is None:
1167 etype,value,tb = sys.exc_info()
1167 etype,value,tb = sys.exc_info()
1168 self.tb = tb
1168 self.tb = tb
1169 return FormattedTB.structured_traceback(
1169 return FormattedTB.structured_traceback(
1170 self, etype, value, tb, tb_offset, context)
1170 self, etype, value, tb, tb_offset, context)
1171
1171
1172 #---------------------------------------------------------------------------
1172 #---------------------------------------------------------------------------
1173
1173
1174 # A simple class to preserve Nathan's original functionality.
1174 # A simple class to preserve Nathan's original functionality.
1175 class ColorTB(FormattedTB):
1175 class ColorTB(FormattedTB):
1176 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1176 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1177 def __init__(self,color_scheme='Linux',call_pdb=0):
1177 def __init__(self,color_scheme='Linux',call_pdb=0):
1178 FormattedTB.__init__(self,color_scheme=color_scheme,
1178 FormattedTB.__init__(self,color_scheme=color_scheme,
1179 call_pdb=call_pdb)
1179 call_pdb=call_pdb)
1180
1180
1181
1181
1182 class SyntaxTB(ListTB):
1182 class SyntaxTB(ListTB):
1183 """Extension which holds some state: the last exception value"""
1183 """Extension which holds some state: the last exception value"""
1184
1184
1185 def __init__(self,color_scheme = 'NoColor'):
1185 def __init__(self,color_scheme = 'NoColor'):
1186 ListTB.__init__(self,color_scheme)
1186 ListTB.__init__(self,color_scheme)
1187 self.last_syntax_error = None
1187 self.last_syntax_error = None
1188
1188
1189 def __call__(self, etype, value, elist):
1189 def __call__(self, etype, value, elist):
1190 self.last_syntax_error = value
1190 self.last_syntax_error = value
1191 ListTB.__call__(self,etype,value,elist)
1191 ListTB.__call__(self,etype,value,elist)
1192
1192
1193 def clear_err_state(self):
1193 def clear_err_state(self):
1194 """Return the current error state and clear it"""
1194 """Return the current error state and clear it"""
1195 e = self.last_syntax_error
1195 e = self.last_syntax_error
1196 self.last_syntax_error = None
1196 self.last_syntax_error = None
1197 return e
1197 return e
1198
1198
1199 def stb2text(self, stb):
1199 def stb2text(self, stb):
1200 """Convert a structured traceback (a list) to a string."""
1200 """Convert a structured traceback (a list) to a string."""
1201 return ''.join(stb)
1201 return ''.join(stb)
1202
1202
1203
1203
1204 #----------------------------------------------------------------------------
1204 #----------------------------------------------------------------------------
1205 # module testing (minimal)
1205 # module testing (minimal)
1206 if __name__ == "__main__":
1206 if __name__ == "__main__":
1207 def spam(c, (d, e)):
1207 def spam(c, (d, e)):
1208 x = c + d
1208 x = c + d
1209 y = c * d
1209 y = c * d
1210 foo(x, y)
1210 foo(x, y)
1211
1211
1212 def foo(a, b, bar=1):
1212 def foo(a, b, bar=1):
1213 eggs(a, b + bar)
1213 eggs(a, b + bar)
1214
1214
1215 def eggs(f, g, z=globals()):
1215 def eggs(f, g, z=globals()):
1216 h = f + g
1216 h = f + g
1217 i = f - g
1217 i = f - g
1218 return h / i
1218 return h / i
1219
1219
1220 print ''
1220 print ''
1221 print '*** Before ***'
1221 print '*** Before ***'
1222 try:
1222 try:
1223 print spam(1, (2, 3))
1223 print spam(1, (2, 3))
1224 except:
1224 except:
1225 traceback.print_exc()
1225 traceback.print_exc()
1226 print ''
1226 print ''
1227
1227
1228 handler = ColorTB()
1228 handler = ColorTB()
1229 print '*** ColorTB ***'
1229 print '*** ColorTB ***'
1230 try:
1230 try:
1231 print spam(1, (2, 3))
1231 print spam(1, (2, 3))
1232 except:
1232 except:
1233 apply(handler, sys.exc_info() )
1233 apply(handler, sys.exc_info() )
1234 print ''
1234 print ''
1235
1235
1236 handler = VerboseTB()
1236 handler = VerboseTB()
1237 print '*** VerboseTB ***'
1237 print '*** VerboseTB ***'
1238 try:
1238 try:
1239 print spam(1, (2, 3))
1239 print spam(1, (2, 3))
1240 except:
1240 except:
1241 apply(handler, sys.exc_info() )
1241 apply(handler, sys.exc_info() )
1242 print ''
1242 print ''
1243
1243
@@ -1,575 +1,575 b''
1 """Module for interactive demos using IPython.
1 """Module for interactive demos using IPython.
2
2
3 This module implements a few classes for running Python scripts interactively
3 This module implements a few classes for running Python scripts interactively
4 in IPython for demonstrations. With very simple markup (a few tags in
4 in IPython for demonstrations. With very simple markup (a few tags in
5 comments), you can control points where the script stops executing and returns
5 comments), you can control points where the script stops executing and returns
6 control to IPython.
6 control to IPython.
7
7
8
8
9 Provided classes
9 Provided classes
10 ================
10 ================
11
11
12 The classes are (see their docstrings for further details):
12 The classes are (see their docstrings for further details):
13
13
14 - Demo: pure python demos
14 - Demo: pure python demos
15
15
16 - IPythonDemo: demos with input to be processed by IPython as if it had been
16 - IPythonDemo: demos with input to be processed by IPython as if it had been
17 typed interactively (so magics work, as well as any other special syntax you
17 typed interactively (so magics work, as well as any other special syntax you
18 may have added via input prefilters).
18 may have added via input prefilters).
19
19
20 - LineDemo: single-line version of the Demo class. These demos are executed
20 - LineDemo: single-line version of the Demo class. These demos are executed
21 one line at a time, and require no markup.
21 one line at a time, and require no markup.
22
22
23 - IPythonLineDemo: IPython version of the LineDemo class (the demo is
23 - IPythonLineDemo: IPython version of the LineDemo class (the demo is
24 executed a line at a time, but processed via IPython).
24 executed a line at a time, but processed via IPython).
25
25
26 - ClearMixin: mixin to make Demo classes with less visual clutter. It
26 - ClearMixin: mixin to make Demo classes with less visual clutter. It
27 declares an empty marquee and a pre_cmd that clears the screen before each
27 declares an empty marquee and a pre_cmd that clears the screen before each
28 block (see Subclassing below).
28 block (see Subclassing below).
29
29
30 - ClearDemo, ClearIPDemo: mixin-enabled versions of the Demo and IPythonDemo
30 - ClearDemo, ClearIPDemo: mixin-enabled versions of the Demo and IPythonDemo
31 classes.
31 classes.
32
32
33
33
34 Subclassing
34 Subclassing
35 ===========
35 ===========
36
36
37 The classes here all include a few methods meant to make customization by
37 The classes here all include a few methods meant to make customization by
38 subclassing more convenient. Their docstrings below have some more details:
38 subclassing more convenient. Their docstrings below have some more details:
39
39
40 - marquee(): generates a marquee to provide visible on-screen markers at each
40 - marquee(): generates a marquee to provide visible on-screen markers at each
41 block start and end.
41 block start and end.
42
42
43 - pre_cmd(): run right before the execution of each block.
43 - pre_cmd(): run right before the execution of each block.
44
44
45 - post_cmd(): run right after the execution of each block. If the block
45 - post_cmd(): run right after the execution of each block. If the block
46 raises an exception, this is NOT called.
46 raises an exception, this is NOT called.
47
47
48
48
49 Operation
49 Operation
50 =========
50 =========
51
51
52 The file is run in its own empty namespace (though you can pass it a string of
52 The file is run in its own empty namespace (though you can pass it a string of
53 arguments as if in a command line environment, and it will see those as
53 arguments as if in a command line environment, and it will see those as
54 sys.argv). But at each stop, the global IPython namespace is updated with the
54 sys.argv). But at each stop, the global IPython namespace is updated with the
55 current internal demo namespace, so you can work interactively with the data
55 current internal demo namespace, so you can work interactively with the data
56 accumulated so far.
56 accumulated so far.
57
57
58 By default, each block of code is printed (with syntax highlighting) before
58 By default, each block of code is printed (with syntax highlighting) before
59 executing it and you have to confirm execution. This is intended to show the
59 executing it and you have to confirm execution. This is intended to show the
60 code to an audience first so you can discuss it, and only proceed with
60 code to an audience first so you can discuss it, and only proceed with
61 execution once you agree. There are a few tags which allow you to modify this
61 execution once you agree. There are a few tags which allow you to modify this
62 behavior.
62 behavior.
63
63
64 The supported tags are:
64 The supported tags are:
65
65
66 # <demo> stop
66 # <demo> stop
67
67
68 Defines block boundaries, the points where IPython stops execution of the
68 Defines block boundaries, the points where IPython stops execution of the
69 file and returns to the interactive prompt.
69 file and returns to the interactive prompt.
70
70
71 You can optionally mark the stop tag with extra dashes before and after the
71 You can optionally mark the stop tag with extra dashes before and after the
72 word 'stop', to help visually distinguish the blocks in a text editor:
72 word 'stop', to help visually distinguish the blocks in a text editor:
73
73
74 # <demo> --- stop ---
74 # <demo> --- stop ---
75
75
76
76
77 # <demo> silent
77 # <demo> silent
78
78
79 Make a block execute silently (and hence automatically). Typically used in
79 Make a block execute silently (and hence automatically). Typically used in
80 cases where you have some boilerplate or initialization code which you need
80 cases where you have some boilerplate or initialization code which you need
81 executed but do not want to be seen in the demo.
81 executed but do not want to be seen in the demo.
82
82
83 # <demo> auto
83 # <demo> auto
84
84
85 Make a block execute automatically, but still being printed. Useful for
85 Make a block execute automatically, but still being printed. Useful for
86 simple code which does not warrant discussion, since it avoids the extra
86 simple code which does not warrant discussion, since it avoids the extra
87 manual confirmation.
87 manual confirmation.
88
88
89 # <demo> auto_all
89 # <demo> auto_all
90
90
91 This tag can _only_ be in the first block, and if given it overrides the
91 This tag can _only_ be in the first block, and if given it overrides the
92 individual auto tags to make the whole demo fully automatic (no block asks
92 individual auto tags to make the whole demo fully automatic (no block asks
93 for confirmation). It can also be given at creation time (or the attribute
93 for confirmation). It can also be given at creation time (or the attribute
94 set later) to override what's in the file.
94 set later) to override what's in the file.
95
95
96 While _any_ python file can be run as a Demo instance, if there are no stop
96 While _any_ python file can be run as a Demo instance, if there are no stop
97 tags the whole file will run in a single block (no different that calling
97 tags the whole file will run in a single block (no different that calling
98 first %pycat and then %run). The minimal markup to make this useful is to
98 first %pycat and then %run). The minimal markup to make this useful is to
99 place a set of stop tags; the other tags are only there to let you fine-tune
99 place a set of stop tags; the other tags are only there to let you fine-tune
100 the execution.
100 the execution.
101
101
102 This is probably best explained with the simple example file below. You can
102 This is probably best explained with the simple example file below. You can
103 copy this into a file named ex_demo.py, and try running it via:
103 copy this into a file named ex_demo.py, and try running it via:
104
104
105 from IPython.demo import Demo
105 from IPython.demo import Demo
106 d = Demo('ex_demo.py')
106 d = Demo('ex_demo.py')
107 d() <--- Call the d object (omit the parens if you have autocall set to 2).
107 d() <--- Call the d object (omit the parens if you have autocall set to 2).
108
108
109 Each time you call the demo object, it runs the next block. The demo object
109 Each time you call the demo object, it runs the next block. The demo object
110 has a few useful methods for navigation, like again(), edit(), jump(), seek()
110 has a few useful methods for navigation, like again(), edit(), jump(), seek()
111 and back(). It can be reset for a new run via reset() or reloaded from disk
111 and back(). It can be reset for a new run via reset() or reloaded from disk
112 (in case you've edited the source) via reload(). See their docstrings below.
112 (in case you've edited the source) via reload(). See their docstrings below.
113
113
114 Note: To make this simpler to explore, a file called "demo-exercizer.py" has
114 Note: To make this simpler to explore, a file called "demo-exercizer.py" has
115 been added to the "docs/examples/core" directory. Just cd to this directory in
115 been added to the "docs/examples/core" directory. Just cd to this directory in
116 an IPython session, and type::
116 an IPython session, and type::
117
117
118 %run demo-exercizer.py
118 %run demo-exercizer.py
119
119
120 and then follow the directions.
120 and then follow the directions.
121
121
122 Example
122 Example
123 =======
123 =======
124
124
125 The following is a very simple example of a valid demo file.
125 The following is a very simple example of a valid demo file.
126
126
127 #################### EXAMPLE DEMO <ex_demo.py> ###############################
127 #################### EXAMPLE DEMO <ex_demo.py> ###############################
128 '''A simple interactive demo to illustrate the use of IPython's Demo class.'''
128 '''A simple interactive demo to illustrate the use of IPython's Demo class.'''
129
129
130 print 'Hello, welcome to an interactive IPython demo.'
130 print 'Hello, welcome to an interactive IPython demo.'
131
131
132 # The mark below defines a block boundary, which is a point where IPython will
132 # The mark below defines a block boundary, which is a point where IPython will
133 # stop execution and return to the interactive prompt. The dashes are actually
133 # stop execution and return to the interactive prompt. The dashes are actually
134 # optional and used only as a visual aid to clearly separate blocks while
134 # optional and used only as a visual aid to clearly separate blocks while
135 # editing the demo code.
135 # editing the demo code.
136 # <demo> stop
136 # <demo> stop
137
137
138 x = 1
138 x = 1
139 y = 2
139 y = 2
140
140
141 # <demo> stop
141 # <demo> stop
142
142
143 # the mark below makes this block as silent
143 # the mark below makes this block as silent
144 # <demo> silent
144 # <demo> silent
145
145
146 print 'This is a silent block, which gets executed but not printed.'
146 print 'This is a silent block, which gets executed but not printed.'
147
147
148 # <demo> stop
148 # <demo> stop
149 # <demo> auto
149 # <demo> auto
150 print 'This is an automatic block.'
150 print 'This is an automatic block.'
151 print 'It is executed without asking for confirmation, but printed.'
151 print 'It is executed without asking for confirmation, but printed.'
152 z = x+y
152 z = x+y
153
153
154 print 'z=',x
154 print 'z=',x
155
155
156 # <demo> stop
156 # <demo> stop
157 # This is just another normal block.
157 # This is just another normal block.
158 print 'z is now:', z
158 print 'z is now:', z
159
159
160 print 'bye!'
160 print 'bye!'
161 ################### END EXAMPLE DEMO <ex_demo.py> ############################
161 ################### END EXAMPLE DEMO <ex_demo.py> ############################
162 """
162 """
163
163
164 #*****************************************************************************
164 #*****************************************************************************
165 # Copyright (C) 2005-2006 Fernando Perez. <Fernando.Perez@colorado.edu>
165 # Copyright (C) 2005-2006 Fernando Perez. <Fernando.Perez@colorado.edu>
166 #
166 #
167 # Distributed under the terms of the BSD License. The full license is in
167 # Distributed under the terms of the BSD License. The full license is in
168 # the file COPYING, distributed as part of this software.
168 # the file COPYING, distributed as part of this software.
169 #
169 #
170 #*****************************************************************************
170 #*****************************************************************************
171
171
172 import exceptions
172 import exceptions
173 import os
173 import os
174 import re
174 import re
175 import shlex
175 import shlex
176 import sys
176 import sys
177
177
178 from IPython.utils.PyColorize import Parser
178 from IPython.utils.PyColorize import Parser
179 from IPython.utils import io
179 from IPython.utils.io import file_read, file_readlines
180 from IPython.utils.io import file_read, file_readlines
180 import IPython.utils.io
181 from IPython.utils.text import marquee
181 from IPython.utils.text import marquee
182
182
183 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
183 __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
184
184
185 class DemoError(exceptions.Exception): pass
185 class DemoError(exceptions.Exception): pass
186
186
187 def re_mark(mark):
187 def re_mark(mark):
188 return re.compile(r'^\s*#\s+<demo>\s+%s\s*$' % mark,re.MULTILINE)
188 return re.compile(r'^\s*#\s+<demo>\s+%s\s*$' % mark,re.MULTILINE)
189
189
190 class Demo(object):
190 class Demo(object):
191
191
192 re_stop = re_mark('-*\s?stop\s?-*')
192 re_stop = re_mark('-*\s?stop\s?-*')
193 re_silent = re_mark('silent')
193 re_silent = re_mark('silent')
194 re_auto = re_mark('auto')
194 re_auto = re_mark('auto')
195 re_auto_all = re_mark('auto_all')
195 re_auto_all = re_mark('auto_all')
196
196
197 def __init__(self,src,title='',arg_str='',auto_all=None):
197 def __init__(self,src,title='',arg_str='',auto_all=None):
198 """Make a new demo object. To run the demo, simply call the object.
198 """Make a new demo object. To run the demo, simply call the object.
199
199
200 See the module docstring for full details and an example (you can use
200 See the module docstring for full details and an example (you can use
201 IPython.Demo? in IPython to see it).
201 IPython.Demo? in IPython to see it).
202
202
203 Inputs:
203 Inputs:
204
204
205 - src is either a file, or file-like object, or a
205 - src is either a file, or file-like object, or a
206 string that can be resolved to a filename.
206 string that can be resolved to a filename.
207
207
208 Optional inputs:
208 Optional inputs:
209
209
210 - title: a string to use as the demo name. Of most use when the demo
210 - title: a string to use as the demo name. Of most use when the demo
211 you are making comes from an object that has no filename, or if you
211 you are making comes from an object that has no filename, or if you
212 want an alternate denotation distinct from the filename.
212 want an alternate denotation distinct from the filename.
213
213
214 - arg_str(''): a string of arguments, internally converted to a list
214 - arg_str(''): a string of arguments, internally converted to a list
215 just like sys.argv, so the demo script can see a similar
215 just like sys.argv, so the demo script can see a similar
216 environment.
216 environment.
217
217
218 - auto_all(None): global flag to run all blocks automatically without
218 - auto_all(None): global flag to run all blocks automatically without
219 confirmation. This attribute overrides the block-level tags and
219 confirmation. This attribute overrides the block-level tags and
220 applies to the whole demo. It is an attribute of the object, and
220 applies to the whole demo. It is an attribute of the object, and
221 can be changed at runtime simply by reassigning it to a boolean
221 can be changed at runtime simply by reassigning it to a boolean
222 value.
222 value.
223 """
223 """
224 if hasattr(src, "read"):
224 if hasattr(src, "read"):
225 # It seems to be a file or a file-like object
225 # It seems to be a file or a file-like object
226 self.fname = "from a file-like object"
226 self.fname = "from a file-like object"
227 if title == '':
227 if title == '':
228 self.title = "from a file-like object"
228 self.title = "from a file-like object"
229 else:
229 else:
230 self.title = title
230 self.title = title
231 else:
231 else:
232 # Assume it's a string or something that can be converted to one
232 # Assume it's a string or something that can be converted to one
233 self.fname = src
233 self.fname = src
234 if title == '':
234 if title == '':
235 (filepath, filename) = os.path.split(src)
235 (filepath, filename) = os.path.split(src)
236 self.title = filename
236 self.title = filename
237 else:
237 else:
238 self.title = title
238 self.title = title
239 self.sys_argv = [src] + shlex.split(arg_str)
239 self.sys_argv = [src] + shlex.split(arg_str)
240 self.auto_all = auto_all
240 self.auto_all = auto_all
241 self.src = src
241 self.src = src
242
242
243 # get a few things from ipython. While it's a bit ugly design-wise,
243 # get a few things from ipython. While it's a bit ugly design-wise,
244 # it ensures that things like color scheme and the like are always in
244 # it ensures that things like color scheme and the like are always in
245 # sync with the ipython mode being used. This class is only meant to
245 # sync with the ipython mode being used. This class is only meant to
246 # be used inside ipython anyways, so it's OK.
246 # be used inside ipython anyways, so it's OK.
247 ip = get_ipython() # this is in builtins whenever IPython is running
247 ip = get_ipython() # this is in builtins whenever IPython is running
248 self.ip_ns = ip.user_ns
248 self.ip_ns = ip.user_ns
249 self.ip_colorize = ip.pycolorize
249 self.ip_colorize = ip.pycolorize
250 self.ip_showtb = ip.showtraceback
250 self.ip_showtb = ip.showtraceback
251 self.ip_run_cell = ip.run_cell
251 self.ip_run_cell = ip.run_cell
252 self.shell = ip
252 self.shell = ip
253
253
254 # load user data and initialize data structures
254 # load user data and initialize data structures
255 self.reload()
255 self.reload()
256
256
257 def fload(self):
257 def fload(self):
258 """Load file object."""
258 """Load file object."""
259 # read data and parse into blocks
259 # read data and parse into blocks
260 if hasattr(self, 'fobj') and self.fobj is not None:
260 if hasattr(self, 'fobj') and self.fobj is not None:
261 self.fobj.close()
261 self.fobj.close()
262 if hasattr(self.src, "read"):
262 if hasattr(self.src, "read"):
263 # It seems to be a file or a file-like object
263 # It seems to be a file or a file-like object
264 self.fobj = self.src
264 self.fobj = self.src
265 else:
265 else:
266 # Assume it's a string or something that can be converted to one
266 # Assume it's a string or something that can be converted to one
267 self.fobj = open(self.fname)
267 self.fobj = open(self.fname)
268
268
269 def reload(self):
269 def reload(self):
270 """Reload source from disk and initialize state."""
270 """Reload source from disk and initialize state."""
271 self.fload()
271 self.fload()
272
272
273 self.src = self.fobj.read()
273 self.src = self.fobj.read()
274 src_b = [b.strip() for b in self.re_stop.split(self.src) if b]
274 src_b = [b.strip() for b in self.re_stop.split(self.src) if b]
275 self._silent = [bool(self.re_silent.findall(b)) for b in src_b]
275 self._silent = [bool(self.re_silent.findall(b)) for b in src_b]
276 self._auto = [bool(self.re_auto.findall(b)) for b in src_b]
276 self._auto = [bool(self.re_auto.findall(b)) for b in src_b]
277
277
278 # if auto_all is not given (def. None), we read it from the file
278 # if auto_all is not given (def. None), we read it from the file
279 if self.auto_all is None:
279 if self.auto_all is None:
280 self.auto_all = bool(self.re_auto_all.findall(src_b[0]))
280 self.auto_all = bool(self.re_auto_all.findall(src_b[0]))
281 else:
281 else:
282 self.auto_all = bool(self.auto_all)
282 self.auto_all = bool(self.auto_all)
283
283
284 # Clean the sources from all markup so it doesn't get displayed when
284 # Clean the sources from all markup so it doesn't get displayed when
285 # running the demo
285 # running the demo
286 src_blocks = []
286 src_blocks = []
287 auto_strip = lambda s: self.re_auto.sub('',s)
287 auto_strip = lambda s: self.re_auto.sub('',s)
288 for i,b in enumerate(src_b):
288 for i,b in enumerate(src_b):
289 if self._auto[i]:
289 if self._auto[i]:
290 src_blocks.append(auto_strip(b))
290 src_blocks.append(auto_strip(b))
291 else:
291 else:
292 src_blocks.append(b)
292 src_blocks.append(b)
293 # remove the auto_all marker
293 # remove the auto_all marker
294 src_blocks[0] = self.re_auto_all.sub('',src_blocks[0])
294 src_blocks[0] = self.re_auto_all.sub('',src_blocks[0])
295
295
296 self.nblocks = len(src_blocks)
296 self.nblocks = len(src_blocks)
297 self.src_blocks = src_blocks
297 self.src_blocks = src_blocks
298
298
299 # also build syntax-highlighted source
299 # also build syntax-highlighted source
300 self.src_blocks_colored = map(self.ip_colorize,self.src_blocks)
300 self.src_blocks_colored = map(self.ip_colorize,self.src_blocks)
301
301
302 # ensure clean namespace and seek offset
302 # ensure clean namespace and seek offset
303 self.reset()
303 self.reset()
304
304
305 def reset(self):
305 def reset(self):
306 """Reset the namespace and seek pointer to restart the demo"""
306 """Reset the namespace and seek pointer to restart the demo"""
307 self.user_ns = {}
307 self.user_ns = {}
308 self.finished = False
308 self.finished = False
309 self.block_index = 0
309 self.block_index = 0
310
310
311 def _validate_index(self,index):
311 def _validate_index(self,index):
312 if index<0 or index>=self.nblocks:
312 if index<0 or index>=self.nblocks:
313 raise ValueError('invalid block index %s' % index)
313 raise ValueError('invalid block index %s' % index)
314
314
315 def _get_index(self,index):
315 def _get_index(self,index):
316 """Get the current block index, validating and checking status.
316 """Get the current block index, validating and checking status.
317
317
318 Returns None if the demo is finished"""
318 Returns None if the demo is finished"""
319
319
320 if index is None:
320 if index is None:
321 if self.finished:
321 if self.finished:
322 print >>IPython.utils.io.Term.cout, 'Demo finished. Use <demo_name>.reset() if you want to rerun it.'
322 print >>io.stdout, 'Demo finished. Use <demo_name>.reset() if you want to rerun it.'
323 return None
323 return None
324 index = self.block_index
324 index = self.block_index
325 else:
325 else:
326 self._validate_index(index)
326 self._validate_index(index)
327 return index
327 return index
328
328
329 def seek(self,index):
329 def seek(self,index):
330 """Move the current seek pointer to the given block.
330 """Move the current seek pointer to the given block.
331
331
332 You can use negative indices to seek from the end, with identical
332 You can use negative indices to seek from the end, with identical
333 semantics to those of Python lists."""
333 semantics to those of Python lists."""
334 if index<0:
334 if index<0:
335 index = self.nblocks + index
335 index = self.nblocks + index
336 self._validate_index(index)
336 self._validate_index(index)
337 self.block_index = index
337 self.block_index = index
338 self.finished = False
338 self.finished = False
339
339
340 def back(self,num=1):
340 def back(self,num=1):
341 """Move the seek pointer back num blocks (default is 1)."""
341 """Move the seek pointer back num blocks (default is 1)."""
342 self.seek(self.block_index-num)
342 self.seek(self.block_index-num)
343
343
344 def jump(self,num=1):
344 def jump(self,num=1):
345 """Jump a given number of blocks relative to the current one.
345 """Jump a given number of blocks relative to the current one.
346
346
347 The offset can be positive or negative, defaults to 1."""
347 The offset can be positive or negative, defaults to 1."""
348 self.seek(self.block_index+num)
348 self.seek(self.block_index+num)
349
349
350 def again(self):
350 def again(self):
351 """Move the seek pointer back one block and re-execute."""
351 """Move the seek pointer back one block and re-execute."""
352 self.back(1)
352 self.back(1)
353 self()
353 self()
354
354
355 def edit(self,index=None):
355 def edit(self,index=None):
356 """Edit a block.
356 """Edit a block.
357
357
358 If no number is given, use the last block executed.
358 If no number is given, use the last block executed.
359
359
360 This edits the in-memory copy of the demo, it does NOT modify the
360 This edits the in-memory copy of the demo, it does NOT modify the
361 original source file. If you want to do that, simply open the file in
361 original source file. If you want to do that, simply open the file in
362 an editor and use reload() when you make changes to the file. This
362 an editor and use reload() when you make changes to the file. This
363 method is meant to let you change a block during a demonstration for
363 method is meant to let you change a block during a demonstration for
364 explanatory purposes, without damaging your original script."""
364 explanatory purposes, without damaging your original script."""
365
365
366 index = self._get_index(index)
366 index = self._get_index(index)
367 if index is None:
367 if index is None:
368 return
368 return
369 # decrease the index by one (unless we're at the very beginning), so
369 # decrease the index by one (unless we're at the very beginning), so
370 # that the default demo.edit() call opens up the sblock we've last run
370 # that the default demo.edit() call opens up the sblock we've last run
371 if index>0:
371 if index>0:
372 index -= 1
372 index -= 1
373
373
374 filename = self.shell.mktempfile(self.src_blocks[index])
374 filename = self.shell.mktempfile(self.src_blocks[index])
375 self.shell.hooks.editor(filename,1)
375 self.shell.hooks.editor(filename,1)
376 new_block = file_read(filename)
376 new_block = file_read(filename)
377 # update the source and colored block
377 # update the source and colored block
378 self.src_blocks[index] = new_block
378 self.src_blocks[index] = new_block
379 self.src_blocks_colored[index] = self.ip_colorize(new_block)
379 self.src_blocks_colored[index] = self.ip_colorize(new_block)
380 self.block_index = index
380 self.block_index = index
381 # call to run with the newly edited index
381 # call to run with the newly edited index
382 self()
382 self()
383
383
384 def show(self,index=None):
384 def show(self,index=None):
385 """Show a single block on screen"""
385 """Show a single block on screen"""
386
386
387 index = self._get_index(index)
387 index = self._get_index(index)
388 if index is None:
388 if index is None:
389 return
389 return
390
390
391 print >>IPython.utils.io.Term.cout, self.marquee('<%s> block # %s (%s remaining)' %
391 print >>io.stdout, self.marquee('<%s> block # %s (%s remaining)' %
392 (self.title,index,self.nblocks-index-1))
392 (self.title,index,self.nblocks-index-1))
393 print >>IPython.utils.io.Term.cout,(self.src_blocks_colored[index])
393 print >>io.stdout,(self.src_blocks_colored[index])
394 sys.stdout.flush()
394 sys.stdout.flush()
395
395
396 def show_all(self):
396 def show_all(self):
397 """Show entire demo on screen, block by block"""
397 """Show entire demo on screen, block by block"""
398
398
399 fname = self.title
399 fname = self.title
400 title = self.title
400 title = self.title
401 nblocks = self.nblocks
401 nblocks = self.nblocks
402 silent = self._silent
402 silent = self._silent
403 marquee = self.marquee
403 marquee = self.marquee
404 for index,block in enumerate(self.src_blocks_colored):
404 for index,block in enumerate(self.src_blocks_colored):
405 if silent[index]:
405 if silent[index]:
406 print >>IPython.utils.io.Term.cout, marquee('<%s> SILENT block # %s (%s remaining)' %
406 print >>io.stdout, marquee('<%s> SILENT block # %s (%s remaining)' %
407 (title,index,nblocks-index-1))
407 (title,index,nblocks-index-1))
408 else:
408 else:
409 print >>IPython.utils.io.Term.cout, marquee('<%s> block # %s (%s remaining)' %
409 print >>io.stdout, marquee('<%s> block # %s (%s remaining)' %
410 (title,index,nblocks-index-1))
410 (title,index,nblocks-index-1))
411 print >>IPython.utils.io.Term.cout, block,
411 print >>io.stdout, block,
412 sys.stdout.flush()
412 sys.stdout.flush()
413
413
414 def run_cell(self,source):
414 def run_cell(self,source):
415 """Execute a string with one or more lines of code"""
415 """Execute a string with one or more lines of code"""
416
416
417 exec source in self.user_ns
417 exec source in self.user_ns
418
418
419 def __call__(self,index=None):
419 def __call__(self,index=None):
420 """run a block of the demo.
420 """run a block of the demo.
421
421
422 If index is given, it should be an integer >=1 and <= nblocks. This
422 If index is given, it should be an integer >=1 and <= nblocks. This
423 means that the calling convention is one off from typical Python
423 means that the calling convention is one off from typical Python
424 lists. The reason for the inconsistency is that the demo always
424 lists. The reason for the inconsistency is that the demo always
425 prints 'Block n/N, and N is the total, so it would be very odd to use
425 prints 'Block n/N, and N is the total, so it would be very odd to use
426 zero-indexing here."""
426 zero-indexing here."""
427
427
428 index = self._get_index(index)
428 index = self._get_index(index)
429 if index is None:
429 if index is None:
430 return
430 return
431 try:
431 try:
432 marquee = self.marquee
432 marquee = self.marquee
433 next_block = self.src_blocks[index]
433 next_block = self.src_blocks[index]
434 self.block_index += 1
434 self.block_index += 1
435 if self._silent[index]:
435 if self._silent[index]:
436 print >>IPython.utils.io.Term.cout, marquee('Executing silent block # %s (%s remaining)' %
436 print >>io.stdout, marquee('Executing silent block # %s (%s remaining)' %
437 (index,self.nblocks-index-1))
437 (index,self.nblocks-index-1))
438 else:
438 else:
439 self.pre_cmd()
439 self.pre_cmd()
440 self.show(index)
440 self.show(index)
441 if self.auto_all or self._auto[index]:
441 if self.auto_all or self._auto[index]:
442 print >>IPython.utils.io.Term.cout, marquee('output:')
442 print >>io.stdout, marquee('output:')
443 else:
443 else:
444 print >>IPython.utils.io.Term.cout, marquee('Press <q> to quit, <Enter> to execute...'),
444 print >>io.stdout, marquee('Press <q> to quit, <Enter> to execute...'),
445 ans = raw_input().strip()
445 ans = raw_input().strip()
446 if ans:
446 if ans:
447 print >>IPython.utils.io.Term.cout, marquee('Block NOT executed')
447 print >>io.stdout, marquee('Block NOT executed')
448 return
448 return
449 try:
449 try:
450 save_argv = sys.argv
450 save_argv = sys.argv
451 sys.argv = self.sys_argv
451 sys.argv = self.sys_argv
452 self.run_cell(next_block)
452 self.run_cell(next_block)
453 self.post_cmd()
453 self.post_cmd()
454 finally:
454 finally:
455 sys.argv = save_argv
455 sys.argv = save_argv
456
456
457 except:
457 except:
458 self.ip_showtb(filename=self.fname)
458 self.ip_showtb(filename=self.fname)
459 else:
459 else:
460 self.ip_ns.update(self.user_ns)
460 self.ip_ns.update(self.user_ns)
461
461
462 if self.block_index == self.nblocks:
462 if self.block_index == self.nblocks:
463 mq1 = self.marquee('END OF DEMO')
463 mq1 = self.marquee('END OF DEMO')
464 if mq1:
464 if mq1:
465 # avoid spurious print >>IPython.utils.io.Term.cout,s if empty marquees are used
465 # avoid spurious print >>io.stdout,s if empty marquees are used
466 print >>IPython.utils.io.Term.cout
466 print >>io.stdout
467 print >>IPython.utils.io.Term.cout, mq1
467 print >>io.stdout, mq1
468 print >>IPython.utils.io.Term.cout, self.marquee('Use <demo_name>.reset() if you want to rerun it.')
468 print >>io.stdout, self.marquee('Use <demo_name>.reset() if you want to rerun it.')
469 self.finished = True
469 self.finished = True
470
470
471 # These methods are meant to be overridden by subclasses who may wish to
471 # These methods are meant to be overridden by subclasses who may wish to
472 # customize the behavior of of their demos.
472 # customize the behavior of of their demos.
473 def marquee(self,txt='',width=78,mark='*'):
473 def marquee(self,txt='',width=78,mark='*'):
474 """Return the input string centered in a 'marquee'."""
474 """Return the input string centered in a 'marquee'."""
475 return marquee(txt,width,mark)
475 return marquee(txt,width,mark)
476
476
477 def pre_cmd(self):
477 def pre_cmd(self):
478 """Method called before executing each block."""
478 """Method called before executing each block."""
479 pass
479 pass
480
480
481 def post_cmd(self):
481 def post_cmd(self):
482 """Method called after executing each block."""
482 """Method called after executing each block."""
483 pass
483 pass
484
484
485
485
486 class IPythonDemo(Demo):
486 class IPythonDemo(Demo):
487 """Class for interactive demos with IPython's input processing applied.
487 """Class for interactive demos with IPython's input processing applied.
488
488
489 This subclasses Demo, but instead of executing each block by the Python
489 This subclasses Demo, but instead of executing each block by the Python
490 interpreter (via exec), it actually calls IPython on it, so that any input
490 interpreter (via exec), it actually calls IPython on it, so that any input
491 filters which may be in place are applied to the input block.
491 filters which may be in place are applied to the input block.
492
492
493 If you have an interactive environment which exposes special input
493 If you have an interactive environment which exposes special input
494 processing, you can use this class instead to write demo scripts which
494 processing, you can use this class instead to write demo scripts which
495 operate exactly as if you had typed them interactively. The default Demo
495 operate exactly as if you had typed them interactively. The default Demo
496 class requires the input to be valid, pure Python code.
496 class requires the input to be valid, pure Python code.
497 """
497 """
498
498
499 def run_cell(self,source):
499 def run_cell(self,source):
500 """Execute a string with one or more lines of code"""
500 """Execute a string with one or more lines of code"""
501
501
502 self.shell.run_cell(source)
502 self.shell.run_cell(source)
503
503
504 class LineDemo(Demo):
504 class LineDemo(Demo):
505 """Demo where each line is executed as a separate block.
505 """Demo where each line is executed as a separate block.
506
506
507 The input script should be valid Python code.
507 The input script should be valid Python code.
508
508
509 This class doesn't require any markup at all, and it's meant for simple
509 This class doesn't require any markup at all, and it's meant for simple
510 scripts (with no nesting or any kind of indentation) which consist of
510 scripts (with no nesting or any kind of indentation) which consist of
511 multiple lines of input to be executed, one at a time, as if they had been
511 multiple lines of input to be executed, one at a time, as if they had been
512 typed in the interactive prompt.
512 typed in the interactive prompt.
513
513
514 Note: the input can not have *any* indentation, which means that only
514 Note: the input can not have *any* indentation, which means that only
515 single-lines of input are accepted, not even function definitions are
515 single-lines of input are accepted, not even function definitions are
516 valid."""
516 valid."""
517
517
518 def reload(self):
518 def reload(self):
519 """Reload source from disk and initialize state."""
519 """Reload source from disk and initialize state."""
520 # read data and parse into blocks
520 # read data and parse into blocks
521 self.fload()
521 self.fload()
522 lines = self.fobj.readlines()
522 lines = self.fobj.readlines()
523 src_b = [l for l in lines if l.strip()]
523 src_b = [l for l in lines if l.strip()]
524 nblocks = len(src_b)
524 nblocks = len(src_b)
525 self.src = ''.join(lines)
525 self.src = ''.join(lines)
526 self._silent = [False]*nblocks
526 self._silent = [False]*nblocks
527 self._auto = [True]*nblocks
527 self._auto = [True]*nblocks
528 self.auto_all = True
528 self.auto_all = True
529 self.nblocks = nblocks
529 self.nblocks = nblocks
530 self.src_blocks = src_b
530 self.src_blocks = src_b
531
531
532 # also build syntax-highlighted source
532 # also build syntax-highlighted source
533 self.src_blocks_colored = map(self.ip_colorize,self.src_blocks)
533 self.src_blocks_colored = map(self.ip_colorize,self.src_blocks)
534
534
535 # ensure clean namespace and seek offset
535 # ensure clean namespace and seek offset
536 self.reset()
536 self.reset()
537
537
538
538
539 class IPythonLineDemo(IPythonDemo,LineDemo):
539 class IPythonLineDemo(IPythonDemo,LineDemo):
540 """Variant of the LineDemo class whose input is processed by IPython."""
540 """Variant of the LineDemo class whose input is processed by IPython."""
541 pass
541 pass
542
542
543
543
544 class ClearMixin(object):
544 class ClearMixin(object):
545 """Use this mixin to make Demo classes with less visual clutter.
545 """Use this mixin to make Demo classes with less visual clutter.
546
546
547 Demos using this mixin will clear the screen before every block and use
547 Demos using this mixin will clear the screen before every block and use
548 blank marquees.
548 blank marquees.
549
549
550 Note that in order for the methods defined here to actually override those
550 Note that in order for the methods defined here to actually override those
551 of the classes it's mixed with, it must go /first/ in the inheritance
551 of the classes it's mixed with, it must go /first/ in the inheritance
552 tree. For example:
552 tree. For example:
553
553
554 class ClearIPDemo(ClearMixin,IPythonDemo): pass
554 class ClearIPDemo(ClearMixin,IPythonDemo): pass
555
555
556 will provide an IPythonDemo class with the mixin's features.
556 will provide an IPythonDemo class with the mixin's features.
557 """
557 """
558
558
559 def marquee(self,txt='',width=78,mark='*'):
559 def marquee(self,txt='',width=78,mark='*'):
560 """Blank marquee that returns '' no matter what the input."""
560 """Blank marquee that returns '' no matter what the input."""
561 return ''
561 return ''
562
562
563 def pre_cmd(self):
563 def pre_cmd(self):
564 """Method called before executing each block.
564 """Method called before executing each block.
565
565
566 This one simply clears the screen."""
566 This one simply clears the screen."""
567 from IPython.utils.terminal import term_clear
567 from IPython.utils.terminal import term_clear
568 term_clear()
568 term_clear()
569
569
570 class ClearDemo(ClearMixin,Demo):
570 class ClearDemo(ClearMixin,Demo):
571 pass
571 pass
572
572
573
573
574 class ClearIPDemo(ClearMixin,IPythonDemo):
574 class ClearIPDemo(ClearMixin,IPythonDemo):
575 pass
575 pass
@@ -1,299 +1,322 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 IO related utilities.
3 IO related utilities.
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 #
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 from __future__ import print_function
12 from __future__ import print_function
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 import sys
17 import sys
18 import tempfile
18 import tempfile
19
19
20 from IPython.external.Itpl import itpl, printpl
20 from IPython.external.Itpl import itpl, printpl
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Code
23 # Code
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26
26
27 class IOStream:
27 class IOStream:
28
28
29 def __init__(self,stream,fallback):
29 def __init__(self,stream, fallback=None):
30 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
30 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
31 stream = fallback
31 if fallback is not None:
32 stream = fallback
33 else:
34 raise ValueError("fallback required, but not specified")
32 self.stream = stream
35 self.stream = stream
33 self._swrite = stream.write
36 self._swrite = stream.write
34 self.flush = stream.flush
37
35
38 # clone all methods not overridden:
39 def clone(meth):
40 return not hasattr(self, meth) and not meth.startswith('_')
41 for meth in filter(clone, dir(stream)):
42 setattr(self, meth, getattr(stream, meth))
43
36 def write(self,data):
44 def write(self,data):
37 try:
45 try:
38 self._swrite(data)
46 self._swrite(data)
39 except:
47 except:
40 try:
48 try:
41 # print handles some unicode issues which may trip a plain
49 # print handles some unicode issues which may trip a plain
42 # write() call. Emulate write() by using an empty end
50 # write() call. Emulate write() by using an empty end
43 # argument.
51 # argument.
44 print(data, end='', file=self.stream)
52 print(data, end='', file=self.stream)
45 except:
53 except:
46 # if we get here, something is seriously broken.
54 # if we get here, something is seriously broken.
47 print('ERROR - failed to write data to stream:', self.stream,
55 print('ERROR - failed to write data to stream:', self.stream,
48 file=sys.stderr)
56 file=sys.stderr)
57
58 def writelines(self, lines):
59 if isinstance(lines, basestring):
60 lines = [lines]
61 for line in lines:
62 self.write(line)
49
63
50 # This class used to have a writeln method, but regular files and streams
64 # This class used to have a writeln method, but regular files and streams
51 # in Python don't have this method. We need to keep this completely
65 # in Python don't have this method. We need to keep this completely
52 # compatible so we removed it.
66 # compatible so we removed it.
53
67
68 @property
69 def closed(self):
70 return self.stream.closed
71
54 def close(self):
72 def close(self):
55 pass
73 pass
56
74
57
75
58 class IOTerm:
76 class IOTerm:
59 """ Term holds the file or file-like objects for handling I/O operations.
77 """ Term holds the file or file-like objects for handling I/O operations.
60
78
61 These are normally just sys.stdin, sys.stdout and sys.stderr but for
79 These are normally just sys.stdin, sys.stdout and sys.stderr but for
62 Windows they can can replaced to allow editing the strings before they are
80 Windows they can can replaced to allow editing the strings before they are
63 displayed."""
81 displayed."""
64
82
65 # In the future, having IPython channel all its I/O operations through
83 # In the future, having IPython channel all its I/O operations through
66 # this class will make it easier to embed it into other environments which
84 # this class will make it easier to embed it into other environments which
67 # are not a normal terminal (such as a GUI-based shell)
85 # are not a normal terminal (such as a GUI-based shell)
68 def __init__(self, cin=None, cout=None, cerr=None):
86 def __init__(self, stdin=None, stdout=None, stderr=None):
69 self.cin = IOStream(cin, sys.stdin)
87 self.stdin = IOStream(stdin, sys.stdin)
70 self.cout = IOStream(cout, sys.stdout)
88 self.stdout = IOStream(stdout, sys.stdout)
71 self.cerr = IOStream(cerr, sys.stderr)
89 self.stderr = IOStream(stderr, sys.stderr)
90
91 # setup stdin/stdout/stderr to sys.stdin/sys.stdout/sys.stderr
92 stdin = IOStream(sys.stdin)
93 stdout = IOStream(sys.stdout)
94 stderr = IOStream(sys.stderr)
72
95
73
96
74 class Tee(object):
97 class Tee(object):
75 """A class to duplicate an output stream to stdout/err.
98 """A class to duplicate an output stream to stdout/err.
76
99
77 This works in a manner very similar to the Unix 'tee' command.
100 This works in a manner very similar to the Unix 'tee' command.
78
101
79 When the object is closed or deleted, it closes the original file given to
102 When the object is closed or deleted, it closes the original file given to
80 it for duplication.
103 it for duplication.
81 """
104 """
82 # Inspired by:
105 # Inspired by:
83 # http://mail.python.org/pipermail/python-list/2007-May/442737.html
106 # http://mail.python.org/pipermail/python-list/2007-May/442737.html
84
107
85 def __init__(self, file_or_name, mode=None, channel='stdout'):
108 def __init__(self, file_or_name, mode=None, channel='stdout'):
86 """Construct a new Tee object.
109 """Construct a new Tee object.
87
110
88 Parameters
111 Parameters
89 ----------
112 ----------
90 file_or_name : filename or open filehandle (writable)
113 file_or_name : filename or open filehandle (writable)
91 File that will be duplicated
114 File that will be duplicated
92
115
93 mode : optional, valid mode for open().
116 mode : optional, valid mode for open().
94 If a filename was give, open with this mode.
117 If a filename was give, open with this mode.
95
118
96 channel : str, one of ['stdout', 'stderr']
119 channel : str, one of ['stdout', 'stderr']
97 """
120 """
98 if channel not in ['stdout', 'stderr']:
121 if channel not in ['stdout', 'stderr']:
99 raise ValueError('Invalid channel spec %s' % channel)
122 raise ValueError('Invalid channel spec %s' % channel)
100
123
101 if hasattr(file, 'write') and hasattr(file, 'seek'):
124 if hasattr(file, 'write') and hasattr(file, 'seek'):
102 self.file = file_or_name
125 self.file = file_or_name
103 else:
126 else:
104 self.file = open(file_or_name, mode)
127 self.file = open(file_or_name, mode)
105 self.channel = channel
128 self.channel = channel
106 self.ostream = getattr(sys, channel)
129 self.ostream = getattr(sys, channel)
107 setattr(sys, channel, self)
130 setattr(sys, channel, self)
108 self._closed = False
131 self._closed = False
109
132
110 def close(self):
133 def close(self):
111 """Close the file and restore the channel."""
134 """Close the file and restore the channel."""
112 self.flush()
135 self.flush()
113 setattr(sys, self.channel, self.ostream)
136 setattr(sys, self.channel, self.ostream)
114 self.file.close()
137 self.file.close()
115 self._closed = True
138 self._closed = True
116
139
117 def write(self, data):
140 def write(self, data):
118 """Write data to both channels."""
141 """Write data to both channels."""
119 self.file.write(data)
142 self.file.write(data)
120 self.ostream.write(data)
143 self.ostream.write(data)
121 self.ostream.flush()
144 self.ostream.flush()
122
145
123 def flush(self):
146 def flush(self):
124 """Flush both channels."""
147 """Flush both channels."""
125 self.file.flush()
148 self.file.flush()
126 self.ostream.flush()
149 self.ostream.flush()
127
150
128 def __del__(self):
151 def __del__(self):
129 if not self._closed:
152 if not self._closed:
130 self.close()
153 self.close()
131
154
132
155
133 def file_read(filename):
156 def file_read(filename):
134 """Read a file and close it. Returns the file source."""
157 """Read a file and close it. Returns the file source."""
135 fobj = open(filename,'r');
158 fobj = open(filename,'r');
136 source = fobj.read();
159 source = fobj.read();
137 fobj.close()
160 fobj.close()
138 return source
161 return source
139
162
140
163
141 def file_readlines(filename):
164 def file_readlines(filename):
142 """Read a file and close it. Returns the file source using readlines()."""
165 """Read a file and close it. Returns the file source using readlines()."""
143 fobj = open(filename,'r');
166 fobj = open(filename,'r');
144 lines = fobj.readlines();
167 lines = fobj.readlines();
145 fobj.close()
168 fobj.close()
146 return lines
169 return lines
147
170
148
171
149 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
172 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
150 """Take multiple lines of input.
173 """Take multiple lines of input.
151
174
152 A list with each line of input as a separate element is returned when a
175 A list with each line of input as a separate element is returned when a
153 termination string is entered (defaults to a single '.'). Input can also
176 termination string is entered (defaults to a single '.'). Input can also
154 terminate via EOF (^D in Unix, ^Z-RET in Windows).
177 terminate via EOF (^D in Unix, ^Z-RET in Windows).
155
178
156 Lines of input which end in \\ are joined into single entries (and a
179 Lines of input which end in \\ are joined into single entries (and a
157 secondary continuation prompt is issued as long as the user terminates
180 secondary continuation prompt is issued as long as the user terminates
158 lines with \\). This allows entering very long strings which are still
181 lines with \\). This allows entering very long strings which are still
159 meant to be treated as single entities.
182 meant to be treated as single entities.
160 """
183 """
161
184
162 try:
185 try:
163 if header:
186 if header:
164 header += '\n'
187 header += '\n'
165 lines = [raw_input(header + ps1)]
188 lines = [raw_input(header + ps1)]
166 except EOFError:
189 except EOFError:
167 return []
190 return []
168 terminate = [terminate_str]
191 terminate = [terminate_str]
169 try:
192 try:
170 while lines[-1:] != terminate:
193 while lines[-1:] != terminate:
171 new_line = raw_input(ps1)
194 new_line = raw_input(ps1)
172 while new_line.endswith('\\'):
195 while new_line.endswith('\\'):
173 new_line = new_line[:-1] + raw_input(ps2)
196 new_line = new_line[:-1] + raw_input(ps2)
174 lines.append(new_line)
197 lines.append(new_line)
175
198
176 return lines[:-1] # don't return the termination command
199 return lines[:-1] # don't return the termination command
177 except EOFError:
200 except EOFError:
178 print
201 print
179 return lines
202 return lines
180
203
181
204
182 def raw_input_ext(prompt='', ps2='... '):
205 def raw_input_ext(prompt='', ps2='... '):
183 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
206 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
184
207
185 line = raw_input(prompt)
208 line = raw_input(prompt)
186 while line.endswith('\\'):
209 while line.endswith('\\'):
187 line = line[:-1] + raw_input(ps2)
210 line = line[:-1] + raw_input(ps2)
188 return line
211 return line
189
212
190
213
191 def ask_yes_no(prompt,default=None):
214 def ask_yes_no(prompt,default=None):
192 """Asks a question and returns a boolean (y/n) answer.
215 """Asks a question and returns a boolean (y/n) answer.
193
216
194 If default is given (one of 'y','n'), it is used if the user input is
217 If default is given (one of 'y','n'), it is used if the user input is
195 empty. Otherwise the question is repeated until an answer is given.
218 empty. Otherwise the question is repeated until an answer is given.
196
219
197 An EOF is treated as the default answer. If there is no default, an
220 An EOF is treated as the default answer. If there is no default, an
198 exception is raised to prevent infinite loops.
221 exception is raised to prevent infinite loops.
199
222
200 Valid answers are: y/yes/n/no (match is not case sensitive)."""
223 Valid answers are: y/yes/n/no (match is not case sensitive)."""
201
224
202 answers = {'y':True,'n':False,'yes':True,'no':False}
225 answers = {'y':True,'n':False,'yes':True,'no':False}
203 ans = None
226 ans = None
204 while ans not in answers.keys():
227 while ans not in answers.keys():
205 try:
228 try:
206 ans = raw_input(prompt+' ').lower()
229 ans = raw_input(prompt+' ').lower()
207 if not ans: # response was an empty string
230 if not ans: # response was an empty string
208 ans = default
231 ans = default
209 except KeyboardInterrupt:
232 except KeyboardInterrupt:
210 pass
233 pass
211 except EOFError:
234 except EOFError:
212 if default in answers.keys():
235 if default in answers.keys():
213 ans = default
236 ans = default
214 print
237 print
215 else:
238 else:
216 raise
239 raise
217
240
218 return answers[ans]
241 return answers[ans]
219
242
220
243
221 class NLprinter:
244 class NLprinter:
222 """Print an arbitrarily nested list, indicating index numbers.
245 """Print an arbitrarily nested list, indicating index numbers.
223
246
224 An instance of this class called nlprint is available and callable as a
247 An instance of this class called nlprint is available and callable as a
225 function.
248 function.
226
249
227 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
250 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
228 and using 'sep' to separate the index from the value. """
251 and using 'sep' to separate the index from the value. """
229
252
230 def __init__(self):
253 def __init__(self):
231 self.depth = 0
254 self.depth = 0
232
255
233 def __call__(self,lst,pos='',**kw):
256 def __call__(self,lst,pos='',**kw):
234 """Prints the nested list numbering levels."""
257 """Prints the nested list numbering levels."""
235 kw.setdefault('indent',' ')
258 kw.setdefault('indent',' ')
236 kw.setdefault('sep',': ')
259 kw.setdefault('sep',': ')
237 kw.setdefault('start',0)
260 kw.setdefault('start',0)
238 kw.setdefault('stop',len(lst))
261 kw.setdefault('stop',len(lst))
239 # we need to remove start and stop from kw so they don't propagate
262 # we need to remove start and stop from kw so they don't propagate
240 # into a recursive call for a nested list.
263 # into a recursive call for a nested list.
241 start = kw['start']; del kw['start']
264 start = kw['start']; del kw['start']
242 stop = kw['stop']; del kw['stop']
265 stop = kw['stop']; del kw['stop']
243 if self.depth == 0 and 'header' in kw.keys():
266 if self.depth == 0 and 'header' in kw.keys():
244 print(kw['header'])
267 print(kw['header'])
245
268
246 for idx in range(start,stop):
269 for idx in range(start,stop):
247 elem = lst[idx]
270 elem = lst[idx]
248 if type(elem)==type([]):
271 if type(elem)==type([]):
249 self.depth += 1
272 self.depth += 1
250 self.__call__(elem,itpl('$pos$idx,'),**kw)
273 self.__call__(elem,itpl('$pos$idx,'),**kw)
251 self.depth -= 1
274 self.depth -= 1
252 else:
275 else:
253 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
276 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
254
277
255 nlprint = NLprinter()
278 nlprint = NLprinter()
256
279
257
280
258 def temp_pyfile(src, ext='.py'):
281 def temp_pyfile(src, ext='.py'):
259 """Make a temporary python file, return filename and filehandle.
282 """Make a temporary python file, return filename and filehandle.
260
283
261 Parameters
284 Parameters
262 ----------
285 ----------
263 src : string or list of strings (no need for ending newlines if list)
286 src : string or list of strings (no need for ending newlines if list)
264 Source code to be written to the file.
287 Source code to be written to the file.
265
288
266 ext : optional, string
289 ext : optional, string
267 Extension for the generated file.
290 Extension for the generated file.
268
291
269 Returns
292 Returns
270 -------
293 -------
271 (filename, open filehandle)
294 (filename, open filehandle)
272 It is the caller's responsibility to close the open file and unlink it.
295 It is the caller's responsibility to close the open file and unlink it.
273 """
296 """
274 fname = tempfile.mkstemp(ext)[1]
297 fname = tempfile.mkstemp(ext)[1]
275 f = open(fname,'w')
298 f = open(fname,'w')
276 f.write(src)
299 f.write(src)
277 f.flush()
300 f.flush()
278 return fname, f
301 return fname, f
279
302
280
303
281 def raw_print(*args, **kw):
304 def raw_print(*args, **kw):
282 """Raw print to sys.__stdout__, otherwise identical interface to print()."""
305 """Raw print to sys.__stdout__, otherwise identical interface to print()."""
283
306
284 print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
307 print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
285 file=sys.__stdout__)
308 file=sys.__stdout__)
286 sys.__stdout__.flush()
309 sys.__stdout__.flush()
287
310
288
311
289 def raw_print_err(*args, **kw):
312 def raw_print_err(*args, **kw):
290 """Raw print to sys.__stderr__, otherwise identical interface to print()."""
313 """Raw print to sys.__stderr__, otherwise identical interface to print()."""
291
314
292 print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
315 print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
293 file=sys.__stderr__)
316 file=sys.__stderr__)
294 sys.__stderr__.flush()
317 sys.__stderr__.flush()
295
318
296
319
297 # Short aliases for quick debugging, do NOT use these in production code.
320 # Short aliases for quick debugging, do NOT use these in production code.
298 rprint = raw_print
321 rprint = raw_print
299 rprinte = raw_print_err
322 rprinte = raw_print_err
@@ -1,61 +1,71 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Tests for io.py"""
2 """Tests for io.py"""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2008 The IPython Development Team
5 # Copyright (C) 2008 The IPython Development Team
6 #
6 #
7 # Distributed under the terms of the BSD License. The full license is in
7 # Distributed under the terms of the BSD License. The full license is in
8 # the file COPYING, distributed as part of this software.
8 # the file COPYING, distributed as part of this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 import sys
15 import sys
16
16
17 from cStringIO import StringIO
17 from cStringIO import StringIO
18 from subprocess import Popen, PIPE
18
19
19 import nose.tools as nt
20 import nose.tools as nt
20
21
21 from IPython.testing import decorators as dec
22 from IPython.testing import decorators as dec
22 from IPython.utils.io import Tee
23 from IPython.utils.io import Tee
23
24
24 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
25 # Tests
26 # Tests
26 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
27
28
28
29
29 def test_tee_simple():
30 def test_tee_simple():
30 "Very simple check with stdout only"
31 "Very simple check with stdout only"
31 chan = StringIO()
32 chan = StringIO()
32 text = 'Hello'
33 text = 'Hello'
33 tee = Tee(chan, channel='stdout')
34 tee = Tee(chan, channel='stdout')
34 print >> chan, text,
35 print >> chan, text,
35 nt.assert_equal(chan.getvalue(), text)
36 nt.assert_equal(chan.getvalue(), text)
36
37
37
38
38 class TeeTestCase(dec.ParametricTestCase):
39 class TeeTestCase(dec.ParametricTestCase):
39
40
40 def tchan(self, channel, check='close'):
41 def tchan(self, channel, check='close'):
41 trap = StringIO()
42 trap = StringIO()
42 chan = StringIO()
43 chan = StringIO()
43 text = 'Hello'
44 text = 'Hello'
44
45
45 std_ori = getattr(sys, channel)
46 std_ori = getattr(sys, channel)
46 setattr(sys, channel, trap)
47 setattr(sys, channel, trap)
47
48
48 tee = Tee(chan, channel=channel)
49 tee = Tee(chan, channel=channel)
49 print >> chan, text,
50 print >> chan, text,
50 setattr(sys, channel, std_ori)
51 setattr(sys, channel, std_ori)
51 trap_val = trap.getvalue()
52 trap_val = trap.getvalue()
52 nt.assert_equals(chan.getvalue(), text)
53 nt.assert_equals(chan.getvalue(), text)
53 if check=='close':
54 if check=='close':
54 tee.close()
55 tee.close()
55 else:
56 else:
56 del tee
57 del tee
57
58
58 def test(self):
59 def test(self):
59 for chan in ['stdout', 'stderr']:
60 for chan in ['stdout', 'stderr']:
60 for check in ['close', 'del']:
61 for check in ['close', 'del']:
61 yield self.tchan(chan, check)
62 yield self.tchan(chan, check)
63
64 def test_io_init():
65 """Test that io.stdin/out/err exist at startup"""
66 for name in ('stdin', 'stdout', 'stderr'):
67 p = Popen([sys.executable, '-c', "from IPython.utils import io;print io.%s.__class__"%name],
68 stdout=PIPE)
69 p.wait()
70 classname = p.stdout.read().strip()
71 nt.assert_equals(classname, 'IPython.utils.io.IOStream')
@@ -1,66 +1,66 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Utilities for warnings. Shoudn't we just use the built in warnings module.
3 Utilities for warnings. Shoudn't we just use the built in warnings module.
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 #
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 import sys
17 import sys
18
18
19 import IPython.utils.io
19 from IPython.utils import io
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Code
22 # Code
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 def warn(msg,level=2,exit_val=1):
25 def warn(msg,level=2,exit_val=1):
26 """Standard warning printer. Gives formatting consistency.
26 """Standard warning printer. Gives formatting consistency.
27
27
28 Output is sent to IPython.utils.io.Term.cerr (sys.stderr by default).
28 Output is sent to io.stderr (sys.stderr by default).
29
29
30 Options:
30 Options:
31
31
32 -level(2): allows finer control:
32 -level(2): allows finer control:
33 0 -> Do nothing, dummy function.
33 0 -> Do nothing, dummy function.
34 1 -> Print message.
34 1 -> Print message.
35 2 -> Print 'WARNING:' + message. (Default level).
35 2 -> Print 'WARNING:' + message. (Default level).
36 3 -> Print 'ERROR:' + message.
36 3 -> Print 'ERROR:' + message.
37 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
37 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
38
38
39 -exit_val (1): exit value returned by sys.exit() for a level 4
39 -exit_val (1): exit value returned by sys.exit() for a level 4
40 warning. Ignored for all other levels."""
40 warning. Ignored for all other levels."""
41
41
42 if level>0:
42 if level>0:
43 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
43 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
44 print >> IPython.utils.io.Term.cerr, '%s%s' % (header[level],msg)
44 print >> io.stderr, '%s%s' % (header[level],msg)
45 if level == 4:
45 if level == 4:
46 print >> IPython.utils.io.Term.cerr,'Exiting.\n'
46 print >> io.stderr,'Exiting.\n'
47 sys.exit(exit_val)
47 sys.exit(exit_val)
48
48
49
49
50 def info(msg):
50 def info(msg):
51 """Equivalent to warn(msg,level=1)."""
51 """Equivalent to warn(msg,level=1)."""
52
52
53 warn(msg,level=1)
53 warn(msg,level=1)
54
54
55
55
56 def error(msg):
56 def error(msg):
57 """Equivalent to warn(msg,level=3)."""
57 """Equivalent to warn(msg,level=3)."""
58
58
59 warn(msg,level=3)
59 warn(msg,level=3)
60
60
61
61
62 def fatal(msg,exit_val=1):
62 def fatal(msg,exit_val=1):
63 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
63 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
64
64
65 warn(msg,exit_val=exit_val,level=4)
65 warn(msg,exit_val=exit_val,level=4)
66
66
General Comments 0
You need to be logged in to leave comments. Login now