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