##// END OF EJS Templates
Find .py files for verbose tracebacks, rather than trying to tokenize .pyc files.
Thomas Kluyver -
Show More
@@ -0,0 +1,23 b''
1 """Utilities for working with Python source files.
2
3 Exposes various functions from recent Python standard libraries, along with
4 equivalents for older Python versions.
5 """
6 import os.path
7
8 try: # Python 3.2
9 from imp import source_from_cache, cache_from_source
10 except ImportError:
11 # Python <= 3.1: .pyc files go next to .py
12 def source_from_cache(path):
13 basename, ext = os.path.splitext(path)
14 if ext not in {'.pyc', '.pyo'}:
15 raise ValueError('Not a cached Python file extension', ext)
16 # Should we look for .pyw files?
17 return basename + '.py'
18
19 def cache_from_source(path, debug_override=None):
20 if debug_override is None:
21 debug_override = __debug__
22 basename, ext = os.path.splitext(path)
23 return basename + '.pyc' if debug_override else '.pyo'
@@ -1,1254 +1,1257 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 try: # Python 2
86 try: # Python 2
87 generate_tokens = tokenize.generate_tokens
87 generate_tokens = tokenize.generate_tokens
88 except AttributeError: # Python 3
88 except AttributeError: # Python 3
89 generate_tokens = tokenize.tokenize
89 generate_tokens = tokenize.tokenize
90
90
91 # For purposes of monkeypatching inspect to fix a bug in it.
91 # For purposes of monkeypatching inspect to fix a bug in it.
92 from inspect import getsourcefile, getfile, getmodule,\
92 from inspect import getsourcefile, getfile, getmodule,\
93 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
93 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
94
94
95 # IPython's own modules
95 # IPython's own modules
96 # Modified pdb which doesn't damage IPython's readline handling
96 # Modified pdb which doesn't damage IPython's readline handling
97 from IPython.core import debugger, ipapi
97 from IPython.core import debugger, ipapi
98 from IPython.core.display_trap import DisplayTrap
98 from IPython.core.display_trap import DisplayTrap
99 from IPython.core.excolors import exception_colors
99 from IPython.core.excolors import exception_colors
100 from IPython.utils import PyColorize
100 from IPython.utils import PyColorize
101 from IPython.utils import io
101 from IPython.utils import io
102 from IPython.utils import py3compat
102 from IPython.utils import py3compat
103 from IPython.utils import pyfile
103 from IPython.utils.data import uniq_stable
104 from IPython.utils.data import uniq_stable
104 from IPython.utils.warn import info, error
105 from IPython.utils.warn import info, error
105
106
106 # Globals
107 # Globals
107 # amount of space to put line numbers before verbose tracebacks
108 # amount of space to put line numbers before verbose tracebacks
108 INDENT_SIZE = 8
109 INDENT_SIZE = 8
109
110
110 # Default color scheme. This is used, for example, by the traceback
111 # Default color scheme. This is used, for example, by the traceback
111 # formatter. When running in an actual IPython instance, the user's rc.colors
112 # formatter. When running in an actual IPython instance, the user's rc.colors
112 # value is used, but havinga module global makes this functionality available
113 # value is used, but havinga module global makes this functionality available
113 # to users of ultratb who are NOT running inside ipython.
114 # to users of ultratb who are NOT running inside ipython.
114 DEFAULT_SCHEME = 'NoColor'
115 DEFAULT_SCHEME = 'NoColor'
115
116
116 #---------------------------------------------------------------------------
117 #---------------------------------------------------------------------------
117 # Code begins
118 # Code begins
118
119
119 # Utility functions
120 # Utility functions
120 def inspect_error():
121 def inspect_error():
121 """Print a message about internal inspect errors.
122 """Print a message about internal inspect errors.
122
123
123 These are unfortunately quite common."""
124 These are unfortunately quite common."""
124
125
125 error('Internal Python error in the inspect module.\n'
126 error('Internal Python error in the inspect module.\n'
126 'Below is the traceback from this internal error.\n')
127 'Below is the traceback from this internal error.\n')
127
128
128
129
129 # N.B. This function is a monkeypatch we are currently not applying.
130 # N.B. This function is a monkeypatch we are currently not applying.
130 # It was written some time ago, to fix an apparent Python bug with
131 # It was written some time ago, to fix an apparent Python bug with
131 # codeobj.co_firstlineno . Unfortunately, we don't know under what conditions
132 # codeobj.co_firstlineno . Unfortunately, we don't know under what conditions
132 # the bug occurred, so we can't tell if it has been fixed. If it reappears, we
133 # the bug occurred, so we can't tell if it has been fixed. If it reappears, we
133 # will apply the monkeypatch again. Also, note that findsource() is not called
134 # will apply the monkeypatch again. Also, note that findsource() is not called
134 # by our code at this time - we don't know if it was when the monkeypatch was
135 # by our code at this time - we don't know if it was when the monkeypatch was
135 # written, or if the monkeypatch is needed for some other code (like a debugger).
136 # written, or if the monkeypatch is needed for some other code (like a debugger).
136 # For the discussion about not applying it, see gh-1229. TK, Jan 2011.
137 # For the discussion about not applying it, see gh-1229. TK, Jan 2011.
137 def findsource(object):
138 def findsource(object):
138 """Return the entire source file and starting line number for an object.
139 """Return the entire source file and starting line number for an object.
139
140
140 The argument may be a module, class, method, function, traceback, frame,
141 The argument may be a module, class, method, function, traceback, frame,
141 or code object. The source code is returned as a list of all the lines
142 or code object. The source code is returned as a list of all the lines
142 in the file and the line number indexes a line in that list. An IOError
143 in the file and the line number indexes a line in that list. An IOError
143 is raised if the source code cannot be retrieved.
144 is raised if the source code cannot be retrieved.
144
145
145 FIXED version with which we monkeypatch the stdlib to work around a bug."""
146 FIXED version with which we monkeypatch the stdlib to work around a bug."""
146
147
147 file = getsourcefile(object) or getfile(object)
148 file = getsourcefile(object) or getfile(object)
148 # If the object is a frame, then trying to get the globals dict from its
149 # If the object is a frame, then trying to get the globals dict from its
149 # module won't work. Instead, the frame object itself has the globals
150 # module won't work. Instead, the frame object itself has the globals
150 # dictionary.
151 # dictionary.
151 globals_dict = None
152 globals_dict = None
152 if inspect.isframe(object):
153 if inspect.isframe(object):
153 # XXX: can this ever be false?
154 # XXX: can this ever be false?
154 globals_dict = object.f_globals
155 globals_dict = object.f_globals
155 else:
156 else:
156 module = getmodule(object, file)
157 module = getmodule(object, file)
157 if module:
158 if module:
158 globals_dict = module.__dict__
159 globals_dict = module.__dict__
159 lines = linecache.getlines(file, globals_dict)
160 lines = linecache.getlines(file, globals_dict)
160 if not lines:
161 if not lines:
161 raise IOError('could not get source code')
162 raise IOError('could not get source code')
162
163
163 if ismodule(object):
164 if ismodule(object):
164 return lines, 0
165 return lines, 0
165
166
166 if isclass(object):
167 if isclass(object):
167 name = object.__name__
168 name = object.__name__
168 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
169 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
169 # make some effort to find the best matching class definition:
170 # make some effort to find the best matching class definition:
170 # use the one with the least indentation, which is the one
171 # use the one with the least indentation, which is the one
171 # that's most probably not inside a function definition.
172 # that's most probably not inside a function definition.
172 candidates = []
173 candidates = []
173 for i in range(len(lines)):
174 for i in range(len(lines)):
174 match = pat.match(lines[i])
175 match = pat.match(lines[i])
175 if match:
176 if match:
176 # if it's at toplevel, it's already the best one
177 # if it's at toplevel, it's already the best one
177 if lines[i][0] == 'c':
178 if lines[i][0] == 'c':
178 return lines, i
179 return lines, i
179 # else add whitespace to candidate list
180 # else add whitespace to candidate list
180 candidates.append((match.group(1), i))
181 candidates.append((match.group(1), i))
181 if candidates:
182 if candidates:
182 # this will sort by whitespace, and by line number,
183 # this will sort by whitespace, and by line number,
183 # less whitespace first
184 # less whitespace first
184 candidates.sort()
185 candidates.sort()
185 return lines, candidates[0][1]
186 return lines, candidates[0][1]
186 else:
187 else:
187 raise IOError('could not find class definition')
188 raise IOError('could not find class definition')
188
189
189 if ismethod(object):
190 if ismethod(object):
190 object = object.im_func
191 object = object.im_func
191 if isfunction(object):
192 if isfunction(object):
192 object = object.func_code
193 object = object.func_code
193 if istraceback(object):
194 if istraceback(object):
194 object = object.tb_frame
195 object = object.tb_frame
195 if isframe(object):
196 if isframe(object):
196 object = object.f_code
197 object = object.f_code
197 if iscode(object):
198 if iscode(object):
198 if not hasattr(object, 'co_firstlineno'):
199 if not hasattr(object, 'co_firstlineno'):
199 raise IOError('could not find function definition')
200 raise IOError('could not find function definition')
200 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
201 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
201 pmatch = pat.match
202 pmatch = pat.match
202 # fperez - fix: sometimes, co_firstlineno can give a number larger than
203 # fperez - fix: sometimes, co_firstlineno can give a number larger than
203 # the length of lines, which causes an error. Safeguard against that.
204 # the length of lines, which causes an error. Safeguard against that.
204 lnum = min(object.co_firstlineno,len(lines))-1
205 lnum = min(object.co_firstlineno,len(lines))-1
205 while lnum > 0:
206 while lnum > 0:
206 if pmatch(lines[lnum]): break
207 if pmatch(lines[lnum]): break
207 lnum -= 1
208 lnum -= 1
208
209
209 return lines, lnum
210 return lines, lnum
210 raise IOError('could not find code object')
211 raise IOError('could not find code object')
211
212
212 # Not applying the monkeypatch - see above the function for details. TK, Jan 2012
213 # Not applying the monkeypatch - see above the function for details. TK, Jan 2012
213 # Monkeypatch inspect to apply our bugfix. This code only works with py25
214 # Monkeypatch inspect to apply our bugfix. This code only works with py25
214 #if sys.version_info[:2] >= (2,5):
215 #if sys.version_info[:2] >= (2,5):
215 # inspect.findsource = findsource
216 # inspect.findsource = findsource
216
217
217 def fix_frame_records_filenames(records):
218 def fix_frame_records_filenames(records):
218 """Try to fix the filenames in each record from inspect.getinnerframes().
219 """Try to fix the filenames in each record from inspect.getinnerframes().
219
220
220 Particularly, modules loaded from within zip files have useless filenames
221 Particularly, modules loaded from within zip files have useless filenames
221 attached to their code object, and inspect.getinnerframes() just uses it.
222 attached to their code object, and inspect.getinnerframes() just uses it.
222 """
223 """
223 fixed_records = []
224 fixed_records = []
224 for frame, filename, line_no, func_name, lines, index in records:
225 for frame, filename, line_no, func_name, lines, index in records:
225 # Look inside the frame's globals dictionary for __file__, which should
226 # Look inside the frame's globals dictionary for __file__, which should
226 # be better.
227 # be better.
227 better_fn = frame.f_globals.get('__file__', None)
228 better_fn = frame.f_globals.get('__file__', None)
228 if isinstance(better_fn, str):
229 if isinstance(better_fn, str):
229 # Check the type just in case someone did something weird with
230 # Check the type just in case someone did something weird with
230 # __file__. It might also be None if the error occurred during
231 # __file__. It might also be None if the error occurred during
231 # import.
232 # import.
232 filename = better_fn
233 filename = better_fn
233 fixed_records.append((frame, filename, line_no, func_name, lines, index))
234 fixed_records.append((frame, filename, line_no, func_name, lines, index))
234 return fixed_records
235 return fixed_records
235
236
236
237
237 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
238 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
238 import linecache
239 import linecache
239 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
240 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
240
241
241 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
242 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
242
243
243 # If the error is at the console, don't build any context, since it would
244 # If the error is at the console, don't build any context, since it would
244 # otherwise produce 5 blank lines printed out (there is no file at the
245 # otherwise produce 5 blank lines printed out (there is no file at the
245 # console)
246 # console)
246 rec_check = records[tb_offset:]
247 rec_check = records[tb_offset:]
247 try:
248 try:
248 rname = rec_check[0][1]
249 rname = rec_check[0][1]
249 if rname == '<ipython console>' or rname.endswith('<string>'):
250 if rname == '<ipython console>' or rname.endswith('<string>'):
250 return rec_check
251 return rec_check
251 except IndexError:
252 except IndexError:
252 pass
253 pass
253
254
254 aux = traceback.extract_tb(etb)
255 aux = traceback.extract_tb(etb)
255 assert len(records) == len(aux)
256 assert len(records) == len(aux)
256 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
257 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
257 maybeStart = lnum-1 - context//2
258 maybeStart = lnum-1 - context//2
258 start = max(maybeStart, 0)
259 start = max(maybeStart, 0)
259 end = start + context
260 end = start + context
260 lines = linecache.getlines(file)[start:end]
261 lines = linecache.getlines(file)[start:end]
261 buf = list(records[i])
262 buf = list(records[i])
262 buf[LNUM_POS] = lnum
263 buf[LNUM_POS] = lnum
263 buf[INDEX_POS] = lnum - 1 - start
264 buf[INDEX_POS] = lnum - 1 - start
264 buf[LINES_POS] = lines
265 buf[LINES_POS] = lines
265 records[i] = tuple(buf)
266 records[i] = tuple(buf)
266 return records[tb_offset:]
267 return records[tb_offset:]
267
268
268 # Helper function -- largely belongs to VerboseTB, but we need the same
269 # Helper function -- largely belongs to VerboseTB, but we need the same
269 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
270 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
270 # can be recognized properly by ipython.el's py-traceback-line-re
271 # can be recognized properly by ipython.el's py-traceback-line-re
271 # (SyntaxErrors have to be treated specially because they have no traceback)
272 # (SyntaxErrors have to be treated specially because they have no traceback)
272
273
273 _parser = PyColorize.Parser()
274 _parser = PyColorize.Parser()
274
275
275 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
276 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
276 numbers_width = INDENT_SIZE - 1
277 numbers_width = INDENT_SIZE - 1
277 res = []
278 res = []
278 i = lnum - index
279 i = lnum - index
279
280
280 # This lets us get fully syntax-highlighted tracebacks.
281 # This lets us get fully syntax-highlighted tracebacks.
281 if scheme is None:
282 if scheme is None:
282 ipinst = ipapi.get()
283 ipinst = ipapi.get()
283 if ipinst is not None:
284 if ipinst is not None:
284 scheme = ipinst.colors
285 scheme = ipinst.colors
285 else:
286 else:
286 scheme = DEFAULT_SCHEME
287 scheme = DEFAULT_SCHEME
287
288
288 _line_format = _parser.format2
289 _line_format = _parser.format2
289
290
290 for line in lines:
291 for line in lines:
291 # FIXME: we need to ensure the source is a pure string at this point,
292 # FIXME: we need to ensure the source is a pure string at this point,
292 # else the coloring code makes a royal mess. This is in need of a
293 # else the coloring code makes a royal mess. This is in need of a
293 # serious refactoring, so that all of the ultratb and PyColorize code
294 # serious refactoring, so that all of the ultratb and PyColorize code
294 # is unicode-safe. So for now this is rather an ugly hack, but
295 # is unicode-safe. So for now this is rather an ugly hack, but
295 # necessary to at least have readable tracebacks. Improvements welcome!
296 # necessary to at least have readable tracebacks. Improvements welcome!
296 line = py3compat.cast_bytes_py2(line, 'utf-8')
297 line = py3compat.cast_bytes_py2(line, 'utf-8')
297
298
298 new_line, err = _line_format(line, 'str', scheme)
299 new_line, err = _line_format(line, 'str', scheme)
299 if not err: line = new_line
300 if not err: line = new_line
300
301
301 if i == lnum:
302 if i == lnum:
302 # This is the line with the error
303 # This is the line with the error
303 pad = numbers_width - len(str(i))
304 pad = numbers_width - len(str(i))
304 if pad >= 3:
305 if pad >= 3:
305 marker = '-'*(pad-3) + '-> '
306 marker = '-'*(pad-3) + '-> '
306 elif pad == 2:
307 elif pad == 2:
307 marker = '> '
308 marker = '> '
308 elif pad == 1:
309 elif pad == 1:
309 marker = '>'
310 marker = '>'
310 else:
311 else:
311 marker = ''
312 marker = ''
312 num = marker + str(i)
313 num = marker + str(i)
313 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
314 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
314 Colors.line, line, Colors.Normal)
315 Colors.line, line, Colors.Normal)
315 else:
316 else:
316 num = '%*s' % (numbers_width,i)
317 num = '%*s' % (numbers_width,i)
317 line = '%s%s%s %s' %(Colors.lineno, num,
318 line = '%s%s%s %s' %(Colors.lineno, num,
318 Colors.Normal, line)
319 Colors.Normal, line)
319
320
320 res.append(line)
321 res.append(line)
321 if lvals and i == lnum:
322 if lvals and i == lnum:
322 res.append(lvals + '\n')
323 res.append(lvals + '\n')
323 i = i + 1
324 i = i + 1
324 return res
325 return res
325
326
326
327
327 #---------------------------------------------------------------------------
328 #---------------------------------------------------------------------------
328 # Module classes
329 # Module classes
329 class TBTools(object):
330 class TBTools(object):
330 """Basic tools used by all traceback printer classes."""
331 """Basic tools used by all traceback printer classes."""
331
332
332 # Number of frames to skip when reporting tracebacks
333 # Number of frames to skip when reporting tracebacks
333 tb_offset = 0
334 tb_offset = 0
334
335
335 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None):
336 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None):
336 # Whether to call the interactive pdb debugger after printing
337 # Whether to call the interactive pdb debugger after printing
337 # tracebacks or not
338 # tracebacks or not
338 self.call_pdb = call_pdb
339 self.call_pdb = call_pdb
339
340
340 # Output stream to write to. Note that we store the original value in
341 # Output stream to write to. Note that we store the original value in
341 # a private attribute and then make the public ostream a property, so
342 # a private attribute and then make the public ostream a property, so
342 # that we can delay accessing io.stdout until runtime. The way
343 # that we can delay accessing io.stdout until runtime. The way
343 # things are written now, the io.stdout object is dynamically managed
344 # things are written now, the io.stdout object is dynamically managed
344 # so a reference to it should NEVER be stored statically. This
345 # so a reference to it should NEVER be stored statically. This
345 # property approach confines this detail to a single location, and all
346 # property approach confines this detail to a single location, and all
346 # subclasses can simply access self.ostream for writing.
347 # subclasses can simply access self.ostream for writing.
347 self._ostream = ostream
348 self._ostream = ostream
348
349
349 # Create color table
350 # Create color table
350 self.color_scheme_table = exception_colors()
351 self.color_scheme_table = exception_colors()
351
352
352 self.set_colors(color_scheme)
353 self.set_colors(color_scheme)
353 self.old_scheme = color_scheme # save initial value for toggles
354 self.old_scheme = color_scheme # save initial value for toggles
354
355
355 if call_pdb:
356 if call_pdb:
356 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
357 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
357 else:
358 else:
358 self.pdb = None
359 self.pdb = None
359
360
360 def _get_ostream(self):
361 def _get_ostream(self):
361 """Output stream that exceptions are written to.
362 """Output stream that exceptions are written to.
362
363
363 Valid values are:
364 Valid values are:
364
365
365 - None: the default, which means that IPython will dynamically resolve
366 - None: the default, which means that IPython will dynamically resolve
366 to io.stdout. This ensures compatibility with most tools, including
367 to io.stdout. This ensures compatibility with most tools, including
367 Windows (where plain stdout doesn't recognize ANSI escapes).
368 Windows (where plain stdout doesn't recognize ANSI escapes).
368
369
369 - Any object with 'write' and 'flush' attributes.
370 - Any object with 'write' and 'flush' attributes.
370 """
371 """
371 return io.stdout if self._ostream is None else self._ostream
372 return io.stdout if self._ostream is None else self._ostream
372
373
373 def _set_ostream(self, val):
374 def _set_ostream(self, val):
374 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
375 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
375 self._ostream = val
376 self._ostream = val
376
377
377 ostream = property(_get_ostream, _set_ostream)
378 ostream = property(_get_ostream, _set_ostream)
378
379
379 def set_colors(self,*args,**kw):
380 def set_colors(self,*args,**kw):
380 """Shorthand access to the color table scheme selector method."""
381 """Shorthand access to the color table scheme selector method."""
381
382
382 # Set own color table
383 # Set own color table
383 self.color_scheme_table.set_active_scheme(*args,**kw)
384 self.color_scheme_table.set_active_scheme(*args,**kw)
384 # for convenience, set Colors to the active scheme
385 # for convenience, set Colors to the active scheme
385 self.Colors = self.color_scheme_table.active_colors
386 self.Colors = self.color_scheme_table.active_colors
386 # Also set colors of debugger
387 # Also set colors of debugger
387 if hasattr(self,'pdb') and self.pdb is not None:
388 if hasattr(self,'pdb') and self.pdb is not None:
388 self.pdb.set_colors(*args,**kw)
389 self.pdb.set_colors(*args,**kw)
389
390
390 def color_toggle(self):
391 def color_toggle(self):
391 """Toggle between the currently active color scheme and NoColor."""
392 """Toggle between the currently active color scheme and NoColor."""
392
393
393 if self.color_scheme_table.active_scheme_name == 'NoColor':
394 if self.color_scheme_table.active_scheme_name == 'NoColor':
394 self.color_scheme_table.set_active_scheme(self.old_scheme)
395 self.color_scheme_table.set_active_scheme(self.old_scheme)
395 self.Colors = self.color_scheme_table.active_colors
396 self.Colors = self.color_scheme_table.active_colors
396 else:
397 else:
397 self.old_scheme = self.color_scheme_table.active_scheme_name
398 self.old_scheme = self.color_scheme_table.active_scheme_name
398 self.color_scheme_table.set_active_scheme('NoColor')
399 self.color_scheme_table.set_active_scheme('NoColor')
399 self.Colors = self.color_scheme_table.active_colors
400 self.Colors = self.color_scheme_table.active_colors
400
401
401 def stb2text(self, stb):
402 def stb2text(self, stb):
402 """Convert a structured traceback (a list) to a string."""
403 """Convert a structured traceback (a list) to a string."""
403 return '\n'.join(stb)
404 return '\n'.join(stb)
404
405
405 def text(self, etype, value, tb, tb_offset=None, context=5):
406 def text(self, etype, value, tb, tb_offset=None, context=5):
406 """Return formatted traceback.
407 """Return formatted traceback.
407
408
408 Subclasses may override this if they add extra arguments.
409 Subclasses may override this if they add extra arguments.
409 """
410 """
410 tb_list = self.structured_traceback(etype, value, tb,
411 tb_list = self.structured_traceback(etype, value, tb,
411 tb_offset, context)
412 tb_offset, context)
412 return self.stb2text(tb_list)
413 return self.stb2text(tb_list)
413
414
414 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
415 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
415 context=5, mode=None):
416 context=5, mode=None):
416 """Return a list of traceback frames.
417 """Return a list of traceback frames.
417
418
418 Must be implemented by each class.
419 Must be implemented by each class.
419 """
420 """
420 raise NotImplementedError()
421 raise NotImplementedError()
421
422
422
423
423 #---------------------------------------------------------------------------
424 #---------------------------------------------------------------------------
424 class ListTB(TBTools):
425 class ListTB(TBTools):
425 """Print traceback information from a traceback list, with optional color.
426 """Print traceback information from a traceback list, with optional color.
426
427
427 Calling: requires 3 arguments:
428 Calling: requires 3 arguments:
428 (etype, evalue, elist)
429 (etype, evalue, elist)
429 as would be obtained by:
430 as would be obtained by:
430 etype, evalue, tb = sys.exc_info()
431 etype, evalue, tb = sys.exc_info()
431 if tb:
432 if tb:
432 elist = traceback.extract_tb(tb)
433 elist = traceback.extract_tb(tb)
433 else:
434 else:
434 elist = None
435 elist = None
435
436
436 It can thus be used by programs which need to process the traceback before
437 It can thus be used by programs which need to process the traceback before
437 printing (such as console replacements based on the code module from the
438 printing (such as console replacements based on the code module from the
438 standard library).
439 standard library).
439
440
440 Because they are meant to be called without a full traceback (only a
441 Because they are meant to be called without a full traceback (only a
441 list), instances of this class can't call the interactive pdb debugger."""
442 list), instances of this class can't call the interactive pdb debugger."""
442
443
443 def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None):
444 def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None):
444 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
445 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
445 ostream=ostream)
446 ostream=ostream)
446
447
447 def __call__(self, etype, value, elist):
448 def __call__(self, etype, value, elist):
448 self.ostream.flush()
449 self.ostream.flush()
449 self.ostream.write(self.text(etype, value, elist))
450 self.ostream.write(self.text(etype, value, elist))
450 self.ostream.write('\n')
451 self.ostream.write('\n')
451
452
452 def structured_traceback(self, etype, value, elist, tb_offset=None,
453 def structured_traceback(self, etype, value, elist, tb_offset=None,
453 context=5):
454 context=5):
454 """Return a color formatted string with the traceback info.
455 """Return a color formatted string with the traceback info.
455
456
456 Parameters
457 Parameters
457 ----------
458 ----------
458 etype : exception type
459 etype : exception type
459 Type of the exception raised.
460 Type of the exception raised.
460
461
461 value : object
462 value : object
462 Data stored in the exception
463 Data stored in the exception
463
464
464 elist : list
465 elist : list
465 List of frames, see class docstring for details.
466 List of frames, see class docstring for details.
466
467
467 tb_offset : int, optional
468 tb_offset : int, optional
468 Number of frames in the traceback to skip. If not given, the
469 Number of frames in the traceback to skip. If not given, the
469 instance value is used (set in constructor).
470 instance value is used (set in constructor).
470
471
471 context : int, optional
472 context : int, optional
472 Number of lines of context information to print.
473 Number of lines of context information to print.
473
474
474 Returns
475 Returns
475 -------
476 -------
476 String with formatted exception.
477 String with formatted exception.
477 """
478 """
478 tb_offset = self.tb_offset if tb_offset is None else tb_offset
479 tb_offset = self.tb_offset if tb_offset is None else tb_offset
479 Colors = self.Colors
480 Colors = self.Colors
480 out_list = []
481 out_list = []
481 if elist:
482 if elist:
482
483
483 if tb_offset and len(elist) > tb_offset:
484 if tb_offset and len(elist) > tb_offset:
484 elist = elist[tb_offset:]
485 elist = elist[tb_offset:]
485
486
486 out_list.append('Traceback %s(most recent call last)%s:' %
487 out_list.append('Traceback %s(most recent call last)%s:' %
487 (Colors.normalEm, Colors.Normal) + '\n')
488 (Colors.normalEm, Colors.Normal) + '\n')
488 out_list.extend(self._format_list(elist))
489 out_list.extend(self._format_list(elist))
489 # The exception info should be a single entry in the list.
490 # The exception info should be a single entry in the list.
490 lines = ''.join(self._format_exception_only(etype, value))
491 lines = ''.join(self._format_exception_only(etype, value))
491 out_list.append(lines)
492 out_list.append(lines)
492
493
493 # Note: this code originally read:
494 # Note: this code originally read:
494
495
495 ## for line in lines[:-1]:
496 ## for line in lines[:-1]:
496 ## out_list.append(" "+line)
497 ## out_list.append(" "+line)
497 ## out_list.append(lines[-1])
498 ## out_list.append(lines[-1])
498
499
499 # This means it was indenting everything but the last line by a little
500 # This means it was indenting everything but the last line by a little
500 # bit. I've disabled this for now, but if we see ugliness somewhre we
501 # bit. I've disabled this for now, but if we see ugliness somewhre we
501 # can restore it.
502 # can restore it.
502
503
503 return out_list
504 return out_list
504
505
505 def _format_list(self, extracted_list):
506 def _format_list(self, extracted_list):
506 """Format a list of traceback entry tuples for printing.
507 """Format a list of traceback entry tuples for printing.
507
508
508 Given a list of tuples as returned by extract_tb() or
509 Given a list of tuples as returned by extract_tb() or
509 extract_stack(), return a list of strings ready for printing.
510 extract_stack(), return a list of strings ready for printing.
510 Each string in the resulting list corresponds to the item with the
511 Each string in the resulting list corresponds to the item with the
511 same index in the argument list. Each string ends in a newline;
512 same index in the argument list. Each string ends in a newline;
512 the strings may contain internal newlines as well, for those items
513 the strings may contain internal newlines as well, for those items
513 whose source text line is not None.
514 whose source text line is not None.
514
515
515 Lifted almost verbatim from traceback.py
516 Lifted almost verbatim from traceback.py
516 """
517 """
517
518
518 Colors = self.Colors
519 Colors = self.Colors
519 list = []
520 list = []
520 for filename, lineno, name, line in extracted_list[:-1]:
521 for filename, lineno, name, line in extracted_list[:-1]:
521 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
522 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
522 (Colors.filename, filename, Colors.Normal,
523 (Colors.filename, filename, Colors.Normal,
523 Colors.lineno, lineno, Colors.Normal,
524 Colors.lineno, lineno, Colors.Normal,
524 Colors.name, name, Colors.Normal)
525 Colors.name, name, Colors.Normal)
525 if line:
526 if line:
526 item += ' %s\n' % line.strip()
527 item += ' %s\n' % line.strip()
527 list.append(item)
528 list.append(item)
528 # Emphasize the last entry
529 # Emphasize the last entry
529 filename, lineno, name, line = extracted_list[-1]
530 filename, lineno, name, line = extracted_list[-1]
530 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
531 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
531 (Colors.normalEm,
532 (Colors.normalEm,
532 Colors.filenameEm, filename, Colors.normalEm,
533 Colors.filenameEm, filename, Colors.normalEm,
533 Colors.linenoEm, lineno, Colors.normalEm,
534 Colors.linenoEm, lineno, Colors.normalEm,
534 Colors.nameEm, name, Colors.normalEm,
535 Colors.nameEm, name, Colors.normalEm,
535 Colors.Normal)
536 Colors.Normal)
536 if line:
537 if line:
537 item += '%s %s%s\n' % (Colors.line, line.strip(),
538 item += '%s %s%s\n' % (Colors.line, line.strip(),
538 Colors.Normal)
539 Colors.Normal)
539 list.append(item)
540 list.append(item)
540 #from pprint import pformat; print 'LISTTB', pformat(list) # dbg
541 #from pprint import pformat; print 'LISTTB', pformat(list) # dbg
541 return list
542 return list
542
543
543 def _format_exception_only(self, etype, value):
544 def _format_exception_only(self, etype, value):
544 """Format the exception part of a traceback.
545 """Format the exception part of a traceback.
545
546
546 The arguments are the exception type and value such as given by
547 The arguments are the exception type and value such as given by
547 sys.exc_info()[:2]. The return value is a list of strings, each ending
548 sys.exc_info()[:2]. The return value is a list of strings, each ending
548 in a newline. Normally, the list contains a single string; however,
549 in a newline. Normally, the list contains a single string; however,
549 for SyntaxError exceptions, it contains several lines that (when
550 for SyntaxError exceptions, it contains several lines that (when
550 printed) display detailed information about where the syntax error
551 printed) display detailed information about where the syntax error
551 occurred. The message indicating which exception occurred is the
552 occurred. The message indicating which exception occurred is the
552 always last string in the list.
553 always last string in the list.
553
554
554 Also lifted nearly verbatim from traceback.py
555 Also lifted nearly verbatim from traceback.py
555 """
556 """
556
557
557 have_filedata = False
558 have_filedata = False
558 Colors = self.Colors
559 Colors = self.Colors
559 list = []
560 list = []
560 stype = Colors.excName + etype.__name__ + Colors.Normal
561 stype = Colors.excName + etype.__name__ + Colors.Normal
561 if value is None:
562 if value is None:
562 # Not sure if this can still happen in Python 2.6 and above
563 # Not sure if this can still happen in Python 2.6 and above
563 list.append( str(stype) + '\n')
564 list.append( str(stype) + '\n')
564 else:
565 else:
565 if etype is SyntaxError:
566 if etype is SyntaxError:
566 have_filedata = True
567 have_filedata = True
567 #print 'filename is',filename # dbg
568 #print 'filename is',filename # dbg
568 if not value.filename: value.filename = "<string>"
569 if not value.filename: value.filename = "<string>"
569 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
570 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
570 (Colors.normalEm,
571 (Colors.normalEm,
571 Colors.filenameEm, value.filename, Colors.normalEm,
572 Colors.filenameEm, value.filename, Colors.normalEm,
572 Colors.linenoEm, value.lineno, Colors.Normal ))
573 Colors.linenoEm, value.lineno, Colors.Normal ))
573 if value.text is not None:
574 if value.text is not None:
574 i = 0
575 i = 0
575 while i < len(value.text) and value.text[i].isspace():
576 while i < len(value.text) and value.text[i].isspace():
576 i += 1
577 i += 1
577 list.append('%s %s%s\n' % (Colors.line,
578 list.append('%s %s%s\n' % (Colors.line,
578 value.text.strip(),
579 value.text.strip(),
579 Colors.Normal))
580 Colors.Normal))
580 if value.offset is not None:
581 if value.offset is not None:
581 s = ' '
582 s = ' '
582 for c in value.text[i:value.offset-1]:
583 for c in value.text[i:value.offset-1]:
583 if c.isspace():
584 if c.isspace():
584 s += c
585 s += c
585 else:
586 else:
586 s += ' '
587 s += ' '
587 list.append('%s%s^%s\n' % (Colors.caret, s,
588 list.append('%s%s^%s\n' % (Colors.caret, s,
588 Colors.Normal) )
589 Colors.Normal) )
589
590
590 try:
591 try:
591 s = value.msg
592 s = value.msg
592 except Exception:
593 except Exception:
593 s = self._some_str(value)
594 s = self._some_str(value)
594 if s:
595 if s:
595 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
596 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
596 Colors.Normal, s))
597 Colors.Normal, s))
597 else:
598 else:
598 list.append('%s\n' % str(stype))
599 list.append('%s\n' % str(stype))
599
600
600 # sync with user hooks
601 # sync with user hooks
601 if have_filedata:
602 if have_filedata:
602 ipinst = ipapi.get()
603 ipinst = ipapi.get()
603 if ipinst is not None:
604 if ipinst is not None:
604 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
605 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
605
606
606 return list
607 return list
607
608
608 def get_exception_only(self, etype, value):
609 def get_exception_only(self, etype, value):
609 """Only print the exception type and message, without a traceback.
610 """Only print the exception type and message, without a traceback.
610
611
611 Parameters
612 Parameters
612 ----------
613 ----------
613 etype : exception type
614 etype : exception type
614 value : exception value
615 value : exception value
615 """
616 """
616 return ListTB.structured_traceback(self, etype, value, [])
617 return ListTB.structured_traceback(self, etype, value, [])
617
618
618
619
619 def show_exception_only(self, etype, evalue):
620 def show_exception_only(self, etype, evalue):
620 """Only print the exception type and message, without a traceback.
621 """Only print the exception type and message, without a traceback.
621
622
622 Parameters
623 Parameters
623 ----------
624 ----------
624 etype : exception type
625 etype : exception type
625 value : exception value
626 value : exception value
626 """
627 """
627 # This method needs to use __call__ from *this* class, not the one from
628 # This method needs to use __call__ from *this* class, not the one from
628 # a subclass whose signature or behavior may be different
629 # a subclass whose signature or behavior may be different
629 ostream = self.ostream
630 ostream = self.ostream
630 ostream.flush()
631 ostream.flush()
631 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
632 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
632 ostream.flush()
633 ostream.flush()
633
634
634 def _some_str(self, value):
635 def _some_str(self, value):
635 # Lifted from traceback.py
636 # Lifted from traceback.py
636 try:
637 try:
637 return str(value)
638 return str(value)
638 except:
639 except:
639 return '<unprintable %s object>' % type(value).__name__
640 return '<unprintable %s object>' % type(value).__name__
640
641
641 #----------------------------------------------------------------------------
642 #----------------------------------------------------------------------------
642 class VerboseTB(TBTools):
643 class VerboseTB(TBTools):
643 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
644 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
644 of HTML. Requires inspect and pydoc. Crazy, man.
645 of HTML. Requires inspect and pydoc. Crazy, man.
645
646
646 Modified version which optionally strips the topmost entries from the
647 Modified version which optionally strips the topmost entries from the
647 traceback, to be used with alternate interpreters (because their own code
648 traceback, to be used with alternate interpreters (because their own code
648 would appear in the traceback)."""
649 would appear in the traceback)."""
649
650
650 def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None,
651 def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None,
651 tb_offset=0, long_header=False, include_vars=True,
652 tb_offset=0, long_header=False, include_vars=True,
652 check_cache=None):
653 check_cache=None):
653 """Specify traceback offset, headers and color scheme.
654 """Specify traceback offset, headers and color scheme.
654
655
655 Define how many frames to drop from the tracebacks. Calling it with
656 Define how many frames to drop from the tracebacks. Calling it with
656 tb_offset=1 allows use of this handler in interpreters which will have
657 tb_offset=1 allows use of this handler in interpreters which will have
657 their own code at the top of the traceback (VerboseTB will first
658 their own code at the top of the traceback (VerboseTB will first
658 remove that frame before printing the traceback info)."""
659 remove that frame before printing the traceback info)."""
659 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
660 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
660 ostream=ostream)
661 ostream=ostream)
661 self.tb_offset = tb_offset
662 self.tb_offset = tb_offset
662 self.long_header = long_header
663 self.long_header = long_header
663 self.include_vars = include_vars
664 self.include_vars = include_vars
664 # By default we use linecache.checkcache, but the user can provide a
665 # By default we use linecache.checkcache, but the user can provide a
665 # different check_cache implementation. This is used by the IPython
666 # different check_cache implementation. This is used by the IPython
666 # kernel to provide tracebacks for interactive code that is cached,
667 # kernel to provide tracebacks for interactive code that is cached,
667 # by a compiler instance that flushes the linecache but preserves its
668 # by a compiler instance that flushes the linecache but preserves its
668 # own code cache.
669 # own code cache.
669 if check_cache is None:
670 if check_cache is None:
670 check_cache = linecache.checkcache
671 check_cache = linecache.checkcache
671 self.check_cache = check_cache
672 self.check_cache = check_cache
672
673
673 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
674 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
674 context=5):
675 context=5):
675 """Return a nice text document describing the traceback."""
676 """Return a nice text document describing the traceback."""
676
677
677 tb_offset = self.tb_offset if tb_offset is None else tb_offset
678 tb_offset = self.tb_offset if tb_offset is None else tb_offset
678
679
679 # some locals
680 # some locals
680 try:
681 try:
681 etype = etype.__name__
682 etype = etype.__name__
682 except AttributeError:
683 except AttributeError:
683 pass
684 pass
684 Colors = self.Colors # just a shorthand + quicker name lookup
685 Colors = self.Colors # just a shorthand + quicker name lookup
685 ColorsNormal = Colors.Normal # used a lot
686 ColorsNormal = Colors.Normal # used a lot
686 col_scheme = self.color_scheme_table.active_scheme_name
687 col_scheme = self.color_scheme_table.active_scheme_name
687 indent = ' '*INDENT_SIZE
688 indent = ' '*INDENT_SIZE
688 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
689 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
689 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
690 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
690 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
691 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
691
692
692 # some internal-use functions
693 # some internal-use functions
693 def text_repr(value):
694 def text_repr(value):
694 """Hopefully pretty robust repr equivalent."""
695 """Hopefully pretty robust repr equivalent."""
695 # this is pretty horrible but should always return *something*
696 # this is pretty horrible but should always return *something*
696 try:
697 try:
697 return pydoc.text.repr(value)
698 return pydoc.text.repr(value)
698 except KeyboardInterrupt:
699 except KeyboardInterrupt:
699 raise
700 raise
700 except:
701 except:
701 try:
702 try:
702 return repr(value)
703 return repr(value)
703 except KeyboardInterrupt:
704 except KeyboardInterrupt:
704 raise
705 raise
705 except:
706 except:
706 try:
707 try:
707 # all still in an except block so we catch
708 # all still in an except block so we catch
708 # getattr raising
709 # getattr raising
709 name = getattr(value, '__name__', None)
710 name = getattr(value, '__name__', None)
710 if name:
711 if name:
711 # ick, recursion
712 # ick, recursion
712 return text_repr(name)
713 return text_repr(name)
713 klass = getattr(value, '__class__', None)
714 klass = getattr(value, '__class__', None)
714 if klass:
715 if klass:
715 return '%s instance' % text_repr(klass)
716 return '%s instance' % text_repr(klass)
716 except KeyboardInterrupt:
717 except KeyboardInterrupt:
717 raise
718 raise
718 except:
719 except:
719 return 'UNRECOVERABLE REPR FAILURE'
720 return 'UNRECOVERABLE REPR FAILURE'
720 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
721 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
721 def nullrepr(value, repr=text_repr): return ''
722 def nullrepr(value, repr=text_repr): return ''
722
723
723 # meat of the code begins
724 # meat of the code begins
724 try:
725 try:
725 etype = etype.__name__
726 etype = etype.__name__
726 except AttributeError:
727 except AttributeError:
727 pass
728 pass
728
729
729 if self.long_header:
730 if self.long_header:
730 # Header with the exception type, python version, and date
731 # Header with the exception type, python version, and date
731 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
732 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
732 date = time.ctime(time.time())
733 date = time.ctime(time.time())
733
734
734 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
735 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
735 exc, ' '*(75-len(str(etype))-len(pyver)),
736 exc, ' '*(75-len(str(etype))-len(pyver)),
736 pyver, date.rjust(75) )
737 pyver, date.rjust(75) )
737 head += "\nA problem occured executing Python code. Here is the sequence of function"\
738 head += "\nA problem occured executing Python code. Here is the sequence of function"\
738 "\ncalls leading up to the error, with the most recent (innermost) call last."
739 "\ncalls leading up to the error, with the most recent (innermost) call last."
739 else:
740 else:
740 # Simplified header
741 # Simplified header
741 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
742 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
742 'Traceback (most recent call last)'.\
743 'Traceback (most recent call last)'.\
743 rjust(75 - len(str(etype)) ) )
744 rjust(75 - len(str(etype)) ) )
744 frames = []
745 frames = []
745 # Flush cache before calling inspect. This helps alleviate some of the
746 # Flush cache before calling inspect. This helps alleviate some of the
746 # problems with python 2.3's inspect.py.
747 # problems with python 2.3's inspect.py.
747 ##self.check_cache()
748 ##self.check_cache()
748 # Drop topmost frames if requested
749 # Drop topmost frames if requested
749 try:
750 try:
750 # Try the default getinnerframes and Alex's: Alex's fixes some
751 # Try the default getinnerframes and Alex's: Alex's fixes some
751 # problems, but it generates empty tracebacks for console errors
752 # problems, but it generates empty tracebacks for console errors
752 # (5 blanks lines) where none should be returned.
753 # (5 blanks lines) where none should be returned.
753 #records = inspect.getinnerframes(etb, context)[tb_offset:]
754 #records = inspect.getinnerframes(etb, context)[tb_offset:]
754 #print 'python records:', records # dbg
755 #print 'python records:', records # dbg
755 records = _fixed_getinnerframes(etb, context, tb_offset)
756 records = _fixed_getinnerframes(etb, context, tb_offset)
756 #print 'alex records:', records # dbg
757 #print 'alex records:', records # dbg
757 except:
758 except:
758
759
759 # FIXME: I've been getting many crash reports from python 2.3
760 # FIXME: I've been getting many crash reports from python 2.3
760 # users, traceable to inspect.py. If I can find a small test-case
761 # users, traceable to inspect.py. If I can find a small test-case
761 # to reproduce this, I should either write a better workaround or
762 # to reproduce this, I should either write a better workaround or
762 # file a bug report against inspect (if that's the real problem).
763 # file a bug report against inspect (if that's the real problem).
763 # So far, I haven't been able to find an isolated example to
764 # So far, I haven't been able to find an isolated example to
764 # reproduce the problem.
765 # reproduce the problem.
765 inspect_error()
766 inspect_error()
766 traceback.print_exc(file=self.ostream)
767 traceback.print_exc(file=self.ostream)
767 info('\nUnfortunately, your original traceback can not be constructed.\n')
768 info('\nUnfortunately, your original traceback can not be constructed.\n')
768 return ''
769 return ''
769
770
770 # build some color string templates outside these nested loops
771 # build some color string templates outside these nested loops
771 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
772 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
772 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
773 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
773 ColorsNormal)
774 ColorsNormal)
774 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
775 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
775 (Colors.vName, Colors.valEm, ColorsNormal)
776 (Colors.vName, Colors.valEm, ColorsNormal)
776 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
777 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
777 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
778 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
778 Colors.vName, ColorsNormal)
779 Colors.vName, ColorsNormal)
779 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
780 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
780 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
781 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
781 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
782 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
782 ColorsNormal)
783 ColorsNormal)
783
784
784 # now, loop over all records printing context and info
785 # now, loop over all records printing context and info
785 abspath = os.path.abspath
786 abspath = os.path.abspath
786 for frame, file, lnum, func, lines, index in records:
787 for frame, file, lnum, func, lines, index in records:
787 #print '*** record:',file,lnum,func,lines,index # dbg
788 #print '*** record:',file,lnum,func,lines,index # dbg
788 try:
789 try:
789 file = file and abspath(file) or '?'
790 file = file and abspath(file) or '?'
790 except OSError:
791 except OSError:
791 # if file is '<console>' or something not in the filesystem,
792 # if file is '<console>' or something not in the filesystem,
792 # the abspath call will throw an OSError. Just ignore it and
793 # the abspath call will throw an OSError. Just ignore it and
793 # keep the original file string.
794 # keep the original file string.
794 pass
795 pass
795 link = tpl_link % file
796 link = tpl_link % file
796 try:
797 try:
797 args, varargs, varkw, locals = inspect.getargvalues(frame)
798 args, varargs, varkw, locals = inspect.getargvalues(frame)
798 except:
799 except:
799 # This can happen due to a bug in python2.3. We should be
800 # This can happen due to a bug in python2.3. We should be
800 # able to remove this try/except when 2.4 becomes a
801 # able to remove this try/except when 2.4 becomes a
801 # requirement. Bug details at http://python.org/sf/1005466
802 # requirement. Bug details at http://python.org/sf/1005466
802 inspect_error()
803 inspect_error()
803 traceback.print_exc(file=self.ostream)
804 traceback.print_exc(file=self.ostream)
804 info("\nIPython's exception reporting continues...\n")
805 info("\nIPython's exception reporting continues...\n")
805
806
806 if func == '?':
807 if func == '?':
807 call = ''
808 call = ''
808 else:
809 else:
809 # Decide whether to include variable details or not
810 # Decide whether to include variable details or not
810 var_repr = self.include_vars and eqrepr or nullrepr
811 var_repr = self.include_vars and eqrepr or nullrepr
811 try:
812 try:
812 call = tpl_call % (func,inspect.formatargvalues(args,
813 call = tpl_call % (func,inspect.formatargvalues(args,
813 varargs, varkw,
814 varargs, varkw,
814 locals,formatvalue=var_repr))
815 locals,formatvalue=var_repr))
815 except KeyError:
816 except KeyError:
816 # This happens in situations like errors inside generator
817 # This happens in situations like errors inside generator
817 # expressions, where local variables are listed in the
818 # expressions, where local variables are listed in the
818 # line, but can't be extracted from the frame. I'm not
819 # line, but can't be extracted from the frame. I'm not
819 # 100% sure this isn't actually a bug in inspect itself,
820 # 100% sure this isn't actually a bug in inspect itself,
820 # but since there's no info for us to compute with, the
821 # but since there's no info for us to compute with, the
821 # best we can do is report the failure and move on. Here
822 # best we can do is report the failure and move on. Here
822 # we must *not* call any traceback construction again,
823 # we must *not* call any traceback construction again,
823 # because that would mess up use of %debug later on. So we
824 # because that would mess up use of %debug later on. So we
824 # simply report the failure and move on. The only
825 # simply report the failure and move on. The only
825 # limitation will be that this frame won't have locals
826 # limitation will be that this frame won't have locals
826 # listed in the call signature. Quite subtle problem...
827 # listed in the call signature. Quite subtle problem...
827 # I can't think of a good way to validate this in a unit
828 # I can't think of a good way to validate this in a unit
828 # test, but running a script consisting of:
829 # test, but running a script consisting of:
829 # dict( (k,v.strip()) for (k,v) in range(10) )
830 # dict( (k,v.strip()) for (k,v) in range(10) )
830 # will illustrate the error, if this exception catch is
831 # will illustrate the error, if this exception catch is
831 # disabled.
832 # disabled.
832 call = tpl_call_fail % func
833 call = tpl_call_fail % func
833
834
834 # Initialize a list of names on the current line, which the
835 # Initialize a list of names on the current line, which the
835 # tokenizer below will populate.
836 # tokenizer below will populate.
836 names = []
837 names = []
837
838
838 def tokeneater(token_type, token, start, end, line):
839 def tokeneater(token_type, token, start, end, line):
839 """Stateful tokeneater which builds dotted names.
840 """Stateful tokeneater which builds dotted names.
840
841
841 The list of names it appends to (from the enclosing scope) can
842 The list of names it appends to (from the enclosing scope) can
842 contain repeated composite names. This is unavoidable, since
843 contain repeated composite names. This is unavoidable, since
843 there is no way to disambguate partial dotted structures until
844 there is no way to disambguate partial dotted structures until
844 the full list is known. The caller is responsible for pruning
845 the full list is known. The caller is responsible for pruning
845 the final list of duplicates before using it."""
846 the final list of duplicates before using it."""
846
847
847 # build composite names
848 # build composite names
848 if token == '.':
849 if token == '.':
849 try:
850 try:
850 names[-1] += '.'
851 names[-1] += '.'
851 # store state so the next token is added for x.y.z names
852 # store state so the next token is added for x.y.z names
852 tokeneater.name_cont = True
853 tokeneater.name_cont = True
853 return
854 return
854 except IndexError:
855 except IndexError:
855 pass
856 pass
856 if token_type == tokenize.NAME and token not in keyword.kwlist:
857 if token_type == tokenize.NAME and token not in keyword.kwlist:
857 if tokeneater.name_cont:
858 if tokeneater.name_cont:
858 # Dotted names
859 # Dotted names
859 names[-1] += token
860 names[-1] += token
860 tokeneater.name_cont = False
861 tokeneater.name_cont = False
861 else:
862 else:
862 # Regular new names. We append everything, the caller
863 # Regular new names. We append everything, the caller
863 # will be responsible for pruning the list later. It's
864 # will be responsible for pruning the list later. It's
864 # very tricky to try to prune as we go, b/c composite
865 # very tricky to try to prune as we go, b/c composite
865 # names can fool us. The pruning at the end is easy
866 # names can fool us. The pruning at the end is easy
866 # to do (or the caller can print a list with repeated
867 # to do (or the caller can print a list with repeated
867 # names if so desired.
868 # names if so desired.
868 names.append(token)
869 names.append(token)
869 elif token_type == tokenize.NEWLINE:
870 elif token_type == tokenize.NEWLINE:
870 raise IndexError
871 raise IndexError
871 # we need to store a bit of state in the tokenizer to build
872 # we need to store a bit of state in the tokenizer to build
872 # dotted names
873 # dotted names
873 tokeneater.name_cont = False
874 tokeneater.name_cont = False
874
875
875 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
876 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
877 if file.endswith(('.pyc','.pyo')):
878 file = pyfile.source_from_cache(file)
876 line = getline(file, lnum[0])
879 line = getline(file, lnum[0])
877 lnum[0] += 1
880 lnum[0] += 1
878 return line
881 return line
879
882
880 # Build the list of names on this line of code where the exception
883 # Build the list of names on this line of code where the exception
881 # occurred.
884 # occurred.
882 try:
885 try:
883 # This builds the names list in-place by capturing it from the
886 # This builds the names list in-place by capturing it from the
884 # enclosing scope.
887 # enclosing scope.
885 for token in generate_tokens(linereader):
888 for token in generate_tokens(linereader):
886 tokeneater(*token)
889 tokeneater(*token)
887 except (IndexError, UnicodeDecodeError):
890 except (IndexError, UnicodeDecodeError):
888 # signals exit of tokenizer
891 # signals exit of tokenizer
889 pass
892 pass
890 except tokenize.TokenError,msg:
893 except tokenize.TokenError,msg:
891 _m = ("An unexpected error occurred while tokenizing input\n"
894 _m = ("An unexpected error occurred while tokenizing input\n"
892 "The following traceback may be corrupted or invalid\n"
895 "The following traceback may be corrupted or invalid\n"
893 "The error message is: %s\n" % msg)
896 "The error message is: %s\n" % msg)
894 error(_m)
897 error(_m)
895
898
896 # prune names list of duplicates, but keep the right order
899 # prune names list of duplicates, but keep the right order
897 unique_names = uniq_stable(names)
900 unique_names = uniq_stable(names)
898
901
899 # Start loop over vars
902 # Start loop over vars
900 lvals = []
903 lvals = []
901 if self.include_vars:
904 if self.include_vars:
902 for name_full in unique_names:
905 for name_full in unique_names:
903 name_base = name_full.split('.',1)[0]
906 name_base = name_full.split('.',1)[0]
904 if name_base in frame.f_code.co_varnames:
907 if name_base in frame.f_code.co_varnames:
905 if locals.has_key(name_base):
908 if locals.has_key(name_base):
906 try:
909 try:
907 value = repr(eval(name_full,locals))
910 value = repr(eval(name_full,locals))
908 except:
911 except:
909 value = undefined
912 value = undefined
910 else:
913 else:
911 value = undefined
914 value = undefined
912 name = tpl_local_var % name_full
915 name = tpl_local_var % name_full
913 else:
916 else:
914 if frame.f_globals.has_key(name_base):
917 if frame.f_globals.has_key(name_base):
915 try:
918 try:
916 value = repr(eval(name_full,frame.f_globals))
919 value = repr(eval(name_full,frame.f_globals))
917 except:
920 except:
918 value = undefined
921 value = undefined
919 else:
922 else:
920 value = undefined
923 value = undefined
921 name = tpl_global_var % name_full
924 name = tpl_global_var % name_full
922 lvals.append(tpl_name_val % (name,value))
925 lvals.append(tpl_name_val % (name,value))
923 if lvals:
926 if lvals:
924 lvals = '%s%s' % (indent,em_normal.join(lvals))
927 lvals = '%s%s' % (indent,em_normal.join(lvals))
925 else:
928 else:
926 lvals = ''
929 lvals = ''
927
930
928 level = '%s %s\n' % (link,call)
931 level = '%s %s\n' % (link,call)
929
932
930 if index is None:
933 if index is None:
931 frames.append(level)
934 frames.append(level)
932 else:
935 else:
933 frames.append('%s%s' % (level,''.join(
936 frames.append('%s%s' % (level,''.join(
934 _format_traceback_lines(lnum,index,lines,Colors,lvals,
937 _format_traceback_lines(lnum,index,lines,Colors,lvals,
935 col_scheme))))
938 col_scheme))))
936
939
937 # Get (safely) a string form of the exception info
940 # Get (safely) a string form of the exception info
938 try:
941 try:
939 etype_str,evalue_str = map(str,(etype,evalue))
942 etype_str,evalue_str = map(str,(etype,evalue))
940 except:
943 except:
941 # User exception is improperly defined.
944 # User exception is improperly defined.
942 etype,evalue = str,sys.exc_info()[:2]
945 etype,evalue = str,sys.exc_info()[:2]
943 etype_str,evalue_str = map(str,(etype,evalue))
946 etype_str,evalue_str = map(str,(etype,evalue))
944 # ... and format it
947 # ... and format it
945 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
948 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
946 ColorsNormal, evalue_str)]
949 ColorsNormal, evalue_str)]
947 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
950 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
948 try:
951 try:
949 names = [w for w in dir(evalue) if isinstance(w, basestring)]
952 names = [w for w in dir(evalue) if isinstance(w, basestring)]
950 except:
953 except:
951 # Every now and then, an object with funny inernals blows up
954 # Every now and then, an object with funny inernals blows up
952 # when dir() is called on it. We do the best we can to report
955 # when dir() is called on it. We do the best we can to report
953 # the problem and continue
956 # the problem and continue
954 _m = '%sException reporting error (object with broken dir())%s:'
957 _m = '%sException reporting error (object with broken dir())%s:'
955 exception.append(_m % (Colors.excName,ColorsNormal))
958 exception.append(_m % (Colors.excName,ColorsNormal))
956 etype_str,evalue_str = map(str,sys.exc_info()[:2])
959 etype_str,evalue_str = map(str,sys.exc_info()[:2])
957 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
960 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
958 ColorsNormal, evalue_str))
961 ColorsNormal, evalue_str))
959 names = []
962 names = []
960 for name in names:
963 for name in names:
961 value = text_repr(getattr(evalue, name))
964 value = text_repr(getattr(evalue, name))
962 exception.append('\n%s%s = %s' % (indent, name, value))
965 exception.append('\n%s%s = %s' % (indent, name, value))
963
966
964 # vds: >>
967 # vds: >>
965 if records:
968 if records:
966 filepath, lnum = records[-1][1:3]
969 filepath, lnum = records[-1][1:3]
967 #print "file:", str(file), "linenb", str(lnum) # dbg
970 #print "file:", str(file), "linenb", str(lnum) # dbg
968 filepath = os.path.abspath(filepath)
971 filepath = os.path.abspath(filepath)
969 ipinst = ipapi.get()
972 ipinst = ipapi.get()
970 if ipinst is not None:
973 if ipinst is not None:
971 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
974 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
972 # vds: <<
975 # vds: <<
973
976
974 # return all our info assembled as a single string
977 # return all our info assembled as a single string
975 # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
978 # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
976 return [head] + frames + [''.join(exception[0])]
979 return [head] + frames + [''.join(exception[0])]
977
980
978 def debugger(self,force=False):
981 def debugger(self,force=False):
979 """Call up the pdb debugger if desired, always clean up the tb
982 """Call up the pdb debugger if desired, always clean up the tb
980 reference.
983 reference.
981
984
982 Keywords:
985 Keywords:
983
986
984 - force(False): by default, this routine checks the instance call_pdb
987 - force(False): by default, this routine checks the instance call_pdb
985 flag and does not actually invoke the debugger if the flag is false.
988 flag and does not actually invoke the debugger if the flag is false.
986 The 'force' option forces the debugger to activate even if the flag
989 The 'force' option forces the debugger to activate even if the flag
987 is false.
990 is false.
988
991
989 If the call_pdb flag is set, the pdb interactive debugger is
992 If the call_pdb flag is set, the pdb interactive debugger is
990 invoked. In all cases, the self.tb reference to the current traceback
993 invoked. In all cases, the self.tb reference to the current traceback
991 is deleted to prevent lingering references which hamper memory
994 is deleted to prevent lingering references which hamper memory
992 management.
995 management.
993
996
994 Note that each call to pdb() does an 'import readline', so if your app
997 Note that each call to pdb() does an 'import readline', so if your app
995 requires a special setup for the readline completers, you'll have to
998 requires a special setup for the readline completers, you'll have to
996 fix that by hand after invoking the exception handler."""
999 fix that by hand after invoking the exception handler."""
997
1000
998 if force or self.call_pdb:
1001 if force or self.call_pdb:
999 if self.pdb is None:
1002 if self.pdb is None:
1000 self.pdb = debugger.Pdb(
1003 self.pdb = debugger.Pdb(
1001 self.color_scheme_table.active_scheme_name)
1004 self.color_scheme_table.active_scheme_name)
1002 # the system displayhook may have changed, restore the original
1005 # the system displayhook may have changed, restore the original
1003 # for pdb
1006 # for pdb
1004 display_trap = DisplayTrap(hook=sys.__displayhook__)
1007 display_trap = DisplayTrap(hook=sys.__displayhook__)
1005 with display_trap:
1008 with display_trap:
1006 self.pdb.reset()
1009 self.pdb.reset()
1007 # Find the right frame so we don't pop up inside ipython itself
1010 # Find the right frame so we don't pop up inside ipython itself
1008 if hasattr(self,'tb') and self.tb is not None:
1011 if hasattr(self,'tb') and self.tb is not None:
1009 etb = self.tb
1012 etb = self.tb
1010 else:
1013 else:
1011 etb = self.tb = sys.last_traceback
1014 etb = self.tb = sys.last_traceback
1012 while self.tb is not None and self.tb.tb_next is not None:
1015 while self.tb is not None and self.tb.tb_next is not None:
1013 self.tb = self.tb.tb_next
1016 self.tb = self.tb.tb_next
1014 if etb and etb.tb_next:
1017 if etb and etb.tb_next:
1015 etb = etb.tb_next
1018 etb = etb.tb_next
1016 self.pdb.botframe = etb.tb_frame
1019 self.pdb.botframe = etb.tb_frame
1017 self.pdb.interaction(self.tb.tb_frame, self.tb)
1020 self.pdb.interaction(self.tb.tb_frame, self.tb)
1018
1021
1019 if hasattr(self,'tb'):
1022 if hasattr(self,'tb'):
1020 del self.tb
1023 del self.tb
1021
1024
1022 def handler(self, info=None):
1025 def handler(self, info=None):
1023 (etype, evalue, etb) = info or sys.exc_info()
1026 (etype, evalue, etb) = info or sys.exc_info()
1024 self.tb = etb
1027 self.tb = etb
1025 ostream = self.ostream
1028 ostream = self.ostream
1026 ostream.flush()
1029 ostream.flush()
1027 ostream.write(self.text(etype, evalue, etb))
1030 ostream.write(self.text(etype, evalue, etb))
1028 ostream.write('\n')
1031 ostream.write('\n')
1029 ostream.flush()
1032 ostream.flush()
1030
1033
1031 # Changed so an instance can just be called as VerboseTB_inst() and print
1034 # Changed so an instance can just be called as VerboseTB_inst() and print
1032 # out the right info on its own.
1035 # out the right info on its own.
1033 def __call__(self, etype=None, evalue=None, etb=None):
1036 def __call__(self, etype=None, evalue=None, etb=None):
1034 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1037 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1035 if etb is None:
1038 if etb is None:
1036 self.handler()
1039 self.handler()
1037 else:
1040 else:
1038 self.handler((etype, evalue, etb))
1041 self.handler((etype, evalue, etb))
1039 try:
1042 try:
1040 self.debugger()
1043 self.debugger()
1041 except KeyboardInterrupt:
1044 except KeyboardInterrupt:
1042 print "\nKeyboardInterrupt"
1045 print "\nKeyboardInterrupt"
1043
1046
1044 #----------------------------------------------------------------------------
1047 #----------------------------------------------------------------------------
1045 class FormattedTB(VerboseTB, ListTB):
1048 class FormattedTB(VerboseTB, ListTB):
1046 """Subclass ListTB but allow calling with a traceback.
1049 """Subclass ListTB but allow calling with a traceback.
1047
1050
1048 It can thus be used as a sys.excepthook for Python > 2.1.
1051 It can thus be used as a sys.excepthook for Python > 2.1.
1049
1052
1050 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1053 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1051
1054
1052 Allows a tb_offset to be specified. This is useful for situations where
1055 Allows a tb_offset to be specified. This is useful for situations where
1053 one needs to remove a number of topmost frames from the traceback (such as
1056 one needs to remove a number of topmost frames from the traceback (such as
1054 occurs with python programs that themselves execute other python code,
1057 occurs with python programs that themselves execute other python code,
1055 like Python shells). """
1058 like Python shells). """
1056
1059
1057 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1060 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1058 ostream=None,
1061 ostream=None,
1059 tb_offset=0, long_header=False, include_vars=False,
1062 tb_offset=0, long_header=False, include_vars=False,
1060 check_cache=None):
1063 check_cache=None):
1061
1064
1062 # NEVER change the order of this list. Put new modes at the end:
1065 # NEVER change the order of this list. Put new modes at the end:
1063 self.valid_modes = ['Plain','Context','Verbose']
1066 self.valid_modes = ['Plain','Context','Verbose']
1064 self.verbose_modes = self.valid_modes[1:3]
1067 self.verbose_modes = self.valid_modes[1:3]
1065
1068
1066 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1069 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1067 ostream=ostream, tb_offset=tb_offset,
1070 ostream=ostream, tb_offset=tb_offset,
1068 long_header=long_header, include_vars=include_vars,
1071 long_header=long_header, include_vars=include_vars,
1069 check_cache=check_cache)
1072 check_cache=check_cache)
1070
1073
1071 # Different types of tracebacks are joined with different separators to
1074 # Different types of tracebacks are joined with different separators to
1072 # form a single string. They are taken from this dict
1075 # form a single string. They are taken from this dict
1073 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1076 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1074 # set_mode also sets the tb_join_char attribute
1077 # set_mode also sets the tb_join_char attribute
1075 self.set_mode(mode)
1078 self.set_mode(mode)
1076
1079
1077 def _extract_tb(self,tb):
1080 def _extract_tb(self,tb):
1078 if tb:
1081 if tb:
1079 return traceback.extract_tb(tb)
1082 return traceback.extract_tb(tb)
1080 else:
1083 else:
1081 return None
1084 return None
1082
1085
1083 def structured_traceback(self, etype, value, tb, tb_offset=None, context=5):
1086 def structured_traceback(self, etype, value, tb, tb_offset=None, context=5):
1084 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1087 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1085 mode = self.mode
1088 mode = self.mode
1086 if mode in self.verbose_modes:
1089 if mode in self.verbose_modes:
1087 # Verbose modes need a full traceback
1090 # Verbose modes need a full traceback
1088 return VerboseTB.structured_traceback(
1091 return VerboseTB.structured_traceback(
1089 self, etype, value, tb, tb_offset, context
1092 self, etype, value, tb, tb_offset, context
1090 )
1093 )
1091 else:
1094 else:
1092 # We must check the source cache because otherwise we can print
1095 # We must check the source cache because otherwise we can print
1093 # out-of-date source code.
1096 # out-of-date source code.
1094 self.check_cache()
1097 self.check_cache()
1095 # Now we can extract and format the exception
1098 # Now we can extract and format the exception
1096 elist = self._extract_tb(tb)
1099 elist = self._extract_tb(tb)
1097 return ListTB.structured_traceback(
1100 return ListTB.structured_traceback(
1098 self, etype, value, elist, tb_offset, context
1101 self, etype, value, elist, tb_offset, context
1099 )
1102 )
1100
1103
1101 def stb2text(self, stb):
1104 def stb2text(self, stb):
1102 """Convert a structured traceback (a list) to a string."""
1105 """Convert a structured traceback (a list) to a string."""
1103 return self.tb_join_char.join(stb)
1106 return self.tb_join_char.join(stb)
1104
1107
1105
1108
1106 def set_mode(self,mode=None):
1109 def set_mode(self,mode=None):
1107 """Switch to the desired mode.
1110 """Switch to the desired mode.
1108
1111
1109 If mode is not specified, cycles through the available modes."""
1112 If mode is not specified, cycles through the available modes."""
1110
1113
1111 if not mode:
1114 if not mode:
1112 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
1115 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
1113 len(self.valid_modes)
1116 len(self.valid_modes)
1114 self.mode = self.valid_modes[new_idx]
1117 self.mode = self.valid_modes[new_idx]
1115 elif mode not in self.valid_modes:
1118 elif mode not in self.valid_modes:
1116 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
1119 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
1117 'Valid modes: '+str(self.valid_modes)
1120 'Valid modes: '+str(self.valid_modes)
1118 else:
1121 else:
1119 self.mode = mode
1122 self.mode = mode
1120 # include variable details only in 'Verbose' mode
1123 # include variable details only in 'Verbose' mode
1121 self.include_vars = (self.mode == self.valid_modes[2])
1124 self.include_vars = (self.mode == self.valid_modes[2])
1122 # Set the join character for generating text tracebacks
1125 # Set the join character for generating text tracebacks
1123 self.tb_join_char = self._join_chars[self.mode]
1126 self.tb_join_char = self._join_chars[self.mode]
1124
1127
1125 # some convenient shorcuts
1128 # some convenient shorcuts
1126 def plain(self):
1129 def plain(self):
1127 self.set_mode(self.valid_modes[0])
1130 self.set_mode(self.valid_modes[0])
1128
1131
1129 def context(self):
1132 def context(self):
1130 self.set_mode(self.valid_modes[1])
1133 self.set_mode(self.valid_modes[1])
1131
1134
1132 def verbose(self):
1135 def verbose(self):
1133 self.set_mode(self.valid_modes[2])
1136 self.set_mode(self.valid_modes[2])
1134
1137
1135 #----------------------------------------------------------------------------
1138 #----------------------------------------------------------------------------
1136 class AutoFormattedTB(FormattedTB):
1139 class AutoFormattedTB(FormattedTB):
1137 """A traceback printer which can be called on the fly.
1140 """A traceback printer which can be called on the fly.
1138
1141
1139 It will find out about exceptions by itself.
1142 It will find out about exceptions by itself.
1140
1143
1141 A brief example:
1144 A brief example:
1142
1145
1143 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1146 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1144 try:
1147 try:
1145 ...
1148 ...
1146 except:
1149 except:
1147 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1150 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1148 """
1151 """
1149
1152
1150 def __call__(self,etype=None,evalue=None,etb=None,
1153 def __call__(self,etype=None,evalue=None,etb=None,
1151 out=None,tb_offset=None):
1154 out=None,tb_offset=None):
1152 """Print out a formatted exception traceback.
1155 """Print out a formatted exception traceback.
1153
1156
1154 Optional arguments:
1157 Optional arguments:
1155 - out: an open file-like object to direct output to.
1158 - out: an open file-like object to direct output to.
1156
1159
1157 - tb_offset: the number of frames to skip over in the stack, on a
1160 - tb_offset: the number of frames to skip over in the stack, on a
1158 per-call basis (this overrides temporarily the instance's tb_offset
1161 per-call basis (this overrides temporarily the instance's tb_offset
1159 given at initialization time. """
1162 given at initialization time. """
1160
1163
1161
1164
1162 if out is None:
1165 if out is None:
1163 out = self.ostream
1166 out = self.ostream
1164 out.flush()
1167 out.flush()
1165 out.write(self.text(etype, evalue, etb, tb_offset))
1168 out.write(self.text(etype, evalue, etb, tb_offset))
1166 out.write('\n')
1169 out.write('\n')
1167 out.flush()
1170 out.flush()
1168 # FIXME: we should remove the auto pdb behavior from here and leave
1171 # FIXME: we should remove the auto pdb behavior from here and leave
1169 # that to the clients.
1172 # that to the clients.
1170 try:
1173 try:
1171 self.debugger()
1174 self.debugger()
1172 except KeyboardInterrupt:
1175 except KeyboardInterrupt:
1173 print "\nKeyboardInterrupt"
1176 print "\nKeyboardInterrupt"
1174
1177
1175 def structured_traceback(self, etype=None, value=None, tb=None,
1178 def structured_traceback(self, etype=None, value=None, tb=None,
1176 tb_offset=None, context=5):
1179 tb_offset=None, context=5):
1177 if etype is None:
1180 if etype is None:
1178 etype,value,tb = sys.exc_info()
1181 etype,value,tb = sys.exc_info()
1179 self.tb = tb
1182 self.tb = tb
1180 return FormattedTB.structured_traceback(
1183 return FormattedTB.structured_traceback(
1181 self, etype, value, tb, tb_offset, context)
1184 self, etype, value, tb, tb_offset, context)
1182
1185
1183 #---------------------------------------------------------------------------
1186 #---------------------------------------------------------------------------
1184
1187
1185 # A simple class to preserve Nathan's original functionality.
1188 # A simple class to preserve Nathan's original functionality.
1186 class ColorTB(FormattedTB):
1189 class ColorTB(FormattedTB):
1187 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1190 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1188 def __init__(self,color_scheme='Linux',call_pdb=0):
1191 def __init__(self,color_scheme='Linux',call_pdb=0):
1189 FormattedTB.__init__(self,color_scheme=color_scheme,
1192 FormattedTB.__init__(self,color_scheme=color_scheme,
1190 call_pdb=call_pdb)
1193 call_pdb=call_pdb)
1191
1194
1192
1195
1193 class SyntaxTB(ListTB):
1196 class SyntaxTB(ListTB):
1194 """Extension which holds some state: the last exception value"""
1197 """Extension which holds some state: the last exception value"""
1195
1198
1196 def __init__(self,color_scheme = 'NoColor'):
1199 def __init__(self,color_scheme = 'NoColor'):
1197 ListTB.__init__(self,color_scheme)
1200 ListTB.__init__(self,color_scheme)
1198 self.last_syntax_error = None
1201 self.last_syntax_error = None
1199
1202
1200 def __call__(self, etype, value, elist):
1203 def __call__(self, etype, value, elist):
1201 self.last_syntax_error = value
1204 self.last_syntax_error = value
1202 ListTB.__call__(self,etype,value,elist)
1205 ListTB.__call__(self,etype,value,elist)
1203
1206
1204 def clear_err_state(self):
1207 def clear_err_state(self):
1205 """Return the current error state and clear it"""
1208 """Return the current error state and clear it"""
1206 e = self.last_syntax_error
1209 e = self.last_syntax_error
1207 self.last_syntax_error = None
1210 self.last_syntax_error = None
1208 return e
1211 return e
1209
1212
1210 def stb2text(self, stb):
1213 def stb2text(self, stb):
1211 """Convert a structured traceback (a list) to a string."""
1214 """Convert a structured traceback (a list) to a string."""
1212 return ''.join(stb)
1215 return ''.join(stb)
1213
1216
1214
1217
1215 #----------------------------------------------------------------------------
1218 #----------------------------------------------------------------------------
1216 # module testing (minimal)
1219 # module testing (minimal)
1217 if __name__ == "__main__":
1220 if __name__ == "__main__":
1218 def spam(c, (d, e)):
1221 def spam(c, (d, e)):
1219 x = c + d
1222 x = c + d
1220 y = c * d
1223 y = c * d
1221 foo(x, y)
1224 foo(x, y)
1222
1225
1223 def foo(a, b, bar=1):
1226 def foo(a, b, bar=1):
1224 eggs(a, b + bar)
1227 eggs(a, b + bar)
1225
1228
1226 def eggs(f, g, z=globals()):
1229 def eggs(f, g, z=globals()):
1227 h = f + g
1230 h = f + g
1228 i = f - g
1231 i = f - g
1229 return h / i
1232 return h / i
1230
1233
1231 print ''
1234 print ''
1232 print '*** Before ***'
1235 print '*** Before ***'
1233 try:
1236 try:
1234 print spam(1, (2, 3))
1237 print spam(1, (2, 3))
1235 except:
1238 except:
1236 traceback.print_exc()
1239 traceback.print_exc()
1237 print ''
1240 print ''
1238
1241
1239 handler = ColorTB()
1242 handler = ColorTB()
1240 print '*** ColorTB ***'
1243 print '*** ColorTB ***'
1241 try:
1244 try:
1242 print spam(1, (2, 3))
1245 print spam(1, (2, 3))
1243 except:
1246 except:
1244 apply(handler, sys.exc_info() )
1247 apply(handler, sys.exc_info() )
1245 print ''
1248 print ''
1246
1249
1247 handler = VerboseTB()
1250 handler = VerboseTB()
1248 print '*** VerboseTB ***'
1251 print '*** VerboseTB ***'
1249 try:
1252 try:
1250 print spam(1, (2, 3))
1253 print spam(1, (2, 3))
1251 except:
1254 except:
1252 apply(handler, sys.exc_info() )
1255 apply(handler, sys.exc_info() )
1253 print ''
1256 print ''
1254
1257
General Comments 0
You need to be logged in to leave comments. Login now