blob: 7a7cca1b677029539ed3b5198992fd050bb142c7 [file] [log] [blame]
Guido van Rossume7b146f2000-02-04 15:28:42 +00001"""Extract, format and print information about Python stack traces."""
Guido van Rossum526beed1994-07-01 15:36:46 +00002
Serhiy Storchaka24559e42015-05-03 13:19:46 +03003import collections
4import itertools
Guido van Rossum526beed1994-07-01 15:36:46 +00005import linecache
Guido van Rossum526beed1994-07-01 15:36:46 +00006import sys
7
Skip Montanaro40fc1602001-03-01 04:27:19 +00008__all__ = ['extract_stack', 'extract_tb', 'format_exception',
9 'format_exception_only', 'format_list', 'format_stack',
Neil Schemenauerf607fc52003-11-05 23:03:00 +000010 'format_tb', 'print_exc', 'format_exc', 'print_exception',
Berker Peksag716b3d32015-04-08 09:47:14 +030011 'print_last', 'print_stack', 'print_tb', 'clear_frames',
12 'FrameSummary', 'StackSummary', 'TracebackException',
13 'walk_stack', 'walk_tb']
Skip Montanaro40fc1602001-03-01 04:27:19 +000014
Benjamin Petersond9fec152013-04-29 16:09:39 -040015#
16# Formatting and printing lists of traceback lines.
17#
Guido van Rossumdcc057a1996-08-12 23:18:13 +000018
Guido van Rossumdcc057a1996-08-12 23:18:13 +000019def print_list(extracted_list, file=None):
Tim Petersb90f89a2001-01-15 03:26:36 +000020 """Print the list of tuples as returned by extract_tb() or
21 extract_stack() as a formatted stack trace to the given file."""
Raymond Hettinger10ff7062002-06-02 03:04:52 +000022 if file is None:
Tim Petersb90f89a2001-01-15 03:26:36 +000023 file = sys.stderr
Robert Collins6bc2c1e2015-03-05 12:07:57 +130024 for item in StackSummary.from_list(extracted_list).format():
Benjamin Petersond9fec152013-04-29 16:09:39 -040025 print(item, file=file, end="")
Guido van Rossumdcc057a1996-08-12 23:18:13 +000026
27def format_list(extracted_list):
torsavaf394ee52018-08-02 17:08:59 +010028 """Format a list of tuples or FrameSummary objects for printing.
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000029
torsavaf394ee52018-08-02 17:08:59 +010030 Given a list of tuples or FrameSummary objects as returned by
31 extract_tb() or extract_stack(), return a list of strings ready
32 for printing.
33
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000034 Each string in the resulting list corresponds to the item with the
35 same index in the argument list. Each string ends in a newline;
36 the strings may contain internal newlines as well, for those items
37 whose source text line is not None.
38 """
Robert Collins6bc2c1e2015-03-05 12:07:57 +130039 return StackSummary.from_list(extracted_list).format()
Tim Petersb90f89a2001-01-15 03:26:36 +000040
Benjamin Petersond9fec152013-04-29 16:09:39 -040041#
42# Printing and Extracting Tracebacks.
43#
44
Guido van Rossum194e20a1995-09-20 20:31:51 +000045def print_tb(tb, limit=None, file=None):
Tim Petersb90f89a2001-01-15 03:26:36 +000046 """Print up to 'limit' stack trace entries from the traceback 'tb'.
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000047
48 If 'limit' is omitted or None, all entries are printed. If 'file'
49 is omitted or None, the output goes to sys.stderr; otherwise
50 'file' should be an open file or file-like object with a write()
51 method.
52 """
Benjamin Petersond9fec152013-04-29 16:09:39 -040053 print_list(extract_tb(tb, limit=limit), file=file)
Guido van Rossum526beed1994-07-01 15:36:46 +000054
Georg Brandl2ad07c32009-09-16 14:24:29 +000055def format_tb(tb, limit=None):
Georg Brandl9e091e12013-10-13 23:32:14 +020056 """A shorthand for 'format_list(extract_tb(tb, limit))'."""
Robert Collins6bc2c1e2015-03-05 12:07:57 +130057 return extract_tb(tb, limit=limit).format()
Guido van Rossum28e99fe1995-08-04 04:30:30 +000058
Georg Brandl2ad07c32009-09-16 14:24:29 +000059def extract_tb(tb, limit=None):
torsavaf394ee52018-08-02 17:08:59 +010060 """
61 Return a StackSummary object representing a list of
62 pre-processed entries from traceback.
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000063
64 This is useful for alternate formatting of stack traces. If
65 'limit' is omitted or None, all entries are extracted. A
torsavaf394ee52018-08-02 17:08:59 +010066 pre-processed stack trace entry is a FrameSummary object
67 containing attributes filename, lineno, name, and line
68 representing the information that is usually printed for a stack
69 trace. The line is a string with leading and trailing
70 whitespace stripped; if the source is not available it is None.
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000071 """
Robert Collins6bc2c1e2015-03-05 12:07:57 +130072 return StackSummary.extract(walk_tb(tb), limit=limit)
Guido van Rossum526beed1994-07-01 15:36:46 +000073
Benjamin Petersond9fec152013-04-29 16:09:39 -040074#
75# Exception formatting and output.
76#
Guido van Rossum28e99fe1995-08-04 04:30:30 +000077
Benjamin Petersone6528212008-07-15 15:32:09 +000078_cause_message = (
79 "\nThe above exception was the direct cause "
Robert Collins6bc2c1e2015-03-05 12:07:57 +130080 "of the following exception:\n\n")
Benjamin Petersone6528212008-07-15 15:32:09 +000081
82_context_message = (
83 "\nDuring handling of the above exception, "
Robert Collins6bc2c1e2015-03-05 12:07:57 +130084 "another exception occurred:\n\n")
Benjamin Petersone6528212008-07-15 15:32:09 +000085
Benjamin Petersone6528212008-07-15 15:32:09 +000086
Miss Islington (bot)eb0a6802021-06-17 09:41:46 -070087class _Sentinel:
88 def __repr__(self):
89 return "<implicit>"
Zackery Spytz91e93792020-11-05 15:18:44 -070090
Miss Islington (bot)eb0a6802021-06-17 09:41:46 -070091_sentinel = _Sentinel()
Zackery Spytz91e93792020-11-05 15:18:44 -070092
93def _parse_value_tb(exc, value, tb):
94 if (value is _sentinel) != (tb is _sentinel):
95 raise ValueError("Both or neither of value and tb must be given")
96 if value is tb is _sentinel:
Irit Katrielb798ab02021-02-23 17:43:04 +000097 if exc is not None:
98 return exc, exc.__traceback__
99 else:
100 return None, None
Zackery Spytz91e93792020-11-05 15:18:44 -0700101 return value, tb
102
103
104def print_exception(exc, /, value=_sentinel, tb=_sentinel, limit=None, \
105 file=None, chain=True):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000106 """Print exception up to 'limit' stack trace entries from 'tb' to 'file'.
107
108 This differs from print_tb() in the following ways: (1) if
109 traceback is not None, it prints a header "Traceback (most recent
110 call last):"; (2) it prints the exception type and value after the
111 stack trace; (3) if type is SyntaxError and value has the
112 appropriate format, it prints the line where the syntax error
Tim Petersb90f89a2001-01-15 03:26:36 +0000113 occurred with a caret on the next line indicating the approximate
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000114 position of the error.
115 """
Zackery Spytz91e93792020-11-05 15:18:44 -0700116 value, tb = _parse_value_tb(exc, value, tb)
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000117 if file is None:
Tim Petersb90f89a2001-01-15 03:26:36 +0000118 file = sys.stderr
Irit Katriel4c94d742021-01-15 02:45:02 +0000119 te = TracebackException(type(value), value, tb, limit=limit, compact=True)
120 for line in te.format(chain=chain):
Benjamin Petersond9fec152013-04-29 16:09:39 -0400121 print(line, file=file, end="")
Guido van Rossum28e99fe1995-08-04 04:30:30 +0000122
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300123
Zackery Spytz91e93792020-11-05 15:18:44 -0700124def format_exception(exc, /, value=_sentinel, tb=_sentinel, limit=None, \
125 chain=True):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000126 """Format a stack trace and the exception information.
127
128 The arguments have the same meaning as the corresponding arguments
129 to print_exception(). The return value is a list of strings, each
Tim Petersb90f89a2001-01-15 03:26:36 +0000130 ending in a newline and some containing internal newlines. When
131 these lines are concatenated and printed, exactly the same text is
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000132 printed as does print_exception().
133 """
Zackery Spytz91e93792020-11-05 15:18:44 -0700134 value, tb = _parse_value_tb(exc, value, tb)
Irit Katriel4c94d742021-01-15 02:45:02 +0000135 te = TracebackException(type(value), value, tb, limit=limit, compact=True)
136 return list(te.format(chain=chain))
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300137
Guido van Rossum28e99fe1995-08-04 04:30:30 +0000138
Zackery Spytz91e93792020-11-05 15:18:44 -0700139def format_exception_only(exc, /, value=_sentinel):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000140 """Format the exception part of a traceback.
141
Zackery Spytz91e93792020-11-05 15:18:44 -0700142 The return value is a list of strings, each ending in a newline.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000143
144 Normally, the list contains a single string; however, for
145 SyntaxError exceptions, it contains several lines that (when
146 printed) display detailed information about where the syntax
147 error occurred.
148
149 The message indicating which exception occurred is always the last
150 string in the list.
151
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000152 """
Zackery Spytz91e93792020-11-05 15:18:44 -0700153 if value is _sentinel:
154 value = exc
Irit Katriel4c94d742021-01-15 02:45:02 +0000155 te = TracebackException(type(value), value, None, compact=True)
156 return list(te.format_exception_only())
Benjamin Petersond9fec152013-04-29 16:09:39 -0400157
Thomas Wouters89f507f2006-12-13 04:49:30 +0000158
Martin Panter46f50722016-05-26 05:35:26 +0000159# -- not official API but folk probably use these two functions.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000160
161def _format_final_exc_line(etype, value):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000162 valuestr = _some_str(value)
Martin Panterbb8b1cb2016-09-22 09:37:39 +0000163 if value is None or not valuestr:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000164 line = "%s\n" % etype
Tim Petersb90f89a2001-01-15 03:26:36 +0000165 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000166 line = "%s: %s\n" % (etype, valuestr)
167 return line
Guido van Rossum28e99fe1995-08-04 04:30:30 +0000168
Guido van Rossum2823f032000-08-22 02:04:46 +0000169def _some_str(value):
Tim Petersb90f89a2001-01-15 03:26:36 +0000170 try:
171 return str(value)
172 except:
173 return '<unprintable %s object>' % type(value).__name__
Guido van Rossum2823f032000-08-22 02:04:46 +0000174
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300175# --
176
Benjamin Petersone6528212008-07-15 15:32:09 +0000177def print_exc(limit=None, file=None, chain=True):
Neal Norwitzac3625f2006-03-17 05:49:33 +0000178 """Shorthand for 'print_exception(*sys.exc_info(), limit, file)'."""
Benjamin Petersond9fec152013-04-29 16:09:39 -0400179 print_exception(*sys.exc_info(), limit=limit, file=file, chain=chain)
Neil Schemenauerf607fc52003-11-05 23:03:00 +0000180
Benjamin Petersone6528212008-07-15 15:32:09 +0000181def format_exc(limit=None, chain=True):
Neil Schemenauerf607fc52003-11-05 23:03:00 +0000182 """Like print_exc() but return a string."""
Benjamin Petersond9fec152013-04-29 16:09:39 -0400183 return "".join(format_exception(*sys.exc_info(), limit=limit, chain=chain))
Neil Schemenauerf607fc52003-11-05 23:03:00 +0000184
Benjamin Petersone6528212008-07-15 15:32:09 +0000185def print_last(limit=None, file=None, chain=True):
Tim Petersb90f89a2001-01-15 03:26:36 +0000186 """This is a shorthand for 'print_exception(sys.last_type,
187 sys.last_value, sys.last_traceback, limit, file)'."""
Benjamin Petersone549ead2009-03-28 21:42:05 +0000188 if not hasattr(sys, "last_type"):
189 raise ValueError("no last exception")
Tim Petersb90f89a2001-01-15 03:26:36 +0000190 print_exception(sys.last_type, sys.last_value, sys.last_traceback,
Benjamin Petersone6528212008-07-15 15:32:09 +0000191 limit, file, chain)
Guido van Rossumdcc057a1996-08-12 23:18:13 +0000192
Benjamin Petersond9fec152013-04-29 16:09:39 -0400193#
194# Printing and Extracting Stacks.
195#
196
Guido van Rossumdcc057a1996-08-12 23:18:13 +0000197def print_stack(f=None, limit=None, file=None):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000198 """Print a stack trace from its invocation point.
Tim Petersa19a1682001-03-29 04:36:09 +0000199
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000200 The optional 'f' argument can be used to specify an alternate
201 stack frame at which to start. The optional 'limit' and 'file'
202 arguments have the same meaning as for print_exception().
203 """
Serhiy Storchakae953ba72015-09-18 10:04:47 +0300204 if f is None:
205 f = sys._getframe().f_back
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300206 print_list(extract_stack(f, limit=limit), file=file)
207
Guido van Rossumdcc057a1996-08-12 23:18:13 +0000208
209def format_stack(f=None, limit=None):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000210 """Shorthand for 'format_list(extract_stack(f, limit))'."""
Serhiy Storchakae953ba72015-09-18 10:04:47 +0300211 if f is None:
212 f = sys._getframe().f_back
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300213 return format_list(extract_stack(f, limit=limit))
214
Guido van Rossumdcc057a1996-08-12 23:18:13 +0000215
Georg Brandl2ad07c32009-09-16 14:24:29 +0000216def extract_stack(f=None, limit=None):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000217 """Extract the raw traceback from the current stack frame.
218
219 The return value has the same format as for extract_tb(). The
220 optional 'f' and 'limit' arguments have the same meaning as for
221 print_stack(). Each item in the list is a quadruple (filename,
222 line number, function name, text), and the entries are in order
223 from oldest to newest stack frame.
224 """
Serhiy Storchakae953ba72015-09-18 10:04:47 +0300225 if f is None:
226 f = sys._getframe().f_back
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300227 stack = StackSummary.extract(walk_stack(f), limit=limit)
Benjamin Petersond9fec152013-04-29 16:09:39 -0400228 stack.reverse()
229 return stack
Andrew Kuchling173a1572013-09-15 18:15:56 -0400230
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300231
Andrew Kuchling173a1572013-09-15 18:15:56 -0400232def clear_frames(tb):
233 "Clear all references to local variables in the frames of a traceback."
234 while tb is not None:
235 try:
236 tb.tb_frame.clear()
237 except RuntimeError:
238 # Ignore the exception raised if the frame is still executing.
239 pass
240 tb = tb.tb_next
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300241
242
243class FrameSummary:
244 """A single frame from a traceback.
245
246 - :attr:`filename` The filename for the frame.
247 - :attr:`lineno` The line within filename for the frame that was
248 active when the frame was captured.
249 - :attr:`name` The name of the function or method that was executing
250 when the frame was captured.
251 - :attr:`line` The text from the linecache module for the
252 of code that was running when the frame was captured.
253 - :attr:`locals` Either None if locals were not supplied, or a dict
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300254 mapping the name to the repr() of the variable.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300255 """
256
257 __slots__ = ('filename', 'lineno', 'name', '_line', 'locals')
258
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300259 def __init__(self, filename, lineno, name, *, lookup_line=True,
260 locals=None, line=None):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300261 """Construct a FrameSummary.
262
263 :param lookup_line: If True, `linecache` is consulted for the source
264 code line. Otherwise, the line will be looked up when first needed.
265 :param locals: If supplied the frame locals, which will be captured as
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300266 object representations.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300267 :param line: If provided, use this instead of looking up the line in
268 the linecache.
269 """
270 self.filename = filename
271 self.lineno = lineno
272 self.name = name
273 self._line = line
274 if lookup_line:
275 self.line
Jon Dufresne39726282017-05-18 07:35:54 -0700276 self.locals = {k: repr(v) for k, v in locals.items()} if locals else None
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300277
278 def __eq__(self, other):
Serhiy Storchaka3066fc42015-09-29 22:33:36 +0300279 if isinstance(other, FrameSummary):
280 return (self.filename == other.filename and
281 self.lineno == other.lineno and
282 self.name == other.name and
283 self.locals == other.locals)
284 if isinstance(other, tuple):
285 return (self.filename, self.lineno, self.name, self.line) == other
286 return NotImplemented
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300287
288 def __getitem__(self, pos):
289 return (self.filename, self.lineno, self.name, self.line)[pos]
290
291 def __iter__(self):
292 return iter([self.filename, self.lineno, self.name, self.line])
293
294 def __repr__(self):
295 return "<FrameSummary file {filename}, line {lineno} in {name}>".format(
296 filename=self.filename, lineno=self.lineno, name=self.name)
297
Berker Peksag9797b7a2018-09-10 20:02:33 +0300298 def __len__(self):
299 return 4
300
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300301 @property
302 def line(self):
303 if self._line is None:
304 self._line = linecache.getline(self.filename, self.lineno).strip()
305 return self._line
306
307
308def walk_stack(f):
309 """Walk a stack yielding the frame and line number for each frame.
310
311 This will follow f.f_back from the given frame. If no frame is given, the
312 current stack is used. Usually used with StackSummary.extract.
313 """
314 if f is None:
315 f = sys._getframe().f_back.f_back
316 while f is not None:
317 yield f, f.f_lineno
318 f = f.f_back
319
320
321def walk_tb(tb):
322 """Walk a traceback yielding the frame and line number for each frame.
323
324 This will follow tb.tb_next (and thus is in the opposite order to
325 walk_stack). Usually used with StackSummary.extract.
326 """
327 while tb is not None:
328 yield tb.tb_frame, tb.tb_lineno
329 tb = tb.tb_next
330
331
Benjamin Petersond5458692018-09-10 08:43:10 -0700332_RECURSIVE_CUTOFF = 3 # Also hardcoded in traceback.c.
333
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300334class StackSummary(list):
335 """A stack of frames."""
336
337 @classmethod
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300338 def extract(klass, frame_gen, *, limit=None, lookup_lines=True,
339 capture_locals=False):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300340 """Create a StackSummary from a traceback or stack object.
341
342 :param frame_gen: A generator that yields (frame, lineno) tuples to
343 include in the stack.
344 :param limit: None to include all frames or the number of frames to
345 include.
346 :param lookup_lines: If True, lookup lines for each frame immediately,
347 otherwise lookup is deferred until the frame is rendered.
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300348 :param capture_locals: If True, the local variables from each frame will
349 be captured as object representations into the FrameSummary.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300350 """
351 if limit is None:
352 limit = getattr(sys, 'tracebacklimit', None)
Serhiy Storchaka24559e42015-05-03 13:19:46 +0300353 if limit is not None and limit < 0:
354 limit = 0
355 if limit is not None:
356 if limit >= 0:
357 frame_gen = itertools.islice(frame_gen, limit)
358 else:
359 frame_gen = collections.deque(frame_gen, maxlen=-limit)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300360
361 result = klass()
362 fnames = set()
Serhiy Storchaka24559e42015-05-03 13:19:46 +0300363 for f, lineno in frame_gen:
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300364 co = f.f_code
365 filename = co.co_filename
366 name = co.co_name
367
368 fnames.add(filename)
369 linecache.lazycache(filename, f.f_globals)
370 # Must defer line lookups until we have called checkcache.
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300371 if capture_locals:
372 f_locals = f.f_locals
373 else:
374 f_locals = None
375 result.append(FrameSummary(
376 filename, lineno, name, lookup_line=False, locals=f_locals))
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300377 for filename in fnames:
378 linecache.checkcache(filename)
379 # If immediate lookup was desired, trigger lookups now.
380 if lookup_lines:
381 for f in result:
382 f.line
383 return result
384
385 @classmethod
386 def from_list(klass, a_list):
torsavaf394ee52018-08-02 17:08:59 +0100387 """
388 Create a StackSummary object from a supplied list of
389 FrameSummary objects or old-style list of tuples.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300390 """
Robert Collinsbbb8ade2015-03-16 15:27:16 +1300391 # While doing a fast-path check for isinstance(a_list, StackSummary) is
392 # appealing, idlelib.run.cleanup_traceback and other similar code may
393 # break this by making arbitrary frames plain tuples, so we need to
394 # check on a frame by frame basis.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300395 result = StackSummary()
Robert Collinsbbb8ade2015-03-16 15:27:16 +1300396 for frame in a_list:
397 if isinstance(frame, FrameSummary):
398 result.append(frame)
399 else:
400 filename, lineno, name, line = frame
401 result.append(FrameSummary(filename, lineno, name, line=line))
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300402 return result
403
404 def format(self):
405 """Format the stack ready for printing.
406
407 Returns a list of strings ready for printing. Each string in the
408 resulting list corresponds to a single frame from the stack.
409 Each string ends in a newline; the strings may contain internal
410 newlines as well, for those items with source text lines.
Nick Coghland0034232016-08-15 13:11:34 +1000411
412 For long sequences of the same frame and line, the first few
413 repetitions are shown, followed by a summary line stating the exact
414 number of further repetitions.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300415 """
416 result = []
Nick Coghland0034232016-08-15 13:11:34 +1000417 last_file = None
418 last_line = None
419 last_name = None
420 count = 0
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300421 for frame in self:
Benjamin Petersond5458692018-09-10 08:43:10 -0700422 if (last_file is None or last_file != frame.filename or
423 last_line is None or last_line != frame.lineno or
424 last_name is None or last_name != frame.name):
425 if count > _RECURSIVE_CUTOFF:
426 count -= _RECURSIVE_CUTOFF
427 result.append(
428 f' [Previous line repeated {count} more '
429 f'time{"s" if count > 1 else ""}]\n'
430 )
Nick Coghland0034232016-08-15 13:11:34 +1000431 last_file = frame.filename
432 last_line = frame.lineno
433 last_name = frame.name
434 count = 0
Benjamin Petersond5458692018-09-10 08:43:10 -0700435 count += 1
436 if count > _RECURSIVE_CUTOFF:
Nick Coghland0034232016-08-15 13:11:34 +1000437 continue
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300438 row = []
439 row.append(' File "{}", line {}, in {}\n'.format(
440 frame.filename, frame.lineno, frame.name))
441 if frame.line:
442 row.append(' {}\n'.format(frame.line.strip()))
443 if frame.locals:
444 for name, value in sorted(frame.locals.items()):
445 row.append(' {name} = {value}\n'.format(name=name, value=value))
446 result.append(''.join(row))
Benjamin Petersond5458692018-09-10 08:43:10 -0700447 if count > _RECURSIVE_CUTOFF:
448 count -= _RECURSIVE_CUTOFF
449 result.append(
450 f' [Previous line repeated {count} more '
451 f'time{"s" if count > 1 else ""}]\n'
452 )
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300453 return result
454
455
456class TracebackException:
457 """An exception ready for rendering.
458
459 The traceback module captures enough attributes from the original exception
460 to this intermediary form to ensure that no references are held, while
461 still being able to fully print or format it.
462
463 Use `from_exception` to create TracebackException instances from exception
464 objects, or the constructor to create TracebackException instances from
465 individual components.
466
467 - :attr:`__cause__` A TracebackException of the original *__cause__*.
468 - :attr:`__context__` A TracebackException of the original *__context__*.
469 - :attr:`__suppress_context__` The *__suppress_context__* value from the
470 original exception.
471 - :attr:`stack` A `StackSummary` representing the traceback.
472 - :attr:`exc_type` The class of the original traceback.
473 - :attr:`filename` For syntax errors - the filename where the error
Martin Panter46f50722016-05-26 05:35:26 +0000474 occurred.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300475 - :attr:`lineno` For syntax errors - the linenumber where the error
Martin Panter46f50722016-05-26 05:35:26 +0000476 occurred.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300477 - :attr:`text` For syntax errors - the text where the error
Martin Panter46f50722016-05-26 05:35:26 +0000478 occurred.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300479 - :attr:`offset` For syntax errors - the offset into the text where the
Martin Panter46f50722016-05-26 05:35:26 +0000480 error occurred.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300481 - :attr:`msg` For syntax errors - the compiler error message.
482 """
483
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300484 def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
Irit Katriel4c94d742021-01-15 02:45:02 +0000485 lookup_lines=True, capture_locals=False, compact=False,
486 _seen=None):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300487 # NB: we need to accept exc_traceback, exc_value, exc_traceback to
488 # permit backwards compat with the existing API, otherwise we
489 # need stub thunk objects just to glue it together.
490 # Handle loops in __cause__ or __context__.
Irit Katriel6dfd1732021-01-12 22:14:27 +0000491 is_recursive_call = _seen is not None
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300492 if _seen is None:
493 _seen = set()
Zane Bitterde860732017-10-17 17:29:39 -0400494 _seen.add(id(exc_value))
Irit Katriel4c94d742021-01-15 02:45:02 +0000495
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300496 # TODO: locals.
497 self.stack = StackSummary.extract(
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300498 walk_tb(exc_traceback), limit=limit, lookup_lines=lookup_lines,
499 capture_locals=capture_locals)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300500 self.exc_type = exc_type
501 # Capture now to permit freeing resources: only complication is in the
502 # unofficial API _format_final_exc_line
503 self._str = _some_str(exc_value)
504 if exc_type and issubclass(exc_type, SyntaxError):
505 # Handle SyntaxError's specially
506 self.filename = exc_value.filename
Irit Katriel069560b2020-12-22 19:53:09 +0000507 lno = exc_value.lineno
508 self.lineno = str(lno) if lno is not None else None
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300509 self.text = exc_value.text
510 self.offset = exc_value.offset
511 self.msg = exc_value.msg
512 if lookup_lines:
513 self._load_lines()
Irit Katriel6dfd1732021-01-12 22:14:27 +0000514 self.__suppress_context__ = \
Irit Katriel4c94d742021-01-15 02:45:02 +0000515 exc_value.__suppress_context__ if exc_value is not None else False
Irit Katriel6dfd1732021-01-12 22:14:27 +0000516
517 # Convert __cause__ and __context__ to `TracebackExceptions`s, use a
518 # queue to avoid recursion (only the top-level call gets _seen == None)
519 if not is_recursive_call:
520 queue = [(self, exc_value)]
521 while queue:
522 te, e = queue.pop()
523 if (e and e.__cause__ is not None
524 and id(e.__cause__) not in _seen):
525 cause = TracebackException(
526 type(e.__cause__),
527 e.__cause__,
528 e.__cause__.__traceback__,
529 limit=limit,
530 lookup_lines=lookup_lines,
531 capture_locals=capture_locals,
532 _seen=_seen)
533 else:
534 cause = None
Irit Katriel4c94d742021-01-15 02:45:02 +0000535
536 if compact:
Irit Katriel26f18b82021-02-23 14:58:47 +0000537 need_context = (cause is None and
538 e is not None and
539 not e.__suppress_context__)
Irit Katriel4c94d742021-01-15 02:45:02 +0000540 else:
541 need_context = True
Irit Katriel6dfd1732021-01-12 22:14:27 +0000542 if (e and e.__context__ is not None
Irit Katriel4c94d742021-01-15 02:45:02 +0000543 and need_context and id(e.__context__) not in _seen):
Irit Katriel6dfd1732021-01-12 22:14:27 +0000544 context = TracebackException(
545 type(e.__context__),
546 e.__context__,
547 e.__context__.__traceback__,
548 limit=limit,
549 lookup_lines=lookup_lines,
550 capture_locals=capture_locals,
551 _seen=_seen)
552 else:
553 context = None
554 te.__cause__ = cause
555 te.__context__ = context
556 if cause:
557 queue.append((te.__cause__, e.__cause__))
558 if context:
559 queue.append((te.__context__, e.__context__))
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300560
561 @classmethod
Robert Collinsaece8242015-07-26 06:50:51 +1200562 def from_exception(cls, exc, *args, **kwargs):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300563 """Create a TracebackException from an exception."""
Robert Collinsaece8242015-07-26 06:50:51 +1200564 return cls(type(exc), exc, exc.__traceback__, *args, **kwargs)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300565
566 def _load_lines(self):
567 """Private API. force all lines in the stack to be loaded."""
568 for frame in self.stack:
569 frame.line
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300570
571 def __eq__(self, other):
Serhiy Storchaka662db122019-08-08 08:42:54 +0300572 if isinstance(other, TracebackException):
573 return self.__dict__ == other.__dict__
574 return NotImplemented
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300575
576 def __str__(self):
577 return self._str
578
579 def format_exception_only(self):
580 """Format the exception part of the traceback.
581
582 The return value is a generator of strings, each ending in a newline.
583
584 Normally, the generator emits a single string; however, for
Galdendf8913f2020-04-20 10:17:37 +0800585 SyntaxError exceptions, it emits several lines that (when
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300586 printed) display detailed information about where the syntax
587 error occurred.
588
589 The message indicating which exception occurred is always the last
590 string in the output.
591 """
592 if self.exc_type is None:
593 yield _format_final_exc_line(None, self._str)
594 return
595
596 stype = self.exc_type.__qualname__
597 smod = self.exc_type.__module__
598 if smod not in ("__main__", "builtins"):
599 stype = smod + '.' + stype
600
601 if not issubclass(self.exc_type, SyntaxError):
602 yield _format_final_exc_line(stype, self._str)
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700603 else:
604 yield from self._format_syntax_error(stype)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300605
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700606 def _format_syntax_error(self, stype):
607 """Format SyntaxError exceptions (internal helper)."""
608 # Show exactly where the problem was found.
Irit Katriel069560b2020-12-22 19:53:09 +0000609 filename_suffix = ''
610 if self.lineno is not None:
611 yield ' File "{}", line {}\n'.format(
612 self.filename or "<string>", self.lineno)
613 elif self.filename is not None:
614 filename_suffix = ' ({})'.format(self.filename)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300615
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700616 text = self.text
617 if text is not None:
618 # text = " foo\n"
619 # rtext = " foo"
620 # ltext = "foo"
621 rtext = text.rstrip('\n')
622 ltext = rtext.lstrip(' \n\f')
623 spaces = len(rtext) - len(ltext)
624 yield ' {}\n'.format(ltext)
625 # Convert 1-based column offset to 0-based index into stripped text
626 caret = (self.offset or 0) - 1 - spaces
627 if caret >= 0:
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300628 # non-space whitespace (likes tabs) must be kept for alignment
Guido van Rossum15bc9ab2020-05-14 19:22:48 -0700629 caretspace = ((c if c.isspace() else ' ') for c in ltext[:caret])
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300630 yield ' {}^\n'.format(''.join(caretspace))
631 msg = self.msg or "<no detail available>"
Irit Katriel069560b2020-12-22 19:53:09 +0000632 yield "{}: {}{}\n".format(stype, msg, filename_suffix)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300633
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300634 def format(self, *, chain=True):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300635 """Format the exception.
636
637 If chain is not *True*, *__cause__* and *__context__* will not be formatted.
638
639 The return value is a generator of strings, each ending in a newline and
640 some containing internal newlines. `print_exception` is a wrapper around
641 this method which just prints the lines to a file.
642
643 The message indicating which exception occurred is always the last
644 string in the output.
645 """
Irit Katriel6dfd1732021-01-12 22:14:27 +0000646
647 output = []
648 exc = self
649 while exc:
650 if chain:
651 if exc.__cause__ is not None:
652 chained_msg = _cause_message
653 chained_exc = exc.__cause__
654 elif (exc.__context__ is not None and
655 not exc.__suppress_context__):
656 chained_msg = _context_message
657 chained_exc = exc.__context__
658 else:
659 chained_msg = None
660 chained_exc = None
661
662 output.append((chained_msg, exc))
663 exc = chained_exc
664 else:
665 output.append((None, exc))
666 exc = None
667
668 for msg, exc in reversed(output):
669 if msg is not None:
670 yield msg
671 if exc.stack:
672 yield 'Traceback (most recent call last):\n'
673 yield from exc.stack.format()
674 yield from exc.format_exception_only()