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