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