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