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