##// END OF EJS Templates
Merge pull request #13588 from Carreau/fix-etb-none...
Matthias Bussonnier -
r27594:d7cc335a merge
parent child Browse files
Show More
@@ -1,1194 +1,1194 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 inspect
93 93 import linecache
94 94 import pydoc
95 95 import sys
96 96 import time
97 97 import traceback
98 98 from types import TracebackType
99 99 from typing import Tuple, List, Any, Optional
100 100
101 101 import stack_data
102 102 from pygments.formatters.terminal256 import Terminal256Formatter
103 103 from pygments.styles import get_style_by_name
104 104
105 105 # IPython's own modules
106 106 from IPython import get_ipython
107 107 from IPython.core import debugger
108 108 from IPython.core.display_trap import DisplayTrap
109 109 from IPython.core.excolors import exception_colors
110 110 from IPython.utils import path as util_path
111 111 from IPython.utils import py3compat
112 112 from IPython.utils.terminal import get_terminal_size
113 113
114 114 import IPython.utils.colorable as colorable
115 115
116 116 # Globals
117 117 # amount of space to put line numbers before verbose tracebacks
118 118 INDENT_SIZE = 8
119 119
120 120 # Default color scheme. This is used, for example, by the traceback
121 121 # formatter. When running in an actual IPython instance, the user's rc.colors
122 122 # value is used, but having a module global makes this functionality available
123 123 # to users of ultratb who are NOT running inside ipython.
124 124 DEFAULT_SCHEME = 'NoColor'
125 125
126 126 # ---------------------------------------------------------------------------
127 127 # Code begins
128 128
129 129 # Helper function -- largely belongs to VerboseTB, but we need the same
130 130 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
131 131 # can be recognized properly by ipython.el's py-traceback-line-re
132 132 # (SyntaxErrors have to be treated specially because they have no traceback)
133 133
134 134
135 135 def _format_traceback_lines(lines, Colors, has_colors: bool, lvals):
136 136 """
137 137 Format tracebacks lines with pointing arrow, leading numbers...
138 138
139 139 Parameters
140 140 ----------
141 141 lines : list[Line]
142 142 Colors
143 143 ColorScheme used.
144 144 lvals : str
145 145 Values of local variables, already colored, to inject just after the error line.
146 146 """
147 147 numbers_width = INDENT_SIZE - 1
148 148 res = []
149 149
150 150 for stack_line in lines:
151 151 if stack_line is stack_data.LINE_GAP:
152 152 res.append('%s (...)%s\n' % (Colors.linenoEm, Colors.Normal))
153 153 continue
154 154
155 155 line = stack_line.render(pygmented=has_colors).rstrip('\n') + '\n'
156 156 lineno = stack_line.lineno
157 157 if stack_line.is_current:
158 158 # This is the line with the error
159 159 pad = numbers_width - len(str(lineno))
160 160 num = '%s%s' % (debugger.make_arrow(pad), str(lineno))
161 161 start_color = Colors.linenoEm
162 162 else:
163 163 num = '%*s' % (numbers_width, lineno)
164 164 start_color = Colors.lineno
165 165
166 166 line = '%s%s%s %s' % (start_color, num, Colors.Normal, line)
167 167
168 168 res.append(line)
169 169 if lvals and stack_line.is_current:
170 170 res.append(lvals + '\n')
171 171 return res
172 172
173 173
174 174 def _format_filename(file, ColorFilename, ColorNormal, *, lineno=None):
175 175 """
176 176 Format filename lines with `In [n]` if it's the nth code cell or `File *.py` if it's a module.
177 177
178 178 Parameters
179 179 ----------
180 180 file : str
181 181 ColorFilename
182 182 ColorScheme's filename coloring to be used.
183 183 ColorNormal
184 184 ColorScheme's normal coloring to be used.
185 185 """
186 186 ipinst = get_ipython()
187 187
188 188 if ipinst is not None and file in ipinst.compile._filename_map:
189 189 file = "[%s]" % ipinst.compile._filename_map[file]
190 190 tpl_link = f"Input {ColorFilename}In {{file}}{ColorNormal}"
191 191 else:
192 192 file = util_path.compress_user(
193 193 py3compat.cast_unicode(file, util_path.fs_encoding)
194 194 )
195 195 if lineno is None:
196 196 tpl_link = f"File {ColorFilename}{{file}}{ColorNormal}"
197 197 else:
198 198 tpl_link = f"File {ColorFilename}{{file}}:{{lineno}}{ColorNormal}"
199 199
200 200 return tpl_link.format(file=file, lineno=lineno)
201 201
202 202 #---------------------------------------------------------------------------
203 203 # Module classes
204 204 class TBTools(colorable.Colorable):
205 205 """Basic tools used by all traceback printer classes."""
206 206
207 207 # Number of frames to skip when reporting tracebacks
208 208 tb_offset = 0
209 209
210 210 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
211 211 # Whether to call the interactive pdb debugger after printing
212 212 # tracebacks or not
213 213 super(TBTools, self).__init__(parent=parent, config=config)
214 214 self.call_pdb = call_pdb
215 215
216 216 # Output stream to write to. Note that we store the original value in
217 217 # a private attribute and then make the public ostream a property, so
218 218 # that we can delay accessing sys.stdout until runtime. The way
219 219 # things are written now, the sys.stdout object is dynamically managed
220 220 # so a reference to it should NEVER be stored statically. This
221 221 # property approach confines this detail to a single location, and all
222 222 # subclasses can simply access self.ostream for writing.
223 223 self._ostream = ostream
224 224
225 225 # Create color table
226 226 self.color_scheme_table = exception_colors()
227 227
228 228 self.set_colors(color_scheme)
229 229 self.old_scheme = color_scheme # save initial value for toggles
230 230
231 231 if call_pdb:
232 232 self.pdb = debugger.Pdb()
233 233 else:
234 234 self.pdb = None
235 235
236 236 def _get_ostream(self):
237 237 """Output stream that exceptions are written to.
238 238
239 239 Valid values are:
240 240
241 241 - None: the default, which means that IPython will dynamically resolve
242 242 to sys.stdout. This ensures compatibility with most tools, including
243 243 Windows (where plain stdout doesn't recognize ANSI escapes).
244 244
245 245 - Any object with 'write' and 'flush' attributes.
246 246 """
247 247 return sys.stdout if self._ostream is None else self._ostream
248 248
249 249 def _set_ostream(self, val):
250 250 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
251 251 self._ostream = val
252 252
253 253 ostream = property(_get_ostream, _set_ostream)
254 254
255 255 @staticmethod
256 256 def _get_chained_exception(exception_value):
257 257 cause = getattr(exception_value, "__cause__", None)
258 258 if cause:
259 259 return cause
260 260 if getattr(exception_value, "__suppress_context__", False):
261 261 return None
262 262 return getattr(exception_value, "__context__", None)
263 263
264 264 def get_parts_of_chained_exception(
265 265 self, evalue
266 266 ) -> Optional[Tuple[type, BaseException, TracebackType]]:
267 267
268 268 chained_evalue = self._get_chained_exception(evalue)
269 269
270 270 if chained_evalue:
271 271 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
272 272 return None
273 273
274 274 def prepare_chained_exception_message(self, cause) -> List[Any]:
275 275 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
276 276 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
277 277
278 278 if cause:
279 279 message = [[direct_cause]]
280 280 else:
281 281 message = [[exception_during_handling]]
282 282 return message
283 283
284 284 @property
285 285 def has_colors(self) -> bool:
286 286 return self.color_scheme_table.active_scheme_name.lower() != "nocolor"
287 287
288 288 def set_colors(self, *args, **kw):
289 289 """Shorthand access to the color table scheme selector method."""
290 290
291 291 # Set own color table
292 292 self.color_scheme_table.set_active_scheme(*args, **kw)
293 293 # for convenience, set Colors to the active scheme
294 294 self.Colors = self.color_scheme_table.active_colors
295 295 # Also set colors of debugger
296 296 if hasattr(self, 'pdb') and self.pdb is not None:
297 297 self.pdb.set_colors(*args, **kw)
298 298
299 299 def color_toggle(self):
300 300 """Toggle between the currently active color scheme and NoColor."""
301 301
302 302 if self.color_scheme_table.active_scheme_name == 'NoColor':
303 303 self.color_scheme_table.set_active_scheme(self.old_scheme)
304 304 self.Colors = self.color_scheme_table.active_colors
305 305 else:
306 306 self.old_scheme = self.color_scheme_table.active_scheme_name
307 307 self.color_scheme_table.set_active_scheme('NoColor')
308 308 self.Colors = self.color_scheme_table.active_colors
309 309
310 310 def stb2text(self, stb):
311 311 """Convert a structured traceback (a list) to a string."""
312 312 return '\n'.join(stb)
313 313
314 314 def text(self, etype, value, tb, tb_offset: Optional[int] = None, context=5):
315 315 """Return formatted traceback.
316 316
317 317 Subclasses may override this if they add extra arguments.
318 318 """
319 319 tb_list = self.structured_traceback(etype, value, tb,
320 320 tb_offset, context)
321 321 return self.stb2text(tb_list)
322 322
323 323 def structured_traceback(
324 324 self, etype, evalue, tb, tb_offset: Optional[int] = None, context=5, mode=None
325 325 ):
326 326 """Return a list of traceback frames.
327 327
328 328 Must be implemented by each class.
329 329 """
330 330 raise NotImplementedError()
331 331
332 332
333 333 #---------------------------------------------------------------------------
334 334 class ListTB(TBTools):
335 335 """Print traceback information from a traceback list, with optional color.
336 336
337 337 Calling requires 3 arguments: (etype, evalue, elist)
338 338 as would be obtained by::
339 339
340 340 etype, evalue, tb = sys.exc_info()
341 341 if tb:
342 342 elist = traceback.extract_tb(tb)
343 343 else:
344 344 elist = None
345 345
346 346 It can thus be used by programs which need to process the traceback before
347 347 printing (such as console replacements based on the code module from the
348 348 standard library).
349 349
350 350 Because they are meant to be called without a full traceback (only a
351 351 list), instances of this class can't call the interactive pdb debugger."""
352 352
353 353 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
354 354 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
355 355 ostream=ostream, parent=parent,config=config)
356 356
357 357 def __call__(self, etype, value, elist):
358 358 self.ostream.flush()
359 359 self.ostream.write(self.text(etype, value, elist))
360 360 self.ostream.write('\n')
361 361
362 362 def _extract_tb(self, tb):
363 363 if tb:
364 364 return traceback.extract_tb(tb)
365 365 else:
366 366 return None
367 367
368 368 def structured_traceback(
369 369 self,
370 370 etype: type,
371 371 evalue: BaseException,
372 372 etb: Optional[TracebackType] = None,
373 373 tb_offset: Optional[int] = None,
374 374 context=5,
375 375 ):
376 376 """Return a color formatted string with the traceback info.
377 377
378 378 Parameters
379 379 ----------
380 380 etype : exception type
381 381 Type of the exception raised.
382 382 evalue : object
383 383 Data stored in the exception
384 384 etb : list | TracebackType | None
385 385 If list: List of frames, see class docstring for details.
386 386 If Traceback: Traceback of the exception.
387 387 tb_offset : int, optional
388 388 Number of frames in the traceback to skip. If not given, the
389 389 instance evalue is used (set in constructor).
390 390 context : int, optional
391 391 Number of lines of context information to print.
392 392
393 393 Returns
394 394 -------
395 395 String with formatted exception.
396 396 """
397 397 # This is a workaround to get chained_exc_ids in recursive calls
398 398 # etb should not be a tuple if structured_traceback is not recursive
399 399 if isinstance(etb, tuple):
400 400 etb, chained_exc_ids = etb
401 401 else:
402 402 chained_exc_ids = set()
403 403
404 404 if isinstance(etb, list):
405 405 elist = etb
406 406 elif etb is not None:
407 407 elist = self._extract_tb(etb)
408 408 else:
409 409 elist = []
410 410 tb_offset = self.tb_offset if tb_offset is None else tb_offset
411 411 assert isinstance(tb_offset, int)
412 412 Colors = self.Colors
413 413 out_list = []
414 414 if elist:
415 415
416 416 if tb_offset and len(elist) > tb_offset:
417 417 elist = elist[tb_offset:]
418 418
419 419 out_list.append('Traceback %s(most recent call last)%s:' %
420 420 (Colors.normalEm, Colors.Normal) + '\n')
421 421 out_list.extend(self._format_list(elist))
422 422 # The exception info should be a single entry in the list.
423 423 lines = ''.join(self._format_exception_only(etype, evalue))
424 424 out_list.append(lines)
425 425
426 426 exception = self.get_parts_of_chained_exception(evalue)
427 427
428 428 if exception and not id(exception[1]) in chained_exc_ids:
429 429 chained_exception_message = self.prepare_chained_exception_message(
430 430 evalue.__cause__)[0]
431 431 etype, evalue, etb = exception
432 432 # Trace exception to avoid infinite 'cause' loop
433 433 chained_exc_ids.add(id(exception[1]))
434 434 chained_exceptions_tb_offset = 0
435 435 out_list = (
436 436 self.structured_traceback(
437 437 etype, evalue, (etb, chained_exc_ids),
438 438 chained_exceptions_tb_offset, context)
439 439 + chained_exception_message
440 440 + out_list)
441 441
442 442 return out_list
443 443
444 444 def _format_list(self, extracted_list):
445 445 """Format a list of traceback entry tuples for printing.
446 446
447 447 Given a list of tuples as returned by extract_tb() or
448 448 extract_stack(), return a list of strings ready for printing.
449 449 Each string in the resulting list corresponds to the item with the
450 450 same index in the argument list. Each string ends in a newline;
451 451 the strings may contain internal newlines as well, for those items
452 452 whose source text line is not None.
453 453
454 454 Lifted almost verbatim from traceback.py
455 455 """
456 456
457 457 Colors = self.Colors
458 458 list = []
459 459 for filename, lineno, name, line in extracted_list[:-1]:
460 460 item = " %s in %s%s%s\n" % (
461 461 _format_filename(
462 462 filename, Colors.filename, Colors.Normal, lineno=lineno
463 463 ),
464 464 Colors.name,
465 465 name,
466 466 Colors.Normal,
467 467 )
468 468 if line:
469 469 item += ' %s\n' % line.strip()
470 470 list.append(item)
471 471 # Emphasize the last entry
472 472 filename, lineno, name, line = extracted_list[-1]
473 473 item = "%s %s in %s%s%s%s\n" % (
474 474 Colors.normalEm,
475 475 _format_filename(
476 476 filename, Colors.filenameEm, Colors.normalEm, lineno=lineno
477 477 ),
478 478 Colors.nameEm,
479 479 name,
480 480 Colors.normalEm,
481 481 Colors.Normal,
482 482 )
483 483 if line:
484 484 item += '%s %s%s\n' % (Colors.line, line.strip(),
485 485 Colors.Normal)
486 486 list.append(item)
487 487 return list
488 488
489 489 def _format_exception_only(self, etype, value):
490 490 """Format the exception part of a traceback.
491 491
492 492 The arguments are the exception type and value such as given by
493 493 sys.exc_info()[:2]. The return value is a list of strings, each ending
494 494 in a newline. Normally, the list contains a single string; however,
495 495 for SyntaxError exceptions, it contains several lines that (when
496 496 printed) display detailed information about where the syntax error
497 497 occurred. The message indicating which exception occurred is the
498 498 always last string in the list.
499 499
500 500 Also lifted nearly verbatim from traceback.py
501 501 """
502 502 have_filedata = False
503 503 Colors = self.Colors
504 504 list = []
505 505 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
506 506 if value is None:
507 507 # Not sure if this can still happen in Python 2.6 and above
508 508 list.append(stype + '\n')
509 509 else:
510 510 if issubclass(etype, SyntaxError):
511 511 have_filedata = True
512 512 if not value.filename: value.filename = "<string>"
513 513 if value.lineno:
514 514 lineno = value.lineno
515 515 textline = linecache.getline(value.filename, value.lineno)
516 516 else:
517 517 lineno = "unknown"
518 518 textline = ""
519 519 list.append(
520 520 "%s %s%s\n"
521 521 % (
522 522 Colors.normalEm,
523 523 _format_filename(
524 524 value.filename,
525 525 Colors.filenameEm,
526 526 Colors.normalEm,
527 527 lineno=(None if lineno == "unknown" else lineno),
528 528 ),
529 529 Colors.Normal,
530 530 )
531 531 )
532 532 if textline == "":
533 533 textline = py3compat.cast_unicode(value.text, "utf-8")
534 534
535 535 if textline is not None:
536 536 i = 0
537 537 while i < len(textline) and textline[i].isspace():
538 538 i += 1
539 539 list.append('%s %s%s\n' % (Colors.line,
540 540 textline.strip(),
541 541 Colors.Normal))
542 542 if value.offset is not None:
543 543 s = ' '
544 544 for c in textline[i:value.offset - 1]:
545 545 if c.isspace():
546 546 s += c
547 547 else:
548 548 s += ' '
549 549 list.append('%s%s^%s\n' % (Colors.caret, s,
550 550 Colors.Normal))
551 551
552 552 try:
553 553 s = value.msg
554 554 except Exception:
555 555 s = self._some_str(value)
556 556 if s:
557 557 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
558 558 Colors.Normal, s))
559 559 else:
560 560 list.append('%s\n' % stype)
561 561
562 562 # sync with user hooks
563 563 if have_filedata:
564 564 ipinst = get_ipython()
565 565 if ipinst is not None:
566 566 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
567 567
568 568 return list
569 569
570 570 def get_exception_only(self, etype, value):
571 571 """Only print the exception type and message, without a traceback.
572 572
573 573 Parameters
574 574 ----------
575 575 etype : exception type
576 576 value : exception value
577 577 """
578 578 return ListTB.structured_traceback(self, etype, value)
579 579
580 580 def show_exception_only(self, etype, evalue):
581 581 """Only print the exception type and message, without a traceback.
582 582
583 583 Parameters
584 584 ----------
585 585 etype : exception type
586 586 evalue : exception value
587 587 """
588 588 # This method needs to use __call__ from *this* class, not the one from
589 589 # a subclass whose signature or behavior may be different
590 590 ostream = self.ostream
591 591 ostream.flush()
592 592 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
593 593 ostream.flush()
594 594
595 595 def _some_str(self, value):
596 596 # Lifted from traceback.py
597 597 try:
598 598 return py3compat.cast_unicode(str(value))
599 599 except:
600 600 return u'<unprintable %s object>' % type(value).__name__
601 601
602 602
603 603 #----------------------------------------------------------------------------
604 604 class VerboseTB(TBTools):
605 605 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
606 606 of HTML. Requires inspect and pydoc. Crazy, man.
607 607
608 608 Modified version which optionally strips the topmost entries from the
609 609 traceback, to be used with alternate interpreters (because their own code
610 610 would appear in the traceback)."""
611 611
612 612 def __init__(
613 613 self,
614 614 color_scheme: str = "Linux",
615 615 call_pdb: bool = False,
616 616 ostream=None,
617 617 tb_offset: int = 0,
618 618 long_header: bool = False,
619 619 include_vars: bool = True,
620 620 check_cache=None,
621 621 debugger_cls=None,
622 622 parent=None,
623 623 config=None,
624 624 ):
625 625 """Specify traceback offset, headers and color scheme.
626 626
627 627 Define how many frames to drop from the tracebacks. Calling it with
628 628 tb_offset=1 allows use of this handler in interpreters which will have
629 629 their own code at the top of the traceback (VerboseTB will first
630 630 remove that frame before printing the traceback info)."""
631 631 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
632 632 ostream=ostream, parent=parent, config=config)
633 633 self.tb_offset = tb_offset
634 634 self.long_header = long_header
635 635 self.include_vars = include_vars
636 636 # By default we use linecache.checkcache, but the user can provide a
637 637 # different check_cache implementation. This is used by the IPython
638 638 # kernel to provide tracebacks for interactive code that is cached,
639 639 # by a compiler instance that flushes the linecache but preserves its
640 640 # own code cache.
641 641 if check_cache is None:
642 642 check_cache = linecache.checkcache
643 643 self.check_cache = check_cache
644 644
645 645 self.debugger_cls = debugger_cls or debugger.Pdb
646 646 self.skip_hidden = True
647 647
648 648 def format_record(self, frame_info):
649 649 """Format a single stack frame"""
650 650 Colors = self.Colors # just a shorthand + quicker name lookup
651 651 ColorsNormal = Colors.Normal # used a lot
652 652
653 653 if isinstance(frame_info, stack_data.RepeatedFrames):
654 654 return ' %s[... skipping similar frames: %s]%s\n' % (
655 655 Colors.excName, frame_info.description, ColorsNormal)
656 656
657 657 indent = " " * INDENT_SIZE
658 658 em_normal = "%s\n%s%s" % (Colors.valEm, indent, ColorsNormal)
659 659 tpl_call = f"in {Colors.vName}{{file}}{Colors.valEm}{{scope}}{ColorsNormal}"
660 660 tpl_call_fail = "in %s%%s%s(***failed resolving arguments***)%s" % (
661 661 Colors.vName,
662 662 Colors.valEm,
663 663 ColorsNormal,
664 664 )
665 665 tpl_name_val = "%%s %s= %%s%s" % (Colors.valEm, ColorsNormal)
666 666
667 667 link = _format_filename(
668 668 frame_info.filename,
669 669 Colors.filenameEm,
670 670 ColorsNormal,
671 671 lineno=frame_info.lineno,
672 672 )
673 673 args, varargs, varkw, locals_ = inspect.getargvalues(frame_info.frame)
674 674
675 675 func = frame_info.executing.code_qualname()
676 676 if func == "<module>":
677 677 call = tpl_call.format(file=func, scope="")
678 678 else:
679 679 # Decide whether to include variable details or not
680 680 var_repr = eqrepr if self.include_vars else nullrepr
681 681 try:
682 682 scope = inspect.formatargvalues(
683 683 args, varargs, varkw, locals_, formatvalue=var_repr
684 684 )
685 685 call = tpl_call.format(file=func, scope=scope)
686 686 except KeyError:
687 687 # This happens in situations like errors inside generator
688 688 # expressions, where local variables are listed in the
689 689 # line, but can't be extracted from the frame. I'm not
690 690 # 100% sure this isn't actually a bug in inspect itself,
691 691 # but since there's no info for us to compute with, the
692 692 # best we can do is report the failure and move on. Here
693 693 # we must *not* call any traceback construction again,
694 694 # because that would mess up use of %debug later on. So we
695 695 # simply report the failure and move on. The only
696 696 # limitation will be that this frame won't have locals
697 697 # listed in the call signature. Quite subtle problem...
698 698 # I can't think of a good way to validate this in a unit
699 699 # test, but running a script consisting of:
700 700 # dict( (k,v.strip()) for (k,v) in range(10) )
701 701 # will illustrate the error, if this exception catch is
702 702 # disabled.
703 703 call = tpl_call_fail % func
704 704
705 705 lvals = ''
706 706 lvals_list = []
707 707 if self.include_vars:
708 708 try:
709 709 # we likely want to fix stackdata at some point, but
710 710 # still need a workaround.
711 711 fibp = frame_info.variables_in_executing_piece
712 712 for var in fibp:
713 713 lvals_list.append(tpl_name_val % (var.name, repr(var.value)))
714 714 except Exception:
715 715 lvals_list.append(
716 716 "Exception trying to inspect frame. No more locals available."
717 717 )
718 718 if lvals_list:
719 719 lvals = '%s%s' % (indent, em_normal.join(lvals_list))
720 720
721 721 result = "%s, %s\n" % (link, call)
722 722
723 723 result += ''.join(_format_traceback_lines(frame_info.lines, Colors, self.has_colors, lvals))
724 724 return result
725 725
726 726 def prepare_header(self, etype, long_version=False):
727 727 colors = self.Colors # just a shorthand + quicker name lookup
728 728 colorsnormal = colors.Normal # used a lot
729 729 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
730 730 width = min(75, get_terminal_size()[0])
731 731 if long_version:
732 732 # Header with the exception type, python version, and date
733 733 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
734 734 date = time.ctime(time.time())
735 735
736 736 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
737 737 exc, ' ' * (width - len(str(etype)) - len(pyver)),
738 738 pyver, date.rjust(width) )
739 739 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
740 740 "\ncalls leading up to the error, with the most recent (innermost) call last."
741 741 else:
742 742 # Simplified header
743 743 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
744 744 rjust(width - len(str(etype))) )
745 745
746 746 return head
747 747
748 748 def format_exception(self, etype, evalue):
749 749 colors = self.Colors # just a shorthand + quicker name lookup
750 750 colorsnormal = colors.Normal # used a lot
751 751 # Get (safely) a string form of the exception info
752 752 try:
753 753 etype_str, evalue_str = map(str, (etype, evalue))
754 754 except:
755 755 # User exception is improperly defined.
756 756 etype, evalue = str, sys.exc_info()[:2]
757 757 etype_str, evalue_str = map(str, (etype, evalue))
758 758 # ... and format it
759 759 return ['%s%s%s: %s' % (colors.excName, etype_str,
760 760 colorsnormal, py3compat.cast_unicode(evalue_str))]
761 761
762 762 def format_exception_as_a_whole(
763 763 self,
764 764 etype: type,
765 765 evalue: BaseException,
766 etb: TracebackType,
766 etb: Optional[TracebackType],
767 767 number_of_lines_of_context,
768 768 tb_offset: Optional[int],
769 769 ):
770 770 """Formats the header, traceback and exception message for a single exception.
771 771
772 772 This may be called multiple times by Python 3 exception chaining
773 773 (PEP 3134).
774 774 """
775 assert etb is not None
776 775 # some locals
777 776 orig_etype = etype
778 777 try:
779 778 etype = etype.__name__
780 779 except AttributeError:
781 780 pass
782 781
783 782 tb_offset = self.tb_offset if tb_offset is None else tb_offset
784 783 assert isinstance(tb_offset, int)
785 784 head = self.prepare_header(etype, self.long_header)
786 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
785 records = (
786 self.get_records(etb, number_of_lines_of_context, tb_offset) if etb else []
787 )
787 788
788 789 frames = []
789 790 skipped = 0
790 791 lastrecord = len(records) - 1
791 792 for i, r in enumerate(records):
792 793 if not isinstance(r, stack_data.RepeatedFrames) and self.skip_hidden:
793 794 if r.frame.f_locals.get("__tracebackhide__", 0) and i != lastrecord:
794 795 skipped += 1
795 796 continue
796 797 if skipped:
797 798 Colors = self.Colors # just a shorthand + quicker name lookup
798 799 ColorsNormal = Colors.Normal # used a lot
799 800 frames.append(
800 801 " %s[... skipping hidden %s frame]%s\n"
801 802 % (Colors.excName, skipped, ColorsNormal)
802 803 )
803 804 skipped = 0
804 805 frames.append(self.format_record(r))
805 806 if skipped:
806 807 Colors = self.Colors # just a shorthand + quicker name lookup
807 808 ColorsNormal = Colors.Normal # used a lot
808 809 frames.append(
809 810 " %s[... skipping hidden %s frame]%s\n"
810 811 % (Colors.excName, skipped, ColorsNormal)
811 812 )
812 813
813 814 formatted_exception = self.format_exception(etype, evalue)
814 815 if records:
815 816 frame_info = records[-1]
816 817 ipinst = get_ipython()
817 818 if ipinst is not None:
818 819 ipinst.hooks.synchronize_with_editor(frame_info.filename, frame_info.lineno, 0)
819 820
820 821 return [[head] + frames + [''.join(formatted_exception[0])]]
821 822
822 823 def get_records(
823 824 self, etb: TracebackType, number_of_lines_of_context: int, tb_offset: int
824 825 ):
826 assert etb is not None
825 827 context = number_of_lines_of_context - 1
826 828 after = context // 2
827 829 before = context - after
828 830 if self.has_colors:
829 831 style = get_style_by_name("default")
830 832 style = stack_data.style_with_executing_node(style, "bg:ansiyellow")
831 833 formatter = Terminal256Formatter(style=style)
832 834 else:
833 835 formatter = None
834 836 options = stack_data.Options(
835 837 before=before,
836 838 after=after,
837 839 pygments_formatter=formatter,
838 840 )
839 assert etb is not None
840 841 return list(stack_data.FrameInfo.stack_data(etb, options=options))[tb_offset:]
841 842
842 843 def structured_traceback(
843 844 self,
844 845 etype: type,
845 846 evalue: Optional[BaseException],
846 etb: TracebackType,
847 etb: Optional[TracebackType],
847 848 tb_offset: Optional[int] = None,
848 849 number_of_lines_of_context: int = 5,
849 850 ):
850 851 """Return a nice text document describing the traceback."""
851 assert etb is not None
852 852 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
853 853 tb_offset)
854 854
855 855 colors = self.Colors # just a shorthand + quicker name lookup
856 856 colorsnormal = colors.Normal # used a lot
857 857 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
858 858 structured_traceback_parts = [head]
859 859 chained_exceptions_tb_offset = 0
860 860 lines_of_context = 3
861 861 formatted_exceptions = formatted_exception
862 862 exception = self.get_parts_of_chained_exception(evalue)
863 863 if exception:
864 864 assert evalue is not None
865 865 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
866 866 etype, evalue, etb = exception
867 867 else:
868 868 evalue = None
869 869 chained_exc_ids = set()
870 870 while evalue:
871 871 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
872 872 chained_exceptions_tb_offset)
873 873 exception = self.get_parts_of_chained_exception(evalue)
874 874
875 875 if exception and not id(exception[1]) in chained_exc_ids:
876 876 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
877 877 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
878 878 etype, evalue, etb = exception
879 879 else:
880 880 evalue = None
881 881
882 882 # we want to see exceptions in a reversed order:
883 883 # the first exception should be on top
884 884 for formatted_exception in reversed(formatted_exceptions):
885 885 structured_traceback_parts += formatted_exception
886 886
887 887 return structured_traceback_parts
888 888
889 889 def debugger(self, force: bool = False):
890 890 """Call up the pdb debugger if desired, always clean up the tb
891 891 reference.
892 892
893 893 Keywords:
894 894
895 895 - force(False): by default, this routine checks the instance call_pdb
896 896 flag and does not actually invoke the debugger if the flag is false.
897 897 The 'force' option forces the debugger to activate even if the flag
898 898 is false.
899 899
900 900 If the call_pdb flag is set, the pdb interactive debugger is
901 901 invoked. In all cases, the self.tb reference to the current traceback
902 902 is deleted to prevent lingering references which hamper memory
903 903 management.
904 904
905 905 Note that each call to pdb() does an 'import readline', so if your app
906 906 requires a special setup for the readline completers, you'll have to
907 907 fix that by hand after invoking the exception handler."""
908 908
909 909 if force or self.call_pdb:
910 910 if self.pdb is None:
911 911 self.pdb = self.debugger_cls()
912 912 # the system displayhook may have changed, restore the original
913 913 # for pdb
914 914 display_trap = DisplayTrap(hook=sys.__displayhook__)
915 915 with display_trap:
916 916 self.pdb.reset()
917 917 # Find the right frame so we don't pop up inside ipython itself
918 918 if hasattr(self, 'tb') and self.tb is not None:
919 919 etb = self.tb
920 920 else:
921 921 etb = self.tb = sys.last_traceback
922 922 while self.tb is not None and self.tb.tb_next is not None:
923 923 assert self.tb.tb_next is not None
924 924 self.tb = self.tb.tb_next
925 925 if etb and etb.tb_next:
926 926 etb = etb.tb_next
927 927 self.pdb.botframe = etb.tb_frame
928 928 self.pdb.interaction(None, etb)
929 929
930 930 if hasattr(self, 'tb'):
931 931 del self.tb
932 932
933 933 def handler(self, info=None):
934 934 (etype, evalue, etb) = info or sys.exc_info()
935 935 self.tb = etb
936 936 ostream = self.ostream
937 937 ostream.flush()
938 938 ostream.write(self.text(etype, evalue, etb))
939 939 ostream.write('\n')
940 940 ostream.flush()
941 941
942 942 # Changed so an instance can just be called as VerboseTB_inst() and print
943 943 # out the right info on its own.
944 944 def __call__(self, etype=None, evalue=None, etb=None):
945 945 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
946 946 if etb is None:
947 947 self.handler()
948 948 else:
949 949 self.handler((etype, evalue, etb))
950 950 try:
951 951 self.debugger()
952 952 except KeyboardInterrupt:
953 953 print("\nKeyboardInterrupt")
954 954
955 955
956 956 #----------------------------------------------------------------------------
957 957 class FormattedTB(VerboseTB, ListTB):
958 958 """Subclass ListTB but allow calling with a traceback.
959 959
960 960 It can thus be used as a sys.excepthook for Python > 2.1.
961 961
962 962 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
963 963
964 964 Allows a tb_offset to be specified. This is useful for situations where
965 965 one needs to remove a number of topmost frames from the traceback (such as
966 966 occurs with python programs that themselves execute other python code,
967 967 like Python shells). """
968 968
969 969 mode: str
970 970
971 971 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
972 972 ostream=None,
973 973 tb_offset=0, long_header=False, include_vars=False,
974 974 check_cache=None, debugger_cls=None,
975 975 parent=None, config=None):
976 976
977 977 # NEVER change the order of this list. Put new modes at the end:
978 978 self.valid_modes = ['Plain', 'Context', 'Verbose', 'Minimal']
979 979 self.verbose_modes = self.valid_modes[1:3]
980 980
981 981 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
982 982 ostream=ostream, tb_offset=tb_offset,
983 983 long_header=long_header, include_vars=include_vars,
984 984 check_cache=check_cache, debugger_cls=debugger_cls,
985 985 parent=parent, config=config)
986 986
987 987 # Different types of tracebacks are joined with different separators to
988 988 # form a single string. They are taken from this dict
989 989 self._join_chars = dict(Plain='', Context='\n', Verbose='\n',
990 990 Minimal='')
991 991 # set_mode also sets the tb_join_char attribute
992 992 self.set_mode(mode)
993 993
994 994 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
995 995 tb_offset = self.tb_offset if tb_offset is None else tb_offset
996 996 mode = self.mode
997 997 if mode in self.verbose_modes:
998 998 # Verbose modes need a full traceback
999 999 return VerboseTB.structured_traceback(
1000 1000 self, etype, value, tb, tb_offset, number_of_lines_of_context
1001 1001 )
1002 1002 elif mode == 'Minimal':
1003 1003 return ListTB.get_exception_only(self, etype, value)
1004 1004 else:
1005 1005 # We must check the source cache because otherwise we can print
1006 1006 # out-of-date source code.
1007 1007 self.check_cache()
1008 1008 # Now we can extract and format the exception
1009 1009 return ListTB.structured_traceback(
1010 1010 self, etype, value, tb, tb_offset, number_of_lines_of_context
1011 1011 )
1012 1012
1013 1013 def stb2text(self, stb):
1014 1014 """Convert a structured traceback (a list) to a string."""
1015 1015 return self.tb_join_char.join(stb)
1016 1016
1017 1017 def set_mode(self, mode: Optional[str] = None):
1018 1018 """Switch to the desired mode.
1019 1019
1020 1020 If mode is not specified, cycles through the available modes."""
1021 1021
1022 1022 if not mode:
1023 1023 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
1024 1024 len(self.valid_modes)
1025 1025 self.mode = self.valid_modes[new_idx]
1026 1026 elif mode not in self.valid_modes:
1027 1027 raise ValueError(
1028 1028 "Unrecognized mode in FormattedTB: <" + mode + ">\n"
1029 1029 "Valid modes: " + str(self.valid_modes)
1030 1030 )
1031 1031 else:
1032 1032 assert isinstance(mode, str)
1033 1033 self.mode = mode
1034 1034 # include variable details only in 'Verbose' mode
1035 1035 self.include_vars = (self.mode == self.valid_modes[2])
1036 1036 # Set the join character for generating text tracebacks
1037 1037 self.tb_join_char = self._join_chars[self.mode]
1038 1038
1039 1039 # some convenient shortcuts
1040 1040 def plain(self):
1041 1041 self.set_mode(self.valid_modes[0])
1042 1042
1043 1043 def context(self):
1044 1044 self.set_mode(self.valid_modes[1])
1045 1045
1046 1046 def verbose(self):
1047 1047 self.set_mode(self.valid_modes[2])
1048 1048
1049 1049 def minimal(self):
1050 1050 self.set_mode(self.valid_modes[3])
1051 1051
1052 1052
1053 1053 #----------------------------------------------------------------------------
1054 1054 class AutoFormattedTB(FormattedTB):
1055 1055 """A traceback printer which can be called on the fly.
1056 1056
1057 1057 It will find out about exceptions by itself.
1058 1058
1059 1059 A brief example::
1060 1060
1061 1061 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1062 1062 try:
1063 1063 ...
1064 1064 except:
1065 1065 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1066 1066 """
1067 1067
1068 1068 def __call__(self, etype=None, evalue=None, etb=None,
1069 1069 out=None, tb_offset=None):
1070 1070 """Print out a formatted exception traceback.
1071 1071
1072 1072 Optional arguments:
1073 1073 - out: an open file-like object to direct output to.
1074 1074
1075 1075 - tb_offset: the number of frames to skip over in the stack, on a
1076 1076 per-call basis (this overrides temporarily the instance's tb_offset
1077 1077 given at initialization time."""
1078 1078
1079 1079 if out is None:
1080 1080 out = self.ostream
1081 1081 out.flush()
1082 1082 out.write(self.text(etype, evalue, etb, tb_offset))
1083 1083 out.write('\n')
1084 1084 out.flush()
1085 1085 # FIXME: we should remove the auto pdb behavior from here and leave
1086 1086 # that to the clients.
1087 1087 try:
1088 1088 self.debugger()
1089 1089 except KeyboardInterrupt:
1090 1090 print("\nKeyboardInterrupt")
1091 1091
1092 1092 def structured_traceback(self, etype=None, value=None, tb=None,
1093 1093 tb_offset=None, number_of_lines_of_context=5):
1094 1094
1095 1095 etype: type
1096 1096 value: BaseException
1097 1097 # tb: TracebackType or tupleof tb types ?
1098 1098 if etype is None:
1099 1099 etype, value, tb = sys.exc_info()
1100 1100 if isinstance(tb, tuple):
1101 1101 # tb is a tuple if this is a chained exception.
1102 1102 self.tb = tb[0]
1103 1103 else:
1104 1104 self.tb = tb
1105 1105 return FormattedTB.structured_traceback(
1106 1106 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1107 1107
1108 1108
1109 1109 #---------------------------------------------------------------------------
1110 1110
1111 1111 # A simple class to preserve Nathan's original functionality.
1112 1112 class ColorTB(FormattedTB):
1113 1113 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1114 1114
1115 1115 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1116 1116 FormattedTB.__init__(self, color_scheme=color_scheme,
1117 1117 call_pdb=call_pdb, **kwargs)
1118 1118
1119 1119
1120 1120 class SyntaxTB(ListTB):
1121 1121 """Extension which holds some state: the last exception value"""
1122 1122
1123 1123 def __init__(self, color_scheme='NoColor', parent=None, config=None):
1124 1124 ListTB.__init__(self, color_scheme, parent=parent, config=config)
1125 1125 self.last_syntax_error = None
1126 1126
1127 1127 def __call__(self, etype, value, elist):
1128 1128 self.last_syntax_error = value
1129 1129
1130 1130 ListTB.__call__(self, etype, value, elist)
1131 1131
1132 1132 def structured_traceback(self, etype, value, elist, tb_offset=None,
1133 1133 context=5):
1134 1134 # If the source file has been edited, the line in the syntax error can
1135 1135 # be wrong (retrieved from an outdated cache). This replaces it with
1136 1136 # the current value.
1137 1137 if isinstance(value, SyntaxError) \
1138 1138 and isinstance(value.filename, str) \
1139 1139 and isinstance(value.lineno, int):
1140 1140 linecache.checkcache(value.filename)
1141 1141 newtext = linecache.getline(value.filename, value.lineno)
1142 1142 if newtext:
1143 1143 value.text = newtext
1144 1144 self.last_syntax_error = value
1145 1145 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1146 1146 tb_offset=tb_offset, context=context)
1147 1147
1148 1148 def clear_err_state(self):
1149 1149 """Return the current error state and clear it"""
1150 1150 e = self.last_syntax_error
1151 1151 self.last_syntax_error = None
1152 1152 return e
1153 1153
1154 1154 def stb2text(self, stb):
1155 1155 """Convert a structured traceback (a list) to a string."""
1156 1156 return ''.join(stb)
1157 1157
1158 1158
1159 1159 # some internal-use functions
1160 1160 def text_repr(value):
1161 1161 """Hopefully pretty robust repr equivalent."""
1162 1162 # this is pretty horrible but should always return *something*
1163 1163 try:
1164 1164 return pydoc.text.repr(value)
1165 1165 except KeyboardInterrupt:
1166 1166 raise
1167 1167 except:
1168 1168 try:
1169 1169 return repr(value)
1170 1170 except KeyboardInterrupt:
1171 1171 raise
1172 1172 except:
1173 1173 try:
1174 1174 # all still in an except block so we catch
1175 1175 # getattr raising
1176 1176 name = getattr(value, '__name__', None)
1177 1177 if name:
1178 1178 # ick, recursion
1179 1179 return text_repr(name)
1180 1180 klass = getattr(value, '__class__', None)
1181 1181 if klass:
1182 1182 return '%s instance' % text_repr(klass)
1183 1183 except KeyboardInterrupt:
1184 1184 raise
1185 1185 except:
1186 1186 return 'UNRECOVERABLE REPR FAILURE'
1187 1187
1188 1188
1189 1189 def eqrepr(value, repr=text_repr):
1190 1190 return '=%s' % repr(value)
1191 1191
1192 1192
1193 1193 def nullrepr(value, repr=text_repr):
1194 1194 return ''
General Comments 0
You need to be logged in to leave comments. Login now