##// END OF EJS Templates
Merge pull request #12790 from Jongy/remove-old-ultratb-getargs...
Matthias Bussonnier -
r26307:9407cc39 merge
parent child Browse files
Show More
@@ -1,1525 +1,1456 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Verbose and colourful traceback formatting.
3 Verbose and colourful traceback formatting.
4
4
5 **ColorTB**
5 **ColorTB**
6
6
7 I've always found it a bit hard to visually parse tracebacks in Python. The
7 I've always found it a bit hard to visually parse tracebacks in Python. The
8 ColorTB class is a solution to that problem. It colors the different parts of a
8 ColorTB class is a solution to that problem. It colors the different parts of a
9 traceback in a manner similar to what you would expect from a syntax-highlighting
9 traceback in a manner similar to what you would expect from a syntax-highlighting
10 text editor.
10 text editor.
11
11
12 Installation instructions for ColorTB::
12 Installation instructions for ColorTB::
13
13
14 import sys,ultratb
14 import sys,ultratb
15 sys.excepthook = ultratb.ColorTB()
15 sys.excepthook = ultratb.ColorTB()
16
16
17 **VerboseTB**
17 **VerboseTB**
18
18
19 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
19 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
20 of useful info when a traceback occurs. Ping originally had it spit out HTML
20 of useful info when a traceback occurs. Ping originally had it spit out HTML
21 and intended it for CGI programmers, but why should they have all the fun? I
21 and intended it for CGI programmers, but why should they have all the fun? I
22 altered it to spit out colored text to the terminal. It's a bit overwhelming,
22 altered it to spit out colored text to the terminal. It's a bit overwhelming,
23 but kind of neat, and maybe useful for long-running programs that you believe
23 but kind of neat, and maybe useful for long-running programs that you believe
24 are bug-free. If a crash *does* occur in that type of program you want details.
24 are bug-free. If a crash *does* occur in that type of program you want details.
25 Give it a shot--you'll love it or you'll hate it.
25 Give it a shot--you'll love it or you'll hate it.
26
26
27 .. note::
27 .. note::
28
28
29 The Verbose mode prints the variables currently visible where the exception
29 The Verbose mode prints the variables currently visible where the exception
30 happened (shortening their strings if too long). This can potentially be
30 happened (shortening their strings if too long). This can potentially be
31 very slow, if you happen to have a huge data structure whose string
31 very slow, if you happen to have a huge data structure whose string
32 representation is complex to compute. Your computer may appear to freeze for
32 representation is complex to compute. Your computer may appear to freeze for
33 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
33 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
34 with Ctrl-C (maybe hitting it more than once).
34 with Ctrl-C (maybe hitting it more than once).
35
35
36 If you encounter this kind of situation often, you may want to use the
36 If you encounter this kind of situation often, you may want to use the
37 Verbose_novars mode instead of the regular Verbose, which avoids formatting
37 Verbose_novars mode instead of the regular Verbose, which avoids formatting
38 variables (but otherwise includes the information and context given by
38 variables (but otherwise includes the information and context given by
39 Verbose).
39 Verbose).
40
40
41 .. note::
41 .. note::
42
42
43 The verbose mode print all variables in the stack, which means it can
43 The verbose mode print all variables in the stack, which means it can
44 potentially leak sensitive information like access keys, or unencrypted
44 potentially leak sensitive information like access keys, or unencrypted
45 password.
45 password.
46
46
47 Installation instructions for VerboseTB::
47 Installation instructions for VerboseTB::
48
48
49 import sys,ultratb
49 import sys,ultratb
50 sys.excepthook = ultratb.VerboseTB()
50 sys.excepthook = ultratb.VerboseTB()
51
51
52 Note: Much of the code in this module was lifted verbatim from the standard
52 Note: Much of the code in this module was lifted verbatim from the standard
53 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
53 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
54
54
55 Color schemes
55 Color schemes
56 -------------
56 -------------
57
57
58 The colors are defined in the class TBTools through the use of the
58 The colors are defined in the class TBTools through the use of the
59 ColorSchemeTable class. Currently the following exist:
59 ColorSchemeTable class. Currently the following exist:
60
60
61 - NoColor: allows all of this module to be used in any terminal (the color
61 - NoColor: allows all of this module to be used in any terminal (the color
62 escapes are just dummy blank strings).
62 escapes are just dummy blank strings).
63
63
64 - Linux: is meant to look good in a terminal like the Linux console (black
64 - Linux: is meant to look good in a terminal like the Linux console (black
65 or very dark background).
65 or very dark background).
66
66
67 - LightBG: similar to Linux but swaps dark/light colors to be more readable
67 - LightBG: similar to Linux but swaps dark/light colors to be more readable
68 in light background terminals.
68 in light background terminals.
69
69
70 - Neutral: a neutral color scheme that should be readable on both light and
70 - Neutral: a neutral color scheme that should be readable on both light and
71 dark background
71 dark background
72
72
73 You can implement other color schemes easily, the syntax is fairly
73 You can implement other color schemes easily, the syntax is fairly
74 self-explanatory. Please send back new schemes you develop to the author for
74 self-explanatory. Please send back new schemes you develop to the author for
75 possible inclusion in future releases.
75 possible inclusion in future releases.
76
76
77 Inheritance diagram:
77 Inheritance diagram:
78
78
79 .. inheritance-diagram:: IPython.core.ultratb
79 .. inheritance-diagram:: IPython.core.ultratb
80 :parts: 3
80 :parts: 3
81 """
81 """
82
82
83 #*****************************************************************************
83 #*****************************************************************************
84 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
84 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
85 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
85 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
86 #
86 #
87 # Distributed under the terms of the BSD License. The full license is in
87 # Distributed under the terms of the BSD License. The full license is in
88 # the file COPYING, distributed as part of this software.
88 # the file COPYING, distributed as part of this software.
89 #*****************************************************************************
89 #*****************************************************************************
90
90
91
91
92 import dis
92 import dis
93 import inspect
93 import inspect
94 import keyword
94 import keyword
95 import linecache
95 import linecache
96 import os
96 import os
97 import pydoc
97 import pydoc
98 import re
98 import re
99 import sys
99 import sys
100 import time
100 import time
101 import tokenize
101 import tokenize
102 import traceback
102 import traceback
103
103
104 from tokenize import generate_tokens
104 from tokenize import generate_tokens
105
105
106 # For purposes of monkeypatching inspect to fix a bug in it.
106 # For purposes of monkeypatching inspect to fix a bug in it.
107 from inspect import getsourcefile, getfile, getmodule, \
107 from inspect import getsourcefile, getfile, getmodule, \
108 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
108 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
109
109
110 # IPython's own modules
110 # IPython's own modules
111 from IPython import get_ipython
111 from IPython import get_ipython
112 from IPython.core import debugger
112 from IPython.core import debugger
113 from IPython.core.display_trap import DisplayTrap
113 from IPython.core.display_trap import DisplayTrap
114 from IPython.core.excolors import exception_colors
114 from IPython.core.excolors import exception_colors
115 from IPython.utils import PyColorize
115 from IPython.utils import PyColorize
116 from IPython.utils import path as util_path
116 from IPython.utils import path as util_path
117 from IPython.utils import py3compat
117 from IPython.utils import py3compat
118 from IPython.utils.data import uniq_stable
118 from IPython.utils.data import uniq_stable
119 from IPython.utils.terminal import get_terminal_size
119 from IPython.utils.terminal import get_terminal_size
120
120
121 from logging import info, error, debug
121 from logging import info, error, debug
122
122
123 from importlib.util import source_from_cache
123 from importlib.util import source_from_cache
124
124
125 import IPython.utils.colorable as colorable
125 import IPython.utils.colorable as colorable
126
126
127 # Globals
127 # Globals
128 # amount of space to put line numbers before verbose tracebacks
128 # amount of space to put line numbers before verbose tracebacks
129 INDENT_SIZE = 8
129 INDENT_SIZE = 8
130
130
131 # Default color scheme. This is used, for example, by the traceback
131 # Default color scheme. This is used, for example, by the traceback
132 # formatter. When running in an actual IPython instance, the user's rc.colors
132 # formatter. When running in an actual IPython instance, the user's rc.colors
133 # value is used, but having a module global makes this functionality available
133 # value is used, but having a module global makes this functionality available
134 # to users of ultratb who are NOT running inside ipython.
134 # to users of ultratb who are NOT running inside ipython.
135 DEFAULT_SCHEME = 'NoColor'
135 DEFAULT_SCHEME = 'NoColor'
136
136
137
137
138 # Number of frame above which we are likely to have a recursion and will
138 # Number of frame above which we are likely to have a recursion and will
139 # **attempt** to detect it. Made modifiable mostly to speedup test suite
139 # **attempt** to detect it. Made modifiable mostly to speedup test suite
140 # as detecting recursion is one of our slowest test
140 # as detecting recursion is one of our slowest test
141 _FRAME_RECURSION_LIMIT = 500
141 _FRAME_RECURSION_LIMIT = 500
142
142
143 # ---------------------------------------------------------------------------
143 # ---------------------------------------------------------------------------
144 # Code begins
144 # Code begins
145
145
146 # Utility functions
146 # Utility functions
147 def inspect_error():
147 def inspect_error():
148 """Print a message about internal inspect errors.
148 """Print a message about internal inspect errors.
149
149
150 These are unfortunately quite common."""
150 These are unfortunately quite common."""
151
151
152 error('Internal Python error in the inspect module.\n'
152 error('Internal Python error in the inspect module.\n'
153 'Below is the traceback from this internal error.\n')
153 'Below is the traceback from this internal error.\n')
154
154
155
155
156 # This function is a monkeypatch we apply to the Python inspect module. We have
156 # This function is a monkeypatch we apply to the Python inspect module. We have
157 # now found when it's needed (see discussion on issue gh-1456), and we have a
157 # now found when it's needed (see discussion on issue gh-1456), and we have a
158 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
158 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
159 # the monkeypatch is not applied. TK, Aug 2012.
159 # the monkeypatch is not applied. TK, Aug 2012.
160 def findsource(object):
160 def findsource(object):
161 """Return the entire source file and starting line number for an object.
161 """Return the entire source file and starting line number for an object.
162
162
163 The argument may be a module, class, method, function, traceback, frame,
163 The argument may be a module, class, method, function, traceback, frame,
164 or code object. The source code is returned as a list of all the lines
164 or code object. The source code is returned as a list of all the lines
165 in the file and the line number indexes a line in that list. An IOError
165 in the file and the line number indexes a line in that list. An IOError
166 is raised if the source code cannot be retrieved.
166 is raised if the source code cannot be retrieved.
167
167
168 FIXED version with which we monkeypatch the stdlib to work around a bug."""
168 FIXED version with which we monkeypatch the stdlib to work around a bug."""
169
169
170 file = getsourcefile(object) or getfile(object)
170 file = getsourcefile(object) or getfile(object)
171 # If the object is a frame, then trying to get the globals dict from its
171 # If the object is a frame, then trying to get the globals dict from its
172 # module won't work. Instead, the frame object itself has the globals
172 # module won't work. Instead, the frame object itself has the globals
173 # dictionary.
173 # dictionary.
174 globals_dict = None
174 globals_dict = None
175 if inspect.isframe(object):
175 if inspect.isframe(object):
176 # XXX: can this ever be false?
176 # XXX: can this ever be false?
177 globals_dict = object.f_globals
177 globals_dict = object.f_globals
178 else:
178 else:
179 module = getmodule(object, file)
179 module = getmodule(object, file)
180 if module:
180 if module:
181 globals_dict = module.__dict__
181 globals_dict = module.__dict__
182 lines = linecache.getlines(file, globals_dict)
182 lines = linecache.getlines(file, globals_dict)
183 if not lines:
183 if not lines:
184 raise IOError('could not get source code')
184 raise IOError('could not get source code')
185
185
186 if ismodule(object):
186 if ismodule(object):
187 return lines, 0
187 return lines, 0
188
188
189 if isclass(object):
189 if isclass(object):
190 name = object.__name__
190 name = object.__name__
191 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
191 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
192 # make some effort to find the best matching class definition:
192 # make some effort to find the best matching class definition:
193 # use the one with the least indentation, which is the one
193 # use the one with the least indentation, which is the one
194 # that's most probably not inside a function definition.
194 # that's most probably not inside a function definition.
195 candidates = []
195 candidates = []
196 for i, line in enumerate(lines):
196 for i, line in enumerate(lines):
197 match = pat.match(line)
197 match = pat.match(line)
198 if match:
198 if match:
199 # if it's at toplevel, it's already the best one
199 # if it's at toplevel, it's already the best one
200 if line[0] == 'c':
200 if line[0] == 'c':
201 return lines, i
201 return lines, i
202 # else add whitespace to candidate list
202 # else add whitespace to candidate list
203 candidates.append((match.group(1), i))
203 candidates.append((match.group(1), i))
204 if candidates:
204 if candidates:
205 # this will sort by whitespace, and by line number,
205 # this will sort by whitespace, and by line number,
206 # less whitespace first
206 # less whitespace first
207 candidates.sort()
207 candidates.sort()
208 return lines, candidates[0][1]
208 return lines, candidates[0][1]
209 else:
209 else:
210 raise IOError('could not find class definition')
210 raise IOError('could not find class definition')
211
211
212 if ismethod(object):
212 if ismethod(object):
213 object = object.__func__
213 object = object.__func__
214 if isfunction(object):
214 if isfunction(object):
215 object = object.__code__
215 object = object.__code__
216 if istraceback(object):
216 if istraceback(object):
217 object = object.tb_frame
217 object = object.tb_frame
218 if isframe(object):
218 if isframe(object):
219 object = object.f_code
219 object = object.f_code
220 if iscode(object):
220 if iscode(object):
221 if not hasattr(object, 'co_firstlineno'):
221 if not hasattr(object, 'co_firstlineno'):
222 raise IOError('could not find function definition')
222 raise IOError('could not find function definition')
223 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
223 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
224 pmatch = pat.match
224 pmatch = pat.match
225 # fperez - fix: sometimes, co_firstlineno can give a number larger than
225 # fperez - fix: sometimes, co_firstlineno can give a number larger than
226 # the length of lines, which causes an error. Safeguard against that.
226 # the length of lines, which causes an error. Safeguard against that.
227 lnum = min(object.co_firstlineno, len(lines)) - 1
227 lnum = min(object.co_firstlineno, len(lines)) - 1
228 while lnum > 0:
228 while lnum > 0:
229 if pmatch(lines[lnum]):
229 if pmatch(lines[lnum]):
230 break
230 break
231 lnum -= 1
231 lnum -= 1
232
232
233 return lines, lnum
233 return lines, lnum
234 raise IOError('could not find code object')
234 raise IOError('could not find code object')
235
235
236
236
237 # This is a patched version of inspect.getargs that applies the (unmerged)
238 # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes
239 # https://github.com/ipython/ipython/issues/8205 and
240 # https://github.com/ipython/ipython/issues/8293
241 def getargs(co):
242 """Get information about the arguments accepted by a code object.
243
244 Three things are returned: (args, varargs, varkw), where 'args' is
245 a list of argument names (possibly containing nested lists), and
246 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
247 if not iscode(co):
248 raise TypeError('{!r} is not a code object'.format(co))
249
250 nargs = co.co_argcount
251 names = co.co_varnames
252 args = list(names[:nargs])
253 step = 0
254
255 # The following acrobatics are for anonymous (tuple) arguments.
256 for i in range(nargs):
257 if args[i][:1] in ('', '.'):
258 stack, remain, count = [], [], []
259 while step < len(co.co_code):
260 op = ord(co.co_code[step])
261 step = step + 1
262 if op >= dis.HAVE_ARGUMENT:
263 opname = dis.opname[op]
264 value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
265 step = step + 2
266 if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
267 remain.append(value)
268 count.append(value)
269 elif opname in ('STORE_FAST', 'STORE_DEREF'):
270 if op in dis.haslocal:
271 stack.append(co.co_varnames[value])
272 elif op in dis.hasfree:
273 stack.append((co.co_cellvars + co.co_freevars)[value])
274 # Special case for sublists of length 1: def foo((bar))
275 # doesn't generate the UNPACK_TUPLE bytecode, so if
276 # `remain` is empty here, we have such a sublist.
277 if not remain:
278 stack[0] = [stack[0]]
279 break
280 else:
281 remain[-1] = remain[-1] - 1
282 while remain[-1] == 0:
283 remain.pop()
284 size = count.pop()
285 stack[-size:] = [stack[-size:]]
286 if not remain:
287 break
288 remain[-1] = remain[-1] - 1
289 if not remain:
290 break
291 args[i] = stack[0]
292
293 varargs = None
294 if co.co_flags & inspect.CO_VARARGS:
295 varargs = co.co_varnames[nargs]
296 nargs = nargs + 1
297 varkw = None
298 if co.co_flags & inspect.CO_VARKEYWORDS:
299 varkw = co.co_varnames[nargs]
300 return inspect.Arguments(args, varargs, varkw)
301
302
303 # Monkeypatch inspect to apply our bugfix.
237 # Monkeypatch inspect to apply our bugfix.
304 def with_patch_inspect(f):
238 def with_patch_inspect(f):
305 """
239 """
306 Deprecated since IPython 6.0
240 Deprecated since IPython 6.0
307 decorator for monkeypatching inspect.findsource
241 decorator for monkeypatching inspect.findsource
308 """
242 """
309
243
310 def wrapped(*args, **kwargs):
244 def wrapped(*args, **kwargs):
311 save_findsource = inspect.findsource
245 save_findsource = inspect.findsource
312 save_getargs = inspect.getargs
313 inspect.findsource = findsource
246 inspect.findsource = findsource
314 inspect.getargs = getargs
315 try:
247 try:
316 return f(*args, **kwargs)
248 return f(*args, **kwargs)
317 finally:
249 finally:
318 inspect.findsource = save_findsource
250 inspect.findsource = save_findsource
319 inspect.getargs = save_getargs
320
251
321 return wrapped
252 return wrapped
322
253
323
254
324 def fix_frame_records_filenames(records):
255 def fix_frame_records_filenames(records):
325 """Try to fix the filenames in each record from inspect.getinnerframes().
256 """Try to fix the filenames in each record from inspect.getinnerframes().
326
257
327 Particularly, modules loaded from within zip files have useless filenames
258 Particularly, modules loaded from within zip files have useless filenames
328 attached to their code object, and inspect.getinnerframes() just uses it.
259 attached to their code object, and inspect.getinnerframes() just uses it.
329 """
260 """
330 fixed_records = []
261 fixed_records = []
331 for frame, filename, line_no, func_name, lines, index in records:
262 for frame, filename, line_no, func_name, lines, index in records:
332 # Look inside the frame's globals dictionary for __file__,
263 # Look inside the frame's globals dictionary for __file__,
333 # which should be better. However, keep Cython filenames since
264 # which should be better. However, keep Cython filenames since
334 # we prefer the source filenames over the compiled .so file.
265 # we prefer the source filenames over the compiled .so file.
335 if not filename.endswith(('.pyx', '.pxd', '.pxi')):
266 if not filename.endswith(('.pyx', '.pxd', '.pxi')):
336 better_fn = frame.f_globals.get('__file__', None)
267 better_fn = frame.f_globals.get('__file__', None)
337 if isinstance(better_fn, str):
268 if isinstance(better_fn, str):
338 # Check the type just in case someone did something weird with
269 # Check the type just in case someone did something weird with
339 # __file__. It might also be None if the error occurred during
270 # __file__. It might also be None if the error occurred during
340 # import.
271 # import.
341 filename = better_fn
272 filename = better_fn
342 fixed_records.append((frame, filename, line_no, func_name, lines, index))
273 fixed_records.append((frame, filename, line_no, func_name, lines, index))
343 return fixed_records
274 return fixed_records
344
275
345
276
346 @with_patch_inspect
277 @with_patch_inspect
347 def _fixed_getinnerframes(etb, context=1, tb_offset=0):
278 def _fixed_getinnerframes(etb, context=1, tb_offset=0):
348 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
279 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
349
280
350 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
281 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
351 # If the error is at the console, don't build any context, since it would
282 # If the error is at the console, don't build any context, since it would
352 # otherwise produce 5 blank lines printed out (there is no file at the
283 # otherwise produce 5 blank lines printed out (there is no file at the
353 # console)
284 # console)
354 rec_check = records[tb_offset:]
285 rec_check = records[tb_offset:]
355 try:
286 try:
356 rname = rec_check[0][1]
287 rname = rec_check[0][1]
357 if rname == '<ipython console>' or rname.endswith('<string>'):
288 if rname == '<ipython console>' or rname.endswith('<string>'):
358 return rec_check
289 return rec_check
359 except IndexError:
290 except IndexError:
360 pass
291 pass
361
292
362 aux = traceback.extract_tb(etb)
293 aux = traceback.extract_tb(etb)
363 assert len(records) == len(aux)
294 assert len(records) == len(aux)
364 for i, (file, lnum, _, _) in enumerate(aux):
295 for i, (file, lnum, _, _) in enumerate(aux):
365 maybeStart = lnum - 1 - context // 2
296 maybeStart = lnum - 1 - context // 2
366 start = max(maybeStart, 0)
297 start = max(maybeStart, 0)
367 end = start + context
298 end = start + context
368 lines = linecache.getlines(file)[start:end]
299 lines = linecache.getlines(file)[start:end]
369 buf = list(records[i])
300 buf = list(records[i])
370 buf[LNUM_POS] = lnum
301 buf[LNUM_POS] = lnum
371 buf[INDEX_POS] = lnum - 1 - start
302 buf[INDEX_POS] = lnum - 1 - start
372 buf[LINES_POS] = lines
303 buf[LINES_POS] = lines
373 records[i] = tuple(buf)
304 records[i] = tuple(buf)
374 return records[tb_offset:]
305 return records[tb_offset:]
375
306
376 # Helper function -- largely belongs to VerboseTB, but we need the same
307 # Helper function -- largely belongs to VerboseTB, but we need the same
377 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
308 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
378 # can be recognized properly by ipython.el's py-traceback-line-re
309 # can be recognized properly by ipython.el's py-traceback-line-re
379 # (SyntaxErrors have to be treated specially because they have no traceback)
310 # (SyntaxErrors have to be treated specially because they have no traceback)
380
311
381
312
382 def _format_traceback_lines(lnum, index, lines, Colors, lvals, _line_format):
313 def _format_traceback_lines(lnum, index, lines, Colors, lvals, _line_format):
383 """
314 """
384 Format tracebacks lines with pointing arrow, leading numbers...
315 Format tracebacks lines with pointing arrow, leading numbers...
385
316
386 Parameters
317 Parameters
387 ==========
318 ==========
388
319
389 lnum: int
320 lnum: int
390 index: int
321 index: int
391 lines: list[string]
322 lines: list[string]
392 Colors:
323 Colors:
393 ColorScheme used.
324 ColorScheme used.
394 lvals: bytes
325 lvals: bytes
395 Values of local variables, already colored, to inject just after the error line.
326 Values of local variables, already colored, to inject just after the error line.
396 _line_format: f (str) -> (str, bool)
327 _line_format: f (str) -> (str, bool)
397 return (colorized version of str, failure to do so)
328 return (colorized version of str, failure to do so)
398 """
329 """
399 numbers_width = INDENT_SIZE - 1
330 numbers_width = INDENT_SIZE - 1
400 res = []
331 res = []
401
332
402 for i,line in enumerate(lines, lnum-index):
333 for i,line in enumerate(lines, lnum-index):
403 line = py3compat.cast_unicode(line)
334 line = py3compat.cast_unicode(line)
404
335
405 new_line, err = _line_format(line, 'str')
336 new_line, err = _line_format(line, 'str')
406 if not err:
337 if not err:
407 line = new_line
338 line = new_line
408
339
409 if i == lnum:
340 if i == lnum:
410 # This is the line with the error
341 # This is the line with the error
411 pad = numbers_width - len(str(i))
342 pad = numbers_width - len(str(i))
412 num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
343 num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
413 line = '%s%s%s %s%s' % (Colors.linenoEm, num,
344 line = '%s%s%s %s%s' % (Colors.linenoEm, num,
414 Colors.line, line, Colors.Normal)
345 Colors.line, line, Colors.Normal)
415 else:
346 else:
416 num = '%*s' % (numbers_width, i)
347 num = '%*s' % (numbers_width, i)
417 line = '%s%s%s %s' % (Colors.lineno, num,
348 line = '%s%s%s %s' % (Colors.lineno, num,
418 Colors.Normal, line)
349 Colors.Normal, line)
419
350
420 res.append(line)
351 res.append(line)
421 if lvals and i == lnum:
352 if lvals and i == lnum:
422 res.append(lvals + '\n')
353 res.append(lvals + '\n')
423 return res
354 return res
424
355
425 def is_recursion_error(etype, value, records):
356 def is_recursion_error(etype, value, records):
426 try:
357 try:
427 # RecursionError is new in Python 3.5
358 # RecursionError is new in Python 3.5
428 recursion_error_type = RecursionError
359 recursion_error_type = RecursionError
429 except NameError:
360 except NameError:
430 recursion_error_type = RuntimeError
361 recursion_error_type = RuntimeError
431
362
432 # The default recursion limit is 1000, but some of that will be taken up
363 # The default recursion limit is 1000, but some of that will be taken up
433 # by stack frames in IPython itself. >500 frames probably indicates
364 # by stack frames in IPython itself. >500 frames probably indicates
434 # a recursion error.
365 # a recursion error.
435 return (etype is recursion_error_type) \
366 return (etype is recursion_error_type) \
436 and "recursion" in str(value).lower() \
367 and "recursion" in str(value).lower() \
437 and len(records) > _FRAME_RECURSION_LIMIT
368 and len(records) > _FRAME_RECURSION_LIMIT
438
369
439 def find_recursion(etype, value, records):
370 def find_recursion(etype, value, records):
440 """Identify the repeating stack frames from a RecursionError traceback
371 """Identify the repeating stack frames from a RecursionError traceback
441
372
442 'records' is a list as returned by VerboseTB.get_records()
373 'records' is a list as returned by VerboseTB.get_records()
443
374
444 Returns (last_unique, repeat_length)
375 Returns (last_unique, repeat_length)
445 """
376 """
446 # This involves a bit of guesswork - we want to show enough of the traceback
377 # This involves a bit of guesswork - we want to show enough of the traceback
447 # to indicate where the recursion is occurring. We guess that the innermost
378 # to indicate where the recursion is occurring. We guess that the innermost
448 # quarter of the traceback (250 frames by default) is repeats, and find the
379 # quarter of the traceback (250 frames by default) is repeats, and find the
449 # first frame (from in to out) that looks different.
380 # first frame (from in to out) that looks different.
450 if not is_recursion_error(etype, value, records):
381 if not is_recursion_error(etype, value, records):
451 return len(records), 0
382 return len(records), 0
452
383
453 # Select filename, lineno, func_name to track frames with
384 # Select filename, lineno, func_name to track frames with
454 records = [r[1:4] for r in records]
385 records = [r[1:4] for r in records]
455 inner_frames = records[-(len(records)//4):]
386 inner_frames = records[-(len(records)//4):]
456 frames_repeated = set(inner_frames)
387 frames_repeated = set(inner_frames)
457
388
458 last_seen_at = {}
389 last_seen_at = {}
459 longest_repeat = 0
390 longest_repeat = 0
460 i = len(records)
391 i = len(records)
461 for frame in reversed(records):
392 for frame in reversed(records):
462 i -= 1
393 i -= 1
463 if frame not in frames_repeated:
394 if frame not in frames_repeated:
464 last_unique = i
395 last_unique = i
465 break
396 break
466
397
467 if frame in last_seen_at:
398 if frame in last_seen_at:
468 distance = last_seen_at[frame] - i
399 distance = last_seen_at[frame] - i
469 longest_repeat = max(longest_repeat, distance)
400 longest_repeat = max(longest_repeat, distance)
470
401
471 last_seen_at[frame] = i
402 last_seen_at[frame] = i
472 else:
403 else:
473 last_unique = 0 # The whole traceback was recursion
404 last_unique = 0 # The whole traceback was recursion
474
405
475 return last_unique, longest_repeat
406 return last_unique, longest_repeat
476
407
477 #---------------------------------------------------------------------------
408 #---------------------------------------------------------------------------
478 # Module classes
409 # Module classes
479 class TBTools(colorable.Colorable):
410 class TBTools(colorable.Colorable):
480 """Basic tools used by all traceback printer classes."""
411 """Basic tools used by all traceback printer classes."""
481
412
482 # Number of frames to skip when reporting tracebacks
413 # Number of frames to skip when reporting tracebacks
483 tb_offset = 0
414 tb_offset = 0
484
415
485 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
416 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
486 # Whether to call the interactive pdb debugger after printing
417 # Whether to call the interactive pdb debugger after printing
487 # tracebacks or not
418 # tracebacks or not
488 super(TBTools, self).__init__(parent=parent, config=config)
419 super(TBTools, self).__init__(parent=parent, config=config)
489 self.call_pdb = call_pdb
420 self.call_pdb = call_pdb
490
421
491 # Output stream to write to. Note that we store the original value in
422 # Output stream to write to. Note that we store the original value in
492 # a private attribute and then make the public ostream a property, so
423 # a private attribute and then make the public ostream a property, so
493 # that we can delay accessing sys.stdout until runtime. The way
424 # that we can delay accessing sys.stdout until runtime. The way
494 # things are written now, the sys.stdout object is dynamically managed
425 # things are written now, the sys.stdout object is dynamically managed
495 # so a reference to it should NEVER be stored statically. This
426 # so a reference to it should NEVER be stored statically. This
496 # property approach confines this detail to a single location, and all
427 # property approach confines this detail to a single location, and all
497 # subclasses can simply access self.ostream for writing.
428 # subclasses can simply access self.ostream for writing.
498 self._ostream = ostream
429 self._ostream = ostream
499
430
500 # Create color table
431 # Create color table
501 self.color_scheme_table = exception_colors()
432 self.color_scheme_table = exception_colors()
502
433
503 self.set_colors(color_scheme)
434 self.set_colors(color_scheme)
504 self.old_scheme = color_scheme # save initial value for toggles
435 self.old_scheme = color_scheme # save initial value for toggles
505
436
506 if call_pdb:
437 if call_pdb:
507 self.pdb = debugger.Pdb()
438 self.pdb = debugger.Pdb()
508 else:
439 else:
509 self.pdb = None
440 self.pdb = None
510
441
511 def _get_ostream(self):
442 def _get_ostream(self):
512 """Output stream that exceptions are written to.
443 """Output stream that exceptions are written to.
513
444
514 Valid values are:
445 Valid values are:
515
446
516 - None: the default, which means that IPython will dynamically resolve
447 - None: the default, which means that IPython will dynamically resolve
517 to sys.stdout. This ensures compatibility with most tools, including
448 to sys.stdout. This ensures compatibility with most tools, including
518 Windows (where plain stdout doesn't recognize ANSI escapes).
449 Windows (where plain stdout doesn't recognize ANSI escapes).
519
450
520 - Any object with 'write' and 'flush' attributes.
451 - Any object with 'write' and 'flush' attributes.
521 """
452 """
522 return sys.stdout if self._ostream is None else self._ostream
453 return sys.stdout if self._ostream is None else self._ostream
523
454
524 def _set_ostream(self, val):
455 def _set_ostream(self, val):
525 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
456 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
526 self._ostream = val
457 self._ostream = val
527
458
528 ostream = property(_get_ostream, _set_ostream)
459 ostream = property(_get_ostream, _set_ostream)
529
460
530 def get_parts_of_chained_exception(self, evalue):
461 def get_parts_of_chained_exception(self, evalue):
531 def get_chained_exception(exception_value):
462 def get_chained_exception(exception_value):
532 cause = getattr(exception_value, '__cause__', None)
463 cause = getattr(exception_value, '__cause__', None)
533 if cause:
464 if cause:
534 return cause
465 return cause
535 if getattr(exception_value, '__suppress_context__', False):
466 if getattr(exception_value, '__suppress_context__', False):
536 return None
467 return None
537 return getattr(exception_value, '__context__', None)
468 return getattr(exception_value, '__context__', None)
538
469
539 chained_evalue = get_chained_exception(evalue)
470 chained_evalue = get_chained_exception(evalue)
540
471
541 if chained_evalue:
472 if chained_evalue:
542 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
473 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
543
474
544 def prepare_chained_exception_message(self, cause):
475 def prepare_chained_exception_message(self, cause):
545 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
476 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
546 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
477 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
547
478
548 if cause:
479 if cause:
549 message = [[direct_cause]]
480 message = [[direct_cause]]
550 else:
481 else:
551 message = [[exception_during_handling]]
482 message = [[exception_during_handling]]
552 return message
483 return message
553
484
554 def set_colors(self, *args, **kw):
485 def set_colors(self, *args, **kw):
555 """Shorthand access to the color table scheme selector method."""
486 """Shorthand access to the color table scheme selector method."""
556
487
557 # Set own color table
488 # Set own color table
558 self.color_scheme_table.set_active_scheme(*args, **kw)
489 self.color_scheme_table.set_active_scheme(*args, **kw)
559 # for convenience, set Colors to the active scheme
490 # for convenience, set Colors to the active scheme
560 self.Colors = self.color_scheme_table.active_colors
491 self.Colors = self.color_scheme_table.active_colors
561 # Also set colors of debugger
492 # Also set colors of debugger
562 if hasattr(self, 'pdb') and self.pdb is not None:
493 if hasattr(self, 'pdb') and self.pdb is not None:
563 self.pdb.set_colors(*args, **kw)
494 self.pdb.set_colors(*args, **kw)
564
495
565 def color_toggle(self):
496 def color_toggle(self):
566 """Toggle between the currently active color scheme and NoColor."""
497 """Toggle between the currently active color scheme and NoColor."""
567
498
568 if self.color_scheme_table.active_scheme_name == 'NoColor':
499 if self.color_scheme_table.active_scheme_name == 'NoColor':
569 self.color_scheme_table.set_active_scheme(self.old_scheme)
500 self.color_scheme_table.set_active_scheme(self.old_scheme)
570 self.Colors = self.color_scheme_table.active_colors
501 self.Colors = self.color_scheme_table.active_colors
571 else:
502 else:
572 self.old_scheme = self.color_scheme_table.active_scheme_name
503 self.old_scheme = self.color_scheme_table.active_scheme_name
573 self.color_scheme_table.set_active_scheme('NoColor')
504 self.color_scheme_table.set_active_scheme('NoColor')
574 self.Colors = self.color_scheme_table.active_colors
505 self.Colors = self.color_scheme_table.active_colors
575
506
576 def stb2text(self, stb):
507 def stb2text(self, stb):
577 """Convert a structured traceback (a list) to a string."""
508 """Convert a structured traceback (a list) to a string."""
578 return '\n'.join(stb)
509 return '\n'.join(stb)
579
510
580 def text(self, etype, value, tb, tb_offset=None, context=5):
511 def text(self, etype, value, tb, tb_offset=None, context=5):
581 """Return formatted traceback.
512 """Return formatted traceback.
582
513
583 Subclasses may override this if they add extra arguments.
514 Subclasses may override this if they add extra arguments.
584 """
515 """
585 tb_list = self.structured_traceback(etype, value, tb,
516 tb_list = self.structured_traceback(etype, value, tb,
586 tb_offset, context)
517 tb_offset, context)
587 return self.stb2text(tb_list)
518 return self.stb2text(tb_list)
588
519
589 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
520 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
590 context=5, mode=None):
521 context=5, mode=None):
591 """Return a list of traceback frames.
522 """Return a list of traceback frames.
592
523
593 Must be implemented by each class.
524 Must be implemented by each class.
594 """
525 """
595 raise NotImplementedError()
526 raise NotImplementedError()
596
527
597
528
598 #---------------------------------------------------------------------------
529 #---------------------------------------------------------------------------
599 class ListTB(TBTools):
530 class ListTB(TBTools):
600 """Print traceback information from a traceback list, with optional color.
531 """Print traceback information from a traceback list, with optional color.
601
532
602 Calling requires 3 arguments: (etype, evalue, elist)
533 Calling requires 3 arguments: (etype, evalue, elist)
603 as would be obtained by::
534 as would be obtained by::
604
535
605 etype, evalue, tb = sys.exc_info()
536 etype, evalue, tb = sys.exc_info()
606 if tb:
537 if tb:
607 elist = traceback.extract_tb(tb)
538 elist = traceback.extract_tb(tb)
608 else:
539 else:
609 elist = None
540 elist = None
610
541
611 It can thus be used by programs which need to process the traceback before
542 It can thus be used by programs which need to process the traceback before
612 printing (such as console replacements based on the code module from the
543 printing (such as console replacements based on the code module from the
613 standard library).
544 standard library).
614
545
615 Because they are meant to be called without a full traceback (only a
546 Because they are meant to be called without a full traceback (only a
616 list), instances of this class can't call the interactive pdb debugger."""
547 list), instances of this class can't call the interactive pdb debugger."""
617
548
618 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
549 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
619 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
550 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
620 ostream=ostream, parent=parent,config=config)
551 ostream=ostream, parent=parent,config=config)
621
552
622 def __call__(self, etype, value, elist):
553 def __call__(self, etype, value, elist):
623 self.ostream.flush()
554 self.ostream.flush()
624 self.ostream.write(self.text(etype, value, elist))
555 self.ostream.write(self.text(etype, value, elist))
625 self.ostream.write('\n')
556 self.ostream.write('\n')
626
557
627 def _extract_tb(self, tb):
558 def _extract_tb(self, tb):
628 if tb:
559 if tb:
629 return traceback.extract_tb(tb)
560 return traceback.extract_tb(tb)
630 else:
561 else:
631 return None
562 return None
632
563
633 def structured_traceback(self, etype, evalue, etb=None, tb_offset=None,
564 def structured_traceback(self, etype, evalue, etb=None, tb_offset=None,
634 context=5):
565 context=5):
635 """Return a color formatted string with the traceback info.
566 """Return a color formatted string with the traceback info.
636
567
637 Parameters
568 Parameters
638 ----------
569 ----------
639 etype : exception type
570 etype : exception type
640 Type of the exception raised.
571 Type of the exception raised.
641
572
642 evalue : object
573 evalue : object
643 Data stored in the exception
574 Data stored in the exception
644
575
645 etb : object
576 etb : object
646 If list: List of frames, see class docstring for details.
577 If list: List of frames, see class docstring for details.
647 If Traceback: Traceback of the exception.
578 If Traceback: Traceback of the exception.
648
579
649 tb_offset : int, optional
580 tb_offset : int, optional
650 Number of frames in the traceback to skip. If not given, the
581 Number of frames in the traceback to skip. If not given, the
651 instance evalue is used (set in constructor).
582 instance evalue is used (set in constructor).
652
583
653 context : int, optional
584 context : int, optional
654 Number of lines of context information to print.
585 Number of lines of context information to print.
655
586
656 Returns
587 Returns
657 -------
588 -------
658 String with formatted exception.
589 String with formatted exception.
659 """
590 """
660 # This is a workaround to get chained_exc_ids in recursive calls
591 # This is a workaround to get chained_exc_ids in recursive calls
661 # etb should not be a tuple if structured_traceback is not recursive
592 # etb should not be a tuple if structured_traceback is not recursive
662 if isinstance(etb, tuple):
593 if isinstance(etb, tuple):
663 etb, chained_exc_ids = etb
594 etb, chained_exc_ids = etb
664 else:
595 else:
665 chained_exc_ids = set()
596 chained_exc_ids = set()
666
597
667 if isinstance(etb, list):
598 if isinstance(etb, list):
668 elist = etb
599 elist = etb
669 elif etb is not None:
600 elif etb is not None:
670 elist = self._extract_tb(etb)
601 elist = self._extract_tb(etb)
671 else:
602 else:
672 elist = []
603 elist = []
673 tb_offset = self.tb_offset if tb_offset is None else tb_offset
604 tb_offset = self.tb_offset if tb_offset is None else tb_offset
674 Colors = self.Colors
605 Colors = self.Colors
675 out_list = []
606 out_list = []
676 if elist:
607 if elist:
677
608
678 if tb_offset and len(elist) > tb_offset:
609 if tb_offset and len(elist) > tb_offset:
679 elist = elist[tb_offset:]
610 elist = elist[tb_offset:]
680
611
681 out_list.append('Traceback %s(most recent call last)%s:' %
612 out_list.append('Traceback %s(most recent call last)%s:' %
682 (Colors.normalEm, Colors.Normal) + '\n')
613 (Colors.normalEm, Colors.Normal) + '\n')
683 out_list.extend(self._format_list(elist))
614 out_list.extend(self._format_list(elist))
684 # The exception info should be a single entry in the list.
615 # The exception info should be a single entry in the list.
685 lines = ''.join(self._format_exception_only(etype, evalue))
616 lines = ''.join(self._format_exception_only(etype, evalue))
686 out_list.append(lines)
617 out_list.append(lines)
687
618
688 exception = self.get_parts_of_chained_exception(evalue)
619 exception = self.get_parts_of_chained_exception(evalue)
689
620
690 if exception and not id(exception[1]) in chained_exc_ids:
621 if exception and not id(exception[1]) in chained_exc_ids:
691 chained_exception_message = self.prepare_chained_exception_message(
622 chained_exception_message = self.prepare_chained_exception_message(
692 evalue.__cause__)[0]
623 evalue.__cause__)[0]
693 etype, evalue, etb = exception
624 etype, evalue, etb = exception
694 # Trace exception to avoid infinite 'cause' loop
625 # Trace exception to avoid infinite 'cause' loop
695 chained_exc_ids.add(id(exception[1]))
626 chained_exc_ids.add(id(exception[1]))
696 chained_exceptions_tb_offset = 0
627 chained_exceptions_tb_offset = 0
697 out_list = (
628 out_list = (
698 self.structured_traceback(
629 self.structured_traceback(
699 etype, evalue, (etb, chained_exc_ids),
630 etype, evalue, (etb, chained_exc_ids),
700 chained_exceptions_tb_offset, context)
631 chained_exceptions_tb_offset, context)
701 + chained_exception_message
632 + chained_exception_message
702 + out_list)
633 + out_list)
703
634
704 return out_list
635 return out_list
705
636
706 def _format_list(self, extracted_list):
637 def _format_list(self, extracted_list):
707 """Format a list of traceback entry tuples for printing.
638 """Format a list of traceback entry tuples for printing.
708
639
709 Given a list of tuples as returned by extract_tb() or
640 Given a list of tuples as returned by extract_tb() or
710 extract_stack(), return a list of strings ready for printing.
641 extract_stack(), return a list of strings ready for printing.
711 Each string in the resulting list corresponds to the item with the
642 Each string in the resulting list corresponds to the item with the
712 same index in the argument list. Each string ends in a newline;
643 same index in the argument list. Each string ends in a newline;
713 the strings may contain internal newlines as well, for those items
644 the strings may contain internal newlines as well, for those items
714 whose source text line is not None.
645 whose source text line is not None.
715
646
716 Lifted almost verbatim from traceback.py
647 Lifted almost verbatim from traceback.py
717 """
648 """
718
649
719 Colors = self.Colors
650 Colors = self.Colors
720 list = []
651 list = []
721 for filename, lineno, name, line in extracted_list[:-1]:
652 for filename, lineno, name, line in extracted_list[:-1]:
722 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
653 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
723 (Colors.filename, filename, Colors.Normal,
654 (Colors.filename, filename, Colors.Normal,
724 Colors.lineno, lineno, Colors.Normal,
655 Colors.lineno, lineno, Colors.Normal,
725 Colors.name, name, Colors.Normal)
656 Colors.name, name, Colors.Normal)
726 if line:
657 if line:
727 item += ' %s\n' % line.strip()
658 item += ' %s\n' % line.strip()
728 list.append(item)
659 list.append(item)
729 # Emphasize the last entry
660 # Emphasize the last entry
730 filename, lineno, name, line = extracted_list[-1]
661 filename, lineno, name, line = extracted_list[-1]
731 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
662 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
732 (Colors.normalEm,
663 (Colors.normalEm,
733 Colors.filenameEm, filename, Colors.normalEm,
664 Colors.filenameEm, filename, Colors.normalEm,
734 Colors.linenoEm, lineno, Colors.normalEm,
665 Colors.linenoEm, lineno, Colors.normalEm,
735 Colors.nameEm, name, Colors.normalEm,
666 Colors.nameEm, name, Colors.normalEm,
736 Colors.Normal)
667 Colors.Normal)
737 if line:
668 if line:
738 item += '%s %s%s\n' % (Colors.line, line.strip(),
669 item += '%s %s%s\n' % (Colors.line, line.strip(),
739 Colors.Normal)
670 Colors.Normal)
740 list.append(item)
671 list.append(item)
741 return list
672 return list
742
673
743 def _format_exception_only(self, etype, value):
674 def _format_exception_only(self, etype, value):
744 """Format the exception part of a traceback.
675 """Format the exception part of a traceback.
745
676
746 The arguments are the exception type and value such as given by
677 The arguments are the exception type and value such as given by
747 sys.exc_info()[:2]. The return value is a list of strings, each ending
678 sys.exc_info()[:2]. The return value is a list of strings, each ending
748 in a newline. Normally, the list contains a single string; however,
679 in a newline. Normally, the list contains a single string; however,
749 for SyntaxError exceptions, it contains several lines that (when
680 for SyntaxError exceptions, it contains several lines that (when
750 printed) display detailed information about where the syntax error
681 printed) display detailed information about where the syntax error
751 occurred. The message indicating which exception occurred is the
682 occurred. The message indicating which exception occurred is the
752 always last string in the list.
683 always last string in the list.
753
684
754 Also lifted nearly verbatim from traceback.py
685 Also lifted nearly verbatim from traceback.py
755 """
686 """
756 have_filedata = False
687 have_filedata = False
757 Colors = self.Colors
688 Colors = self.Colors
758 list = []
689 list = []
759 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
690 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
760 if value is None:
691 if value is None:
761 # Not sure if this can still happen in Python 2.6 and above
692 # Not sure if this can still happen in Python 2.6 and above
762 list.append(stype + '\n')
693 list.append(stype + '\n')
763 else:
694 else:
764 if issubclass(etype, SyntaxError):
695 if issubclass(etype, SyntaxError):
765 have_filedata = True
696 have_filedata = True
766 if not value.filename: value.filename = "<string>"
697 if not value.filename: value.filename = "<string>"
767 if value.lineno:
698 if value.lineno:
768 lineno = value.lineno
699 lineno = value.lineno
769 textline = linecache.getline(value.filename, value.lineno)
700 textline = linecache.getline(value.filename, value.lineno)
770 else:
701 else:
771 lineno = 'unknown'
702 lineno = 'unknown'
772 textline = ''
703 textline = ''
773 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
704 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
774 (Colors.normalEm,
705 (Colors.normalEm,
775 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
706 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
776 Colors.linenoEm, lineno, Colors.Normal ))
707 Colors.linenoEm, lineno, Colors.Normal ))
777 if textline == '':
708 if textline == '':
778 textline = py3compat.cast_unicode(value.text, "utf-8")
709 textline = py3compat.cast_unicode(value.text, "utf-8")
779
710
780 if textline is not None:
711 if textline is not None:
781 i = 0
712 i = 0
782 while i < len(textline) and textline[i].isspace():
713 while i < len(textline) and textline[i].isspace():
783 i += 1
714 i += 1
784 list.append('%s %s%s\n' % (Colors.line,
715 list.append('%s %s%s\n' % (Colors.line,
785 textline.strip(),
716 textline.strip(),
786 Colors.Normal))
717 Colors.Normal))
787 if value.offset is not None:
718 if value.offset is not None:
788 s = ' '
719 s = ' '
789 for c in textline[i:value.offset - 1]:
720 for c in textline[i:value.offset - 1]:
790 if c.isspace():
721 if c.isspace():
791 s += c
722 s += c
792 else:
723 else:
793 s += ' '
724 s += ' '
794 list.append('%s%s^%s\n' % (Colors.caret, s,
725 list.append('%s%s^%s\n' % (Colors.caret, s,
795 Colors.Normal))
726 Colors.Normal))
796
727
797 try:
728 try:
798 s = value.msg
729 s = value.msg
799 except Exception:
730 except Exception:
800 s = self._some_str(value)
731 s = self._some_str(value)
801 if s:
732 if s:
802 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
733 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
803 Colors.Normal, s))
734 Colors.Normal, s))
804 else:
735 else:
805 list.append('%s\n' % stype)
736 list.append('%s\n' % stype)
806
737
807 # sync with user hooks
738 # sync with user hooks
808 if have_filedata:
739 if have_filedata:
809 ipinst = get_ipython()
740 ipinst = get_ipython()
810 if ipinst is not None:
741 if ipinst is not None:
811 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
742 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
812
743
813 return list
744 return list
814
745
815 def get_exception_only(self, etype, value):
746 def get_exception_only(self, etype, value):
816 """Only print the exception type and message, without a traceback.
747 """Only print the exception type and message, without a traceback.
817
748
818 Parameters
749 Parameters
819 ----------
750 ----------
820 etype : exception type
751 etype : exception type
821 value : exception value
752 value : exception value
822 """
753 """
823 return ListTB.structured_traceback(self, etype, value)
754 return ListTB.structured_traceback(self, etype, value)
824
755
825 def show_exception_only(self, etype, evalue):
756 def show_exception_only(self, etype, evalue):
826 """Only print the exception type and message, without a traceback.
757 """Only print the exception type and message, without a traceback.
827
758
828 Parameters
759 Parameters
829 ----------
760 ----------
830 etype : exception type
761 etype : exception type
831 value : exception value
762 value : exception value
832 """
763 """
833 # This method needs to use __call__ from *this* class, not the one from
764 # This method needs to use __call__ from *this* class, not the one from
834 # a subclass whose signature or behavior may be different
765 # a subclass whose signature or behavior may be different
835 ostream = self.ostream
766 ostream = self.ostream
836 ostream.flush()
767 ostream.flush()
837 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
768 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
838 ostream.flush()
769 ostream.flush()
839
770
840 def _some_str(self, value):
771 def _some_str(self, value):
841 # Lifted from traceback.py
772 # Lifted from traceback.py
842 try:
773 try:
843 return py3compat.cast_unicode(str(value))
774 return py3compat.cast_unicode(str(value))
844 except:
775 except:
845 return u'<unprintable %s object>' % type(value).__name__
776 return u'<unprintable %s object>' % type(value).__name__
846
777
847
778
848 #----------------------------------------------------------------------------
779 #----------------------------------------------------------------------------
849 class VerboseTB(TBTools):
780 class VerboseTB(TBTools):
850 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
781 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
851 of HTML. Requires inspect and pydoc. Crazy, man.
782 of HTML. Requires inspect and pydoc. Crazy, man.
852
783
853 Modified version which optionally strips the topmost entries from the
784 Modified version which optionally strips the topmost entries from the
854 traceback, to be used with alternate interpreters (because their own code
785 traceback, to be used with alternate interpreters (because their own code
855 would appear in the traceback)."""
786 would appear in the traceback)."""
856
787
857 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
788 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
858 tb_offset=0, long_header=False, include_vars=True,
789 tb_offset=0, long_header=False, include_vars=True,
859 check_cache=None, debugger_cls = None,
790 check_cache=None, debugger_cls = None,
860 parent=None, config=None):
791 parent=None, config=None):
861 """Specify traceback offset, headers and color scheme.
792 """Specify traceback offset, headers and color scheme.
862
793
863 Define how many frames to drop from the tracebacks. Calling it with
794 Define how many frames to drop from the tracebacks. Calling it with
864 tb_offset=1 allows use of this handler in interpreters which will have
795 tb_offset=1 allows use of this handler in interpreters which will have
865 their own code at the top of the traceback (VerboseTB will first
796 their own code at the top of the traceback (VerboseTB will first
866 remove that frame before printing the traceback info)."""
797 remove that frame before printing the traceback info)."""
867 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
798 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
868 ostream=ostream, parent=parent, config=config)
799 ostream=ostream, parent=parent, config=config)
869 self.tb_offset = tb_offset
800 self.tb_offset = tb_offset
870 self.long_header = long_header
801 self.long_header = long_header
871 self.include_vars = include_vars
802 self.include_vars = include_vars
872 # By default we use linecache.checkcache, but the user can provide a
803 # By default we use linecache.checkcache, but the user can provide a
873 # different check_cache implementation. This is used by the IPython
804 # different check_cache implementation. This is used by the IPython
874 # kernel to provide tracebacks for interactive code that is cached,
805 # kernel to provide tracebacks for interactive code that is cached,
875 # by a compiler instance that flushes the linecache but preserves its
806 # by a compiler instance that flushes the linecache but preserves its
876 # own code cache.
807 # own code cache.
877 if check_cache is None:
808 if check_cache is None:
878 check_cache = linecache.checkcache
809 check_cache = linecache.checkcache
879 self.check_cache = check_cache
810 self.check_cache = check_cache
880
811
881 self.debugger_cls = debugger_cls or debugger.Pdb
812 self.debugger_cls = debugger_cls or debugger.Pdb
882 self.skip_hidden = True
813 self.skip_hidden = True
883
814
884 def format_records(self, records, last_unique, recursion_repeat):
815 def format_records(self, records, last_unique, recursion_repeat):
885 """Format the stack frames of the traceback"""
816 """Format the stack frames of the traceback"""
886 frames = []
817 frames = []
887
818
888 skipped = 0
819 skipped = 0
889 lastrecord = len(records) - 1
820 lastrecord = len(records) - 1
890 for i, r in enumerate(records[: last_unique + recursion_repeat + 1]):
821 for i, r in enumerate(records[: last_unique + recursion_repeat + 1]):
891 if self.skip_hidden:
822 if self.skip_hidden:
892 if r[0].f_locals.get("__tracebackhide__", 0) and i != lastrecord:
823 if r[0].f_locals.get("__tracebackhide__", 0) and i != lastrecord:
893 skipped += 1
824 skipped += 1
894 continue
825 continue
895 if skipped:
826 if skipped:
896 Colors = self.Colors # just a shorthand + quicker name lookup
827 Colors = self.Colors # just a shorthand + quicker name lookup
897 ColorsNormal = Colors.Normal # used a lot
828 ColorsNormal = Colors.Normal # used a lot
898 frames.append(
829 frames.append(
899 " %s[... skipping hidden %s frame]%s\n"
830 " %s[... skipping hidden %s frame]%s\n"
900 % (Colors.excName, skipped, ColorsNormal)
831 % (Colors.excName, skipped, ColorsNormal)
901 )
832 )
902 skipped = 0
833 skipped = 0
903
834
904 frames.append(self.format_record(*r))
835 frames.append(self.format_record(*r))
905
836
906 if skipped:
837 if skipped:
907 Colors = self.Colors # just a shorthand + quicker name lookup
838 Colors = self.Colors # just a shorthand + quicker name lookup
908 ColorsNormal = Colors.Normal # used a lot
839 ColorsNormal = Colors.Normal # used a lot
909 frames.append(
840 frames.append(
910 " %s[... skipping hidden %s frame]%s\n"
841 " %s[... skipping hidden %s frame]%s\n"
911 % (Colors.excName, skipped, ColorsNormal)
842 % (Colors.excName, skipped, ColorsNormal)
912 )
843 )
913
844
914 if recursion_repeat:
845 if recursion_repeat:
915 frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat)
846 frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat)
916 frames.append(self.format_record(*records[last_unique+recursion_repeat+1]))
847 frames.append(self.format_record(*records[last_unique+recursion_repeat+1]))
917
848
918 return frames
849 return frames
919
850
920 def format_record(self, frame, file, lnum, func, lines, index):
851 def format_record(self, frame, file, lnum, func, lines, index):
921 """Format a single stack frame"""
852 """Format a single stack frame"""
922 Colors = self.Colors # just a shorthand + quicker name lookup
853 Colors = self.Colors # just a shorthand + quicker name lookup
923 ColorsNormal = Colors.Normal # used a lot
854 ColorsNormal = Colors.Normal # used a lot
924 col_scheme = self.color_scheme_table.active_scheme_name
855 col_scheme = self.color_scheme_table.active_scheme_name
925 indent = ' ' * INDENT_SIZE
856 indent = ' ' * INDENT_SIZE
926 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
857 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
927 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
858 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
928 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
859 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
929 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
860 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
930 ColorsNormal)
861 ColorsNormal)
931 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
862 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
932 (Colors.vName, Colors.valEm, ColorsNormal)
863 (Colors.vName, Colors.valEm, ColorsNormal)
933 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
864 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
934 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
865 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
935 Colors.vName, ColorsNormal)
866 Colors.vName, ColorsNormal)
936 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
867 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
937
868
938 if not file:
869 if not file:
939 file = '?'
870 file = '?'
940 elif file.startswith(str("<")) and file.endswith(str(">")):
871 elif file.startswith(str("<")) and file.endswith(str(">")):
941 # Not a real filename, no problem...
872 # Not a real filename, no problem...
942 pass
873 pass
943 elif not os.path.isabs(file):
874 elif not os.path.isabs(file):
944 # Try to make the filename absolute by trying all
875 # Try to make the filename absolute by trying all
945 # sys.path entries (which is also what linecache does)
876 # sys.path entries (which is also what linecache does)
946 for dirname in sys.path:
877 for dirname in sys.path:
947 try:
878 try:
948 fullname = os.path.join(dirname, file)
879 fullname = os.path.join(dirname, file)
949 if os.path.isfile(fullname):
880 if os.path.isfile(fullname):
950 file = os.path.abspath(fullname)
881 file = os.path.abspath(fullname)
951 break
882 break
952 except Exception:
883 except Exception:
953 # Just in case that sys.path contains very
884 # Just in case that sys.path contains very
954 # strange entries...
885 # strange entries...
955 pass
886 pass
956
887
957 file = py3compat.cast_unicode(file, util_path.fs_encoding)
888 file = py3compat.cast_unicode(file, util_path.fs_encoding)
958 link = tpl_link % util_path.compress_user(file)
889 link = tpl_link % util_path.compress_user(file)
959 args, varargs, varkw, locals_ = inspect.getargvalues(frame)
890 args, varargs, varkw, locals_ = inspect.getargvalues(frame)
960
891
961 if func == '?':
892 if func == '?':
962 call = ''
893 call = ''
963 elif func == '<module>':
894 elif func == '<module>':
964 call = tpl_call % (func, '')
895 call = tpl_call % (func, '')
965 else:
896 else:
966 # Decide whether to include variable details or not
897 # Decide whether to include variable details or not
967 var_repr = eqrepr if self.include_vars else nullrepr
898 var_repr = eqrepr if self.include_vars else nullrepr
968 try:
899 try:
969 call = tpl_call % (func, inspect.formatargvalues(args,
900 call = tpl_call % (func, inspect.formatargvalues(args,
970 varargs, varkw,
901 varargs, varkw,
971 locals_, formatvalue=var_repr))
902 locals_, formatvalue=var_repr))
972 except KeyError:
903 except KeyError:
973 # This happens in situations like errors inside generator
904 # This happens in situations like errors inside generator
974 # expressions, where local variables are listed in the
905 # expressions, where local variables are listed in the
975 # line, but can't be extracted from the frame. I'm not
906 # line, but can't be extracted from the frame. I'm not
976 # 100% sure this isn't actually a bug in inspect itself,
907 # 100% sure this isn't actually a bug in inspect itself,
977 # but since there's no info for us to compute with, the
908 # but since there's no info for us to compute with, the
978 # best we can do is report the failure and move on. Here
909 # best we can do is report the failure and move on. Here
979 # we must *not* call any traceback construction again,
910 # we must *not* call any traceback construction again,
980 # because that would mess up use of %debug later on. So we
911 # because that would mess up use of %debug later on. So we
981 # simply report the failure and move on. The only
912 # simply report the failure and move on. The only
982 # limitation will be that this frame won't have locals
913 # limitation will be that this frame won't have locals
983 # listed in the call signature. Quite subtle problem...
914 # listed in the call signature. Quite subtle problem...
984 # I can't think of a good way to validate this in a unit
915 # I can't think of a good way to validate this in a unit
985 # test, but running a script consisting of:
916 # test, but running a script consisting of:
986 # dict( (k,v.strip()) for (k,v) in range(10) )
917 # dict( (k,v.strip()) for (k,v) in range(10) )
987 # will illustrate the error, if this exception catch is
918 # will illustrate the error, if this exception catch is
988 # disabled.
919 # disabled.
989 call = tpl_call_fail % func
920 call = tpl_call_fail % func
990
921
991 # Don't attempt to tokenize binary files.
922 # Don't attempt to tokenize binary files.
992 if file.endswith(('.so', '.pyd', '.dll')):
923 if file.endswith(('.so', '.pyd', '.dll')):
993 return '%s %s\n' % (link, call)
924 return '%s %s\n' % (link, call)
994
925
995 elif file.endswith(('.pyc', '.pyo')):
926 elif file.endswith(('.pyc', '.pyo')):
996 # Look up the corresponding source file.
927 # Look up the corresponding source file.
997 try:
928 try:
998 file = source_from_cache(file)
929 file = source_from_cache(file)
999 except ValueError:
930 except ValueError:
1000 # Failed to get the source file for some reason
931 # Failed to get the source file for some reason
1001 # E.g. https://github.com/ipython/ipython/issues/9486
932 # E.g. https://github.com/ipython/ipython/issues/9486
1002 return '%s %s\n' % (link, call)
933 return '%s %s\n' % (link, call)
1003
934
1004 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
935 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
1005 line = getline(file, lnum[0])
936 line = getline(file, lnum[0])
1006 lnum[0] += 1
937 lnum[0] += 1
1007 return line
938 return line
1008
939
1009 # Build the list of names on this line of code where the exception
940 # Build the list of names on this line of code where the exception
1010 # occurred.
941 # occurred.
1011 try:
942 try:
1012 names = []
943 names = []
1013 name_cont = False
944 name_cont = False
1014
945
1015 for token_type, token, start, end, line in generate_tokens(linereader):
946 for token_type, token, start, end, line in generate_tokens(linereader):
1016 # build composite names
947 # build composite names
1017 if token_type == tokenize.NAME and token not in keyword.kwlist:
948 if token_type == tokenize.NAME and token not in keyword.kwlist:
1018 if name_cont:
949 if name_cont:
1019 # Continuation of a dotted name
950 # Continuation of a dotted name
1020 try:
951 try:
1021 names[-1].append(token)
952 names[-1].append(token)
1022 except IndexError:
953 except IndexError:
1023 names.append([token])
954 names.append([token])
1024 name_cont = False
955 name_cont = False
1025 else:
956 else:
1026 # Regular new names. We append everything, the caller
957 # Regular new names. We append everything, the caller
1027 # will be responsible for pruning the list later. It's
958 # will be responsible for pruning the list later. It's
1028 # very tricky to try to prune as we go, b/c composite
959 # very tricky to try to prune as we go, b/c composite
1029 # names can fool us. The pruning at the end is easy
960 # names can fool us. The pruning at the end is easy
1030 # to do (or the caller can print a list with repeated
961 # to do (or the caller can print a list with repeated
1031 # names if so desired.
962 # names if so desired.
1032 names.append([token])
963 names.append([token])
1033 elif token == '.':
964 elif token == '.':
1034 name_cont = True
965 name_cont = True
1035 elif token_type == tokenize.NEWLINE:
966 elif token_type == tokenize.NEWLINE:
1036 break
967 break
1037
968
1038 except (IndexError, UnicodeDecodeError, SyntaxError):
969 except (IndexError, UnicodeDecodeError, SyntaxError):
1039 # signals exit of tokenizer
970 # signals exit of tokenizer
1040 # SyntaxError can occur if the file is not actually Python
971 # SyntaxError can occur if the file is not actually Python
1041 # - see gh-6300
972 # - see gh-6300
1042 pass
973 pass
1043 except tokenize.TokenError as msg:
974 except tokenize.TokenError as msg:
1044 # Tokenizing may fail for various reasons, many of which are
975 # Tokenizing may fail for various reasons, many of which are
1045 # harmless. (A good example is when the line in question is the
976 # harmless. (A good example is when the line in question is the
1046 # close of a triple-quoted string, cf gh-6864). We don't want to
977 # close of a triple-quoted string, cf gh-6864). We don't want to
1047 # show this to users, but want make it available for debugging
978 # show this to users, but want make it available for debugging
1048 # purposes.
979 # purposes.
1049 _m = ("An unexpected error occurred while tokenizing input\n"
980 _m = ("An unexpected error occurred while tokenizing input\n"
1050 "The following traceback may be corrupted or invalid\n"
981 "The following traceback may be corrupted or invalid\n"
1051 "The error message is: %s\n" % msg)
982 "The error message is: %s\n" % msg)
1052 debug(_m)
983 debug(_m)
1053
984
1054 # Join composite names (e.g. "dict.fromkeys")
985 # Join composite names (e.g. "dict.fromkeys")
1055 names = ['.'.join(n) for n in names]
986 names = ['.'.join(n) for n in names]
1056 # prune names list of duplicates, but keep the right order
987 # prune names list of duplicates, but keep the right order
1057 unique_names = uniq_stable(names)
988 unique_names = uniq_stable(names)
1058
989
1059 # Start loop over vars
990 # Start loop over vars
1060 lvals = ''
991 lvals = ''
1061 lvals_list = []
992 lvals_list = []
1062 if self.include_vars:
993 if self.include_vars:
1063 for name_full in unique_names:
994 for name_full in unique_names:
1064 name_base = name_full.split('.', 1)[0]
995 name_base = name_full.split('.', 1)[0]
1065 if name_base in frame.f_code.co_varnames:
996 if name_base in frame.f_code.co_varnames:
1066 if name_base in locals_:
997 if name_base in locals_:
1067 try:
998 try:
1068 value = repr(eval(name_full, locals_))
999 value = repr(eval(name_full, locals_))
1069 except:
1000 except:
1070 value = undefined
1001 value = undefined
1071 else:
1002 else:
1072 value = undefined
1003 value = undefined
1073 name = tpl_local_var % name_full
1004 name = tpl_local_var % name_full
1074 else:
1005 else:
1075 if name_base in frame.f_globals:
1006 if name_base in frame.f_globals:
1076 try:
1007 try:
1077 value = repr(eval(name_full, frame.f_globals))
1008 value = repr(eval(name_full, frame.f_globals))
1078 except:
1009 except:
1079 value = undefined
1010 value = undefined
1080 else:
1011 else:
1081 value = undefined
1012 value = undefined
1082 name = tpl_global_var % name_full
1013 name = tpl_global_var % name_full
1083 lvals_list.append(tpl_name_val % (name, value))
1014 lvals_list.append(tpl_name_val % (name, value))
1084 if lvals_list:
1015 if lvals_list:
1085 lvals = '%s%s' % (indent, em_normal.join(lvals_list))
1016 lvals = '%s%s' % (indent, em_normal.join(lvals_list))
1086
1017
1087 level = '%s %s\n' % (link, call)
1018 level = '%s %s\n' % (link, call)
1088
1019
1089 if index is None:
1020 if index is None:
1090 return level
1021 return level
1091 else:
1022 else:
1092 _line_format = PyColorize.Parser(style=col_scheme, parent=self).format2
1023 _line_format = PyColorize.Parser(style=col_scheme, parent=self).format2
1093 return '%s%s' % (level, ''.join(
1024 return '%s%s' % (level, ''.join(
1094 _format_traceback_lines(lnum, index, lines, Colors, lvals,
1025 _format_traceback_lines(lnum, index, lines, Colors, lvals,
1095 _line_format)))
1026 _line_format)))
1096
1027
1097 def prepare_header(self, etype, long_version=False):
1028 def prepare_header(self, etype, long_version=False):
1098 colors = self.Colors # just a shorthand + quicker name lookup
1029 colors = self.Colors # just a shorthand + quicker name lookup
1099 colorsnormal = colors.Normal # used a lot
1030 colorsnormal = colors.Normal # used a lot
1100 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
1031 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
1101 width = min(75, get_terminal_size()[0])
1032 width = min(75, get_terminal_size()[0])
1102 if long_version:
1033 if long_version:
1103 # Header with the exception type, python version, and date
1034 # Header with the exception type, python version, and date
1104 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
1035 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
1105 date = time.ctime(time.time())
1036 date = time.ctime(time.time())
1106
1037
1107 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
1038 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
1108 exc, ' ' * (width - len(str(etype)) - len(pyver)),
1039 exc, ' ' * (width - len(str(etype)) - len(pyver)),
1109 pyver, date.rjust(width) )
1040 pyver, date.rjust(width) )
1110 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
1041 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
1111 "\ncalls leading up to the error, with the most recent (innermost) call last."
1042 "\ncalls leading up to the error, with the most recent (innermost) call last."
1112 else:
1043 else:
1113 # Simplified header
1044 # Simplified header
1114 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
1045 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
1115 rjust(width - len(str(etype))) )
1046 rjust(width - len(str(etype))) )
1116
1047
1117 return head
1048 return head
1118
1049
1119 def format_exception(self, etype, evalue):
1050 def format_exception(self, etype, evalue):
1120 colors = self.Colors # just a shorthand + quicker name lookup
1051 colors = self.Colors # just a shorthand + quicker name lookup
1121 colorsnormal = colors.Normal # used a lot
1052 colorsnormal = colors.Normal # used a lot
1122 # Get (safely) a string form of the exception info
1053 # Get (safely) a string form of the exception info
1123 try:
1054 try:
1124 etype_str, evalue_str = map(str, (etype, evalue))
1055 etype_str, evalue_str = map(str, (etype, evalue))
1125 except:
1056 except:
1126 # User exception is improperly defined.
1057 # User exception is improperly defined.
1127 etype, evalue = str, sys.exc_info()[:2]
1058 etype, evalue = str, sys.exc_info()[:2]
1128 etype_str, evalue_str = map(str, (etype, evalue))
1059 etype_str, evalue_str = map(str, (etype, evalue))
1129 # ... and format it
1060 # ... and format it
1130 return ['%s%s%s: %s' % (colors.excName, etype_str,
1061 return ['%s%s%s: %s' % (colors.excName, etype_str,
1131 colorsnormal, py3compat.cast_unicode(evalue_str))]
1062 colorsnormal, py3compat.cast_unicode(evalue_str))]
1132
1063
1133 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
1064 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
1134 """Formats the header, traceback and exception message for a single exception.
1065 """Formats the header, traceback and exception message for a single exception.
1135
1066
1136 This may be called multiple times by Python 3 exception chaining
1067 This may be called multiple times by Python 3 exception chaining
1137 (PEP 3134).
1068 (PEP 3134).
1138 """
1069 """
1139 # some locals
1070 # some locals
1140 orig_etype = etype
1071 orig_etype = etype
1141 try:
1072 try:
1142 etype = etype.__name__
1073 etype = etype.__name__
1143 except AttributeError:
1074 except AttributeError:
1144 pass
1075 pass
1145
1076
1146 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1077 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1147 head = self.prepare_header(etype, self.long_header)
1078 head = self.prepare_header(etype, self.long_header)
1148 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
1079 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
1149
1080
1150
1081
1151 last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
1082 last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
1152
1083
1153 frames = self.format_records(records, last_unique, recursion_repeat)
1084 frames = self.format_records(records, last_unique, recursion_repeat)
1154
1085
1155 formatted_exception = self.format_exception(etype, evalue)
1086 formatted_exception = self.format_exception(etype, evalue)
1156 if records:
1087 if records:
1157 filepath, lnum = records[-1][1:3]
1088 filepath, lnum = records[-1][1:3]
1158 filepath = os.path.abspath(filepath)
1089 filepath = os.path.abspath(filepath)
1159 ipinst = get_ipython()
1090 ipinst = get_ipython()
1160 if ipinst is not None:
1091 if ipinst is not None:
1161 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
1092 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
1162
1093
1163 return [[head] + frames + [''.join(formatted_exception[0])]]
1094 return [[head] + frames + [''.join(formatted_exception[0])]]
1164
1095
1165 def get_records(self, etb, number_of_lines_of_context, tb_offset):
1096 def get_records(self, etb, number_of_lines_of_context, tb_offset):
1166 try:
1097 try:
1167 # Try the default getinnerframes and Alex's: Alex's fixes some
1098 # Try the default getinnerframes and Alex's: Alex's fixes some
1168 # problems, but it generates empty tracebacks for console errors
1099 # problems, but it generates empty tracebacks for console errors
1169 # (5 blanks lines) where none should be returned.
1100 # (5 blanks lines) where none should be returned.
1170 return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
1101 return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
1171 except UnicodeDecodeError:
1102 except UnicodeDecodeError:
1172 # This can occur if a file's encoding magic comment is wrong.
1103 # This can occur if a file's encoding magic comment is wrong.
1173 # I can't see a way to recover without duplicating a bunch of code
1104 # I can't see a way to recover without duplicating a bunch of code
1174 # from the stdlib traceback module. --TK
1105 # from the stdlib traceback module. --TK
1175 error('\nUnicodeDecodeError while processing traceback.\n')
1106 error('\nUnicodeDecodeError while processing traceback.\n')
1176 return None
1107 return None
1177 except:
1108 except:
1178 # FIXME: I've been getting many crash reports from python 2.3
1109 # FIXME: I've been getting many crash reports from python 2.3
1179 # users, traceable to inspect.py. If I can find a small test-case
1110 # users, traceable to inspect.py. If I can find a small test-case
1180 # to reproduce this, I should either write a better workaround or
1111 # to reproduce this, I should either write a better workaround or
1181 # file a bug report against inspect (if that's the real problem).
1112 # file a bug report against inspect (if that's the real problem).
1182 # So far, I haven't been able to find an isolated example to
1113 # So far, I haven't been able to find an isolated example to
1183 # reproduce the problem.
1114 # reproduce the problem.
1184 inspect_error()
1115 inspect_error()
1185 traceback.print_exc(file=self.ostream)
1116 traceback.print_exc(file=self.ostream)
1186 info('\nUnfortunately, your original traceback can not be constructed.\n')
1117 info('\nUnfortunately, your original traceback can not be constructed.\n')
1187 return None
1118 return None
1188
1119
1189 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
1120 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
1190 number_of_lines_of_context=5):
1121 number_of_lines_of_context=5):
1191 """Return a nice text document describing the traceback."""
1122 """Return a nice text document describing the traceback."""
1192
1123
1193 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
1124 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
1194 tb_offset)
1125 tb_offset)
1195
1126
1196 colors = self.Colors # just a shorthand + quicker name lookup
1127 colors = self.Colors # just a shorthand + quicker name lookup
1197 colorsnormal = colors.Normal # used a lot
1128 colorsnormal = colors.Normal # used a lot
1198 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
1129 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
1199 structured_traceback_parts = [head]
1130 structured_traceback_parts = [head]
1200 chained_exceptions_tb_offset = 0
1131 chained_exceptions_tb_offset = 0
1201 lines_of_context = 3
1132 lines_of_context = 3
1202 formatted_exceptions = formatted_exception
1133 formatted_exceptions = formatted_exception
1203 exception = self.get_parts_of_chained_exception(evalue)
1134 exception = self.get_parts_of_chained_exception(evalue)
1204 if exception:
1135 if exception:
1205 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1136 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1206 etype, evalue, etb = exception
1137 etype, evalue, etb = exception
1207 else:
1138 else:
1208 evalue = None
1139 evalue = None
1209 chained_exc_ids = set()
1140 chained_exc_ids = set()
1210 while evalue:
1141 while evalue:
1211 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
1142 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
1212 chained_exceptions_tb_offset)
1143 chained_exceptions_tb_offset)
1213 exception = self.get_parts_of_chained_exception(evalue)
1144 exception = self.get_parts_of_chained_exception(evalue)
1214
1145
1215 if exception and not id(exception[1]) in chained_exc_ids:
1146 if exception and not id(exception[1]) in chained_exc_ids:
1216 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
1147 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
1217 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1148 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1218 etype, evalue, etb = exception
1149 etype, evalue, etb = exception
1219 else:
1150 else:
1220 evalue = None
1151 evalue = None
1221
1152
1222 # we want to see exceptions in a reversed order:
1153 # we want to see exceptions in a reversed order:
1223 # the first exception should be on top
1154 # the first exception should be on top
1224 for formatted_exception in reversed(formatted_exceptions):
1155 for formatted_exception in reversed(formatted_exceptions):
1225 structured_traceback_parts += formatted_exception
1156 structured_traceback_parts += formatted_exception
1226
1157
1227 return structured_traceback_parts
1158 return structured_traceback_parts
1228
1159
1229 def debugger(self, force=False):
1160 def debugger(self, force=False):
1230 """Call up the pdb debugger if desired, always clean up the tb
1161 """Call up the pdb debugger if desired, always clean up the tb
1231 reference.
1162 reference.
1232
1163
1233 Keywords:
1164 Keywords:
1234
1165
1235 - force(False): by default, this routine checks the instance call_pdb
1166 - force(False): by default, this routine checks the instance call_pdb
1236 flag and does not actually invoke the debugger if the flag is false.
1167 flag and does not actually invoke the debugger if the flag is false.
1237 The 'force' option forces the debugger to activate even if the flag
1168 The 'force' option forces the debugger to activate even if the flag
1238 is false.
1169 is false.
1239
1170
1240 If the call_pdb flag is set, the pdb interactive debugger is
1171 If the call_pdb flag is set, the pdb interactive debugger is
1241 invoked. In all cases, the self.tb reference to the current traceback
1172 invoked. In all cases, the self.tb reference to the current traceback
1242 is deleted to prevent lingering references which hamper memory
1173 is deleted to prevent lingering references which hamper memory
1243 management.
1174 management.
1244
1175
1245 Note that each call to pdb() does an 'import readline', so if your app
1176 Note that each call to pdb() does an 'import readline', so if your app
1246 requires a special setup for the readline completers, you'll have to
1177 requires a special setup for the readline completers, you'll have to
1247 fix that by hand after invoking the exception handler."""
1178 fix that by hand after invoking the exception handler."""
1248
1179
1249 if force or self.call_pdb:
1180 if force or self.call_pdb:
1250 if self.pdb is None:
1181 if self.pdb is None:
1251 self.pdb = self.debugger_cls()
1182 self.pdb = self.debugger_cls()
1252 # the system displayhook may have changed, restore the original
1183 # the system displayhook may have changed, restore the original
1253 # for pdb
1184 # for pdb
1254 display_trap = DisplayTrap(hook=sys.__displayhook__)
1185 display_trap = DisplayTrap(hook=sys.__displayhook__)
1255 with display_trap:
1186 with display_trap:
1256 self.pdb.reset()
1187 self.pdb.reset()
1257 # Find the right frame so we don't pop up inside ipython itself
1188 # Find the right frame so we don't pop up inside ipython itself
1258 if hasattr(self, 'tb') and self.tb is not None:
1189 if hasattr(self, 'tb') and self.tb is not None:
1259 etb = self.tb
1190 etb = self.tb
1260 else:
1191 else:
1261 etb = self.tb = sys.last_traceback
1192 etb = self.tb = sys.last_traceback
1262 while self.tb is not None and self.tb.tb_next is not None:
1193 while self.tb is not None and self.tb.tb_next is not None:
1263 self.tb = self.tb.tb_next
1194 self.tb = self.tb.tb_next
1264 if etb and etb.tb_next:
1195 if etb and etb.tb_next:
1265 etb = etb.tb_next
1196 etb = etb.tb_next
1266 self.pdb.botframe = etb.tb_frame
1197 self.pdb.botframe = etb.tb_frame
1267 self.pdb.interaction(None, etb)
1198 self.pdb.interaction(None, etb)
1268
1199
1269 if hasattr(self, 'tb'):
1200 if hasattr(self, 'tb'):
1270 del self.tb
1201 del self.tb
1271
1202
1272 def handler(self, info=None):
1203 def handler(self, info=None):
1273 (etype, evalue, etb) = info or sys.exc_info()
1204 (etype, evalue, etb) = info or sys.exc_info()
1274 self.tb = etb
1205 self.tb = etb
1275 ostream = self.ostream
1206 ostream = self.ostream
1276 ostream.flush()
1207 ostream.flush()
1277 ostream.write(self.text(etype, evalue, etb))
1208 ostream.write(self.text(etype, evalue, etb))
1278 ostream.write('\n')
1209 ostream.write('\n')
1279 ostream.flush()
1210 ostream.flush()
1280
1211
1281 # Changed so an instance can just be called as VerboseTB_inst() and print
1212 # Changed so an instance can just be called as VerboseTB_inst() and print
1282 # out the right info on its own.
1213 # out the right info on its own.
1283 def __call__(self, etype=None, evalue=None, etb=None):
1214 def __call__(self, etype=None, evalue=None, etb=None):
1284 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1215 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1285 if etb is None:
1216 if etb is None:
1286 self.handler()
1217 self.handler()
1287 else:
1218 else:
1288 self.handler((etype, evalue, etb))
1219 self.handler((etype, evalue, etb))
1289 try:
1220 try:
1290 self.debugger()
1221 self.debugger()
1291 except KeyboardInterrupt:
1222 except KeyboardInterrupt:
1292 print("\nKeyboardInterrupt")
1223 print("\nKeyboardInterrupt")
1293
1224
1294
1225
1295 #----------------------------------------------------------------------------
1226 #----------------------------------------------------------------------------
1296 class FormattedTB(VerboseTB, ListTB):
1227 class FormattedTB(VerboseTB, ListTB):
1297 """Subclass ListTB but allow calling with a traceback.
1228 """Subclass ListTB but allow calling with a traceback.
1298
1229
1299 It can thus be used as a sys.excepthook for Python > 2.1.
1230 It can thus be used as a sys.excepthook for Python > 2.1.
1300
1231
1301 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1232 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1302
1233
1303 Allows a tb_offset to be specified. This is useful for situations where
1234 Allows a tb_offset to be specified. This is useful for situations where
1304 one needs to remove a number of topmost frames from the traceback (such as
1235 one needs to remove a number of topmost frames from the traceback (such as
1305 occurs with python programs that themselves execute other python code,
1236 occurs with python programs that themselves execute other python code,
1306 like Python shells). """
1237 like Python shells). """
1307
1238
1308 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1239 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1309 ostream=None,
1240 ostream=None,
1310 tb_offset=0, long_header=False, include_vars=False,
1241 tb_offset=0, long_header=False, include_vars=False,
1311 check_cache=None, debugger_cls=None,
1242 check_cache=None, debugger_cls=None,
1312 parent=None, config=None):
1243 parent=None, config=None):
1313
1244
1314 # NEVER change the order of this list. Put new modes at the end:
1245 # NEVER change the order of this list. Put new modes at the end:
1315 self.valid_modes = ['Plain', 'Context', 'Verbose', 'Minimal']
1246 self.valid_modes = ['Plain', 'Context', 'Verbose', 'Minimal']
1316 self.verbose_modes = self.valid_modes[1:3]
1247 self.verbose_modes = self.valid_modes[1:3]
1317
1248
1318 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1249 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1319 ostream=ostream, tb_offset=tb_offset,
1250 ostream=ostream, tb_offset=tb_offset,
1320 long_header=long_header, include_vars=include_vars,
1251 long_header=long_header, include_vars=include_vars,
1321 check_cache=check_cache, debugger_cls=debugger_cls,
1252 check_cache=check_cache, debugger_cls=debugger_cls,
1322 parent=parent, config=config)
1253 parent=parent, config=config)
1323
1254
1324 # Different types of tracebacks are joined with different separators to
1255 # Different types of tracebacks are joined with different separators to
1325 # form a single string. They are taken from this dict
1256 # form a single string. They are taken from this dict
1326 self._join_chars = dict(Plain='', Context='\n', Verbose='\n',
1257 self._join_chars = dict(Plain='', Context='\n', Verbose='\n',
1327 Minimal='')
1258 Minimal='')
1328 # set_mode also sets the tb_join_char attribute
1259 # set_mode also sets the tb_join_char attribute
1329 self.set_mode(mode)
1260 self.set_mode(mode)
1330
1261
1331 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
1262 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
1332 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1263 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1333 mode = self.mode
1264 mode = self.mode
1334 if mode in self.verbose_modes:
1265 if mode in self.verbose_modes:
1335 # Verbose modes need a full traceback
1266 # Verbose modes need a full traceback
1336 return VerboseTB.structured_traceback(
1267 return VerboseTB.structured_traceback(
1337 self, etype, value, tb, tb_offset, number_of_lines_of_context
1268 self, etype, value, tb, tb_offset, number_of_lines_of_context
1338 )
1269 )
1339 elif mode == 'Minimal':
1270 elif mode == 'Minimal':
1340 return ListTB.get_exception_only(self, etype, value)
1271 return ListTB.get_exception_only(self, etype, value)
1341 else:
1272 else:
1342 # We must check the source cache because otherwise we can print
1273 # We must check the source cache because otherwise we can print
1343 # out-of-date source code.
1274 # out-of-date source code.
1344 self.check_cache()
1275 self.check_cache()
1345 # Now we can extract and format the exception
1276 # Now we can extract and format the exception
1346 return ListTB.structured_traceback(
1277 return ListTB.structured_traceback(
1347 self, etype, value, tb, tb_offset, number_of_lines_of_context
1278 self, etype, value, tb, tb_offset, number_of_lines_of_context
1348 )
1279 )
1349
1280
1350 def stb2text(self, stb):
1281 def stb2text(self, stb):
1351 """Convert a structured traceback (a list) to a string."""
1282 """Convert a structured traceback (a list) to a string."""
1352 return self.tb_join_char.join(stb)
1283 return self.tb_join_char.join(stb)
1353
1284
1354
1285
1355 def set_mode(self, mode=None):
1286 def set_mode(self, mode=None):
1356 """Switch to the desired mode.
1287 """Switch to the desired mode.
1357
1288
1358 If mode is not specified, cycles through the available modes."""
1289 If mode is not specified, cycles through the available modes."""
1359
1290
1360 if not mode:
1291 if not mode:
1361 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
1292 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
1362 len(self.valid_modes)
1293 len(self.valid_modes)
1363 self.mode = self.valid_modes[new_idx]
1294 self.mode = self.valid_modes[new_idx]
1364 elif mode not in self.valid_modes:
1295 elif mode not in self.valid_modes:
1365 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
1296 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
1366 'Valid modes: ' + str(self.valid_modes))
1297 'Valid modes: ' + str(self.valid_modes))
1367 else:
1298 else:
1368 self.mode = mode
1299 self.mode = mode
1369 # include variable details only in 'Verbose' mode
1300 # include variable details only in 'Verbose' mode
1370 self.include_vars = (self.mode == self.valid_modes[2])
1301 self.include_vars = (self.mode == self.valid_modes[2])
1371 # Set the join character for generating text tracebacks
1302 # Set the join character for generating text tracebacks
1372 self.tb_join_char = self._join_chars[self.mode]
1303 self.tb_join_char = self._join_chars[self.mode]
1373
1304
1374 # some convenient shortcuts
1305 # some convenient shortcuts
1375 def plain(self):
1306 def plain(self):
1376 self.set_mode(self.valid_modes[0])
1307 self.set_mode(self.valid_modes[0])
1377
1308
1378 def context(self):
1309 def context(self):
1379 self.set_mode(self.valid_modes[1])
1310 self.set_mode(self.valid_modes[1])
1380
1311
1381 def verbose(self):
1312 def verbose(self):
1382 self.set_mode(self.valid_modes[2])
1313 self.set_mode(self.valid_modes[2])
1383
1314
1384 def minimal(self):
1315 def minimal(self):
1385 self.set_mode(self.valid_modes[3])
1316 self.set_mode(self.valid_modes[3])
1386
1317
1387
1318
1388 #----------------------------------------------------------------------------
1319 #----------------------------------------------------------------------------
1389 class AutoFormattedTB(FormattedTB):
1320 class AutoFormattedTB(FormattedTB):
1390 """A traceback printer which can be called on the fly.
1321 """A traceback printer which can be called on the fly.
1391
1322
1392 It will find out about exceptions by itself.
1323 It will find out about exceptions by itself.
1393
1324
1394 A brief example::
1325 A brief example::
1395
1326
1396 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1327 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1397 try:
1328 try:
1398 ...
1329 ...
1399 except:
1330 except:
1400 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1331 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1401 """
1332 """
1402
1333
1403 def __call__(self, etype=None, evalue=None, etb=None,
1334 def __call__(self, etype=None, evalue=None, etb=None,
1404 out=None, tb_offset=None):
1335 out=None, tb_offset=None):
1405 """Print out a formatted exception traceback.
1336 """Print out a formatted exception traceback.
1406
1337
1407 Optional arguments:
1338 Optional arguments:
1408 - out: an open file-like object to direct output to.
1339 - out: an open file-like object to direct output to.
1409
1340
1410 - tb_offset: the number of frames to skip over in the stack, on a
1341 - tb_offset: the number of frames to skip over in the stack, on a
1411 per-call basis (this overrides temporarily the instance's tb_offset
1342 per-call basis (this overrides temporarily the instance's tb_offset
1412 given at initialization time. """
1343 given at initialization time. """
1413
1344
1414 if out is None:
1345 if out is None:
1415 out = self.ostream
1346 out = self.ostream
1416 out.flush()
1347 out.flush()
1417 out.write(self.text(etype, evalue, etb, tb_offset))
1348 out.write(self.text(etype, evalue, etb, tb_offset))
1418 out.write('\n')
1349 out.write('\n')
1419 out.flush()
1350 out.flush()
1420 # FIXME: we should remove the auto pdb behavior from here and leave
1351 # FIXME: we should remove the auto pdb behavior from here and leave
1421 # that to the clients.
1352 # that to the clients.
1422 try:
1353 try:
1423 self.debugger()
1354 self.debugger()
1424 except KeyboardInterrupt:
1355 except KeyboardInterrupt:
1425 print("\nKeyboardInterrupt")
1356 print("\nKeyboardInterrupt")
1426
1357
1427 def structured_traceback(self, etype=None, value=None, tb=None,
1358 def structured_traceback(self, etype=None, value=None, tb=None,
1428 tb_offset=None, number_of_lines_of_context=5):
1359 tb_offset=None, number_of_lines_of_context=5):
1429 if etype is None:
1360 if etype is None:
1430 etype, value, tb = sys.exc_info()
1361 etype, value, tb = sys.exc_info()
1431 if isinstance(tb, tuple):
1362 if isinstance(tb, tuple):
1432 # tb is a tuple if this is a chained exception.
1363 # tb is a tuple if this is a chained exception.
1433 self.tb = tb[0]
1364 self.tb = tb[0]
1434 else:
1365 else:
1435 self.tb = tb
1366 self.tb = tb
1436 return FormattedTB.structured_traceback(
1367 return FormattedTB.structured_traceback(
1437 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1368 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1438
1369
1439
1370
1440 #---------------------------------------------------------------------------
1371 #---------------------------------------------------------------------------
1441
1372
1442 # A simple class to preserve Nathan's original functionality.
1373 # A simple class to preserve Nathan's original functionality.
1443 class ColorTB(FormattedTB):
1374 class ColorTB(FormattedTB):
1444 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1375 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1445
1376
1446 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1377 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1447 FormattedTB.__init__(self, color_scheme=color_scheme,
1378 FormattedTB.__init__(self, color_scheme=color_scheme,
1448 call_pdb=call_pdb, **kwargs)
1379 call_pdb=call_pdb, **kwargs)
1449
1380
1450
1381
1451 class SyntaxTB(ListTB):
1382 class SyntaxTB(ListTB):
1452 """Extension which holds some state: the last exception value"""
1383 """Extension which holds some state: the last exception value"""
1453
1384
1454 def __init__(self, color_scheme='NoColor', parent=None, config=None):
1385 def __init__(self, color_scheme='NoColor', parent=None, config=None):
1455 ListTB.__init__(self, color_scheme, parent=parent, config=config)
1386 ListTB.__init__(self, color_scheme, parent=parent, config=config)
1456 self.last_syntax_error = None
1387 self.last_syntax_error = None
1457
1388
1458 def __call__(self, etype, value, elist):
1389 def __call__(self, etype, value, elist):
1459 self.last_syntax_error = value
1390 self.last_syntax_error = value
1460
1391
1461 ListTB.__call__(self, etype, value, elist)
1392 ListTB.__call__(self, etype, value, elist)
1462
1393
1463 def structured_traceback(self, etype, value, elist, tb_offset=None,
1394 def structured_traceback(self, etype, value, elist, tb_offset=None,
1464 context=5):
1395 context=5):
1465 # If the source file has been edited, the line in the syntax error can
1396 # If the source file has been edited, the line in the syntax error can
1466 # be wrong (retrieved from an outdated cache). This replaces it with
1397 # be wrong (retrieved from an outdated cache). This replaces it with
1467 # the current value.
1398 # the current value.
1468 if isinstance(value, SyntaxError) \
1399 if isinstance(value, SyntaxError) \
1469 and isinstance(value.filename, str) \
1400 and isinstance(value.filename, str) \
1470 and isinstance(value.lineno, int):
1401 and isinstance(value.lineno, int):
1471 linecache.checkcache(value.filename)
1402 linecache.checkcache(value.filename)
1472 newtext = linecache.getline(value.filename, value.lineno)
1403 newtext = linecache.getline(value.filename, value.lineno)
1473 if newtext:
1404 if newtext:
1474 value.text = newtext
1405 value.text = newtext
1475 self.last_syntax_error = value
1406 self.last_syntax_error = value
1476 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1407 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1477 tb_offset=tb_offset, context=context)
1408 tb_offset=tb_offset, context=context)
1478
1409
1479 def clear_err_state(self):
1410 def clear_err_state(self):
1480 """Return the current error state and clear it"""
1411 """Return the current error state and clear it"""
1481 e = self.last_syntax_error
1412 e = self.last_syntax_error
1482 self.last_syntax_error = None
1413 self.last_syntax_error = None
1483 return e
1414 return e
1484
1415
1485 def stb2text(self, stb):
1416 def stb2text(self, stb):
1486 """Convert a structured traceback (a list) to a string."""
1417 """Convert a structured traceback (a list) to a string."""
1487 return ''.join(stb)
1418 return ''.join(stb)
1488
1419
1489
1420
1490 # some internal-use functions
1421 # some internal-use functions
1491 def text_repr(value):
1422 def text_repr(value):
1492 """Hopefully pretty robust repr equivalent."""
1423 """Hopefully pretty robust repr equivalent."""
1493 # this is pretty horrible but should always return *something*
1424 # this is pretty horrible but should always return *something*
1494 try:
1425 try:
1495 return pydoc.text.repr(value)
1426 return pydoc.text.repr(value)
1496 except KeyboardInterrupt:
1427 except KeyboardInterrupt:
1497 raise
1428 raise
1498 except:
1429 except:
1499 try:
1430 try:
1500 return repr(value)
1431 return repr(value)
1501 except KeyboardInterrupt:
1432 except KeyboardInterrupt:
1502 raise
1433 raise
1503 except:
1434 except:
1504 try:
1435 try:
1505 # all still in an except block so we catch
1436 # all still in an except block so we catch
1506 # getattr raising
1437 # getattr raising
1507 name = getattr(value, '__name__', None)
1438 name = getattr(value, '__name__', None)
1508 if name:
1439 if name:
1509 # ick, recursion
1440 # ick, recursion
1510 return text_repr(name)
1441 return text_repr(name)
1511 klass = getattr(value, '__class__', None)
1442 klass = getattr(value, '__class__', None)
1512 if klass:
1443 if klass:
1513 return '%s instance' % text_repr(klass)
1444 return '%s instance' % text_repr(klass)
1514 except KeyboardInterrupt:
1445 except KeyboardInterrupt:
1515 raise
1446 raise
1516 except:
1447 except:
1517 return 'UNRECOVERABLE REPR FAILURE'
1448 return 'UNRECOVERABLE REPR FAILURE'
1518
1449
1519
1450
1520 def eqrepr(value, repr=text_repr):
1451 def eqrepr(value, repr=text_repr):
1521 return '=%s' % repr(value)
1452 return '=%s' % repr(value)
1522
1453
1523
1454
1524 def nullrepr(value, repr=text_repr):
1455 def nullrepr(value, repr=text_repr):
1525 return ''
1456 return ''
General Comments 0
You need to be logged in to leave comments. Login now