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