blob: afab0a4b91f1cca93b052f2dac34e5401070092f [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
87def print_exception(etype, value, tb, limit=None, file=None, chain=True):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000088 """Print exception up to 'limit' stack trace entries from 'tb' to 'file'.
89
90 This differs from print_tb() in the following ways: (1) if
91 traceback is not None, it prints a header "Traceback (most recent
92 call last):"; (2) it prints the exception type and value after the
93 stack trace; (3) if type is SyntaxError and value has the
94 appropriate format, it prints the line where the syntax error
Tim Petersb90f89a2001-01-15 03:26:36 +000095 occurred with a caret on the next line indicating the approximate
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000096 position of the error.
97 """
Robert Collins2f0441f2015-03-05 15:45:01 +130098 # format_exception has ignored etype for some time, and code such as cgitb
99 # passes in bogus values as a result. For compatibility with such code we
100 # ignore it here (rather than in the new TracebackException API).
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000101 if file is None:
Tim Petersb90f89a2001-01-15 03:26:36 +0000102 file = sys.stderr
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300103 for line in TracebackException(
Robert Collins2f0441f2015-03-05 15:45:01 +1300104 type(value), value, tb, limit=limit).format(chain=chain):
Benjamin Petersond9fec152013-04-29 16:09:39 -0400105 print(line, file=file, end="")
Guido van Rossum28e99fe1995-08-04 04:30:30 +0000106
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300107
Benjamin Petersone6528212008-07-15 15:32:09 +0000108def format_exception(etype, value, tb, limit=None, chain=True):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000109 """Format a stack trace and the exception information.
110
111 The arguments have the same meaning as the corresponding arguments
112 to print_exception(). The return value is a list of strings, each
Tim Petersb90f89a2001-01-15 03:26:36 +0000113 ending in a newline and some containing internal newlines. When
114 these lines are concatenated and printed, exactly the same text is
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000115 printed as does print_exception().
116 """
Robert Collins2f0441f2015-03-05 15:45:01 +1300117 # format_exception has ignored etype for some time, and code such as cgitb
118 # passes in bogus values as a result. For compatibility with such code we
119 # ignore it here (rather than in the new TracebackException API).
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300120 return list(TracebackException(
Robert Collins2f0441f2015-03-05 15:45:01 +1300121 type(value), value, tb, limit=limit).format(chain=chain))
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300122
Guido van Rossum28e99fe1995-08-04 04:30:30 +0000123
124def format_exception_only(etype, value):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000125 """Format the exception part of a traceback.
126
127 The arguments are the exception type and value such as given by
128 sys.last_type and sys.last_value. The return value is a list of
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000129 strings, each ending in a newline.
130
131 Normally, the list contains a single string; however, for
132 SyntaxError exceptions, it contains several lines that (when
133 printed) display detailed information about where the syntax
134 error occurred.
135
136 The message indicating which exception occurred is always the last
137 string in the list.
138
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000139 """
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300140 return list(TracebackException(etype, value, None).format_exception_only())
Benjamin Petersond9fec152013-04-29 16:09:39 -0400141
Thomas Wouters89f507f2006-12-13 04:49:30 +0000142
Martin Panter46f50722016-05-26 05:35:26 +0000143# -- not official API but folk probably use these two functions.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000144
145def _format_final_exc_line(etype, value):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000146 valuestr = _some_str(value)
Martin Panterbb8b1cb2016-09-22 09:37:39 +0000147 if value is None or not valuestr:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000148 line = "%s\n" % etype
Tim Petersb90f89a2001-01-15 03:26:36 +0000149 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000150 line = "%s: %s\n" % (etype, valuestr)
151 return line
Guido van Rossum28e99fe1995-08-04 04:30:30 +0000152
Guido van Rossum2823f032000-08-22 02:04:46 +0000153def _some_str(value):
Tim Petersb90f89a2001-01-15 03:26:36 +0000154 try:
155 return str(value)
156 except:
157 return '<unprintable %s object>' % type(value).__name__
Guido van Rossum2823f032000-08-22 02:04:46 +0000158
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300159# --
160
Benjamin Petersone6528212008-07-15 15:32:09 +0000161def print_exc(limit=None, file=None, chain=True):
Neal Norwitzac3625f2006-03-17 05:49:33 +0000162 """Shorthand for 'print_exception(*sys.exc_info(), limit, file)'."""
Benjamin Petersond9fec152013-04-29 16:09:39 -0400163 print_exception(*sys.exc_info(), limit=limit, file=file, chain=chain)
Neil Schemenauerf607fc52003-11-05 23:03:00 +0000164
Benjamin Petersone6528212008-07-15 15:32:09 +0000165def format_exc(limit=None, chain=True):
Neil Schemenauerf607fc52003-11-05 23:03:00 +0000166 """Like print_exc() but return a string."""
Benjamin Petersond9fec152013-04-29 16:09:39 -0400167 return "".join(format_exception(*sys.exc_info(), limit=limit, chain=chain))
Neil Schemenauerf607fc52003-11-05 23:03:00 +0000168
Benjamin Petersone6528212008-07-15 15:32:09 +0000169def print_last(limit=None, file=None, chain=True):
Tim Petersb90f89a2001-01-15 03:26:36 +0000170 """This is a shorthand for 'print_exception(sys.last_type,
171 sys.last_value, sys.last_traceback, limit, file)'."""
Benjamin Petersone549ead2009-03-28 21:42:05 +0000172 if not hasattr(sys, "last_type"):
173 raise ValueError("no last exception")
Tim Petersb90f89a2001-01-15 03:26:36 +0000174 print_exception(sys.last_type, sys.last_value, sys.last_traceback,
Benjamin Petersone6528212008-07-15 15:32:09 +0000175 limit, file, chain)
Guido van Rossumdcc057a1996-08-12 23:18:13 +0000176
Benjamin Petersond9fec152013-04-29 16:09:39 -0400177#
178# Printing and Extracting Stacks.
179#
180
Guido van Rossumdcc057a1996-08-12 23:18:13 +0000181def print_stack(f=None, limit=None, file=None):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000182 """Print a stack trace from its invocation point.
Tim Petersa19a1682001-03-29 04:36:09 +0000183
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000184 The optional 'f' argument can be used to specify an alternate
185 stack frame at which to start. The optional 'limit' and 'file'
186 arguments have the same meaning as for print_exception().
187 """
Serhiy Storchakae953ba72015-09-18 10:04:47 +0300188 if f is None:
189 f = sys._getframe().f_back
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300190 print_list(extract_stack(f, limit=limit), file=file)
191
Guido van Rossumdcc057a1996-08-12 23:18:13 +0000192
193def format_stack(f=None, limit=None):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000194 """Shorthand for 'format_list(extract_stack(f, limit))'."""
Serhiy Storchakae953ba72015-09-18 10:04:47 +0300195 if f is None:
196 f = sys._getframe().f_back
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300197 return format_list(extract_stack(f, limit=limit))
198
Guido van Rossumdcc057a1996-08-12 23:18:13 +0000199
Georg Brandl2ad07c32009-09-16 14:24:29 +0000200def extract_stack(f=None, limit=None):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000201 """Extract the raw traceback from the current stack frame.
202
203 The return value has the same format as for extract_tb(). The
204 optional 'f' and 'limit' arguments have the same meaning as for
205 print_stack(). Each item in the list is a quadruple (filename,
206 line number, function name, text), and the entries are in order
207 from oldest to newest stack frame.
208 """
Serhiy Storchakae953ba72015-09-18 10:04:47 +0300209 if f is None:
210 f = sys._getframe().f_back
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300211 stack = StackSummary.extract(walk_stack(f), limit=limit)
Benjamin Petersond9fec152013-04-29 16:09:39 -0400212 stack.reverse()
213 return stack
Andrew Kuchling173a1572013-09-15 18:15:56 -0400214
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300215
Andrew Kuchling173a1572013-09-15 18:15:56 -0400216def clear_frames(tb):
217 "Clear all references to local variables in the frames of a traceback."
218 while tb is not None:
219 try:
220 tb.tb_frame.clear()
221 except RuntimeError:
222 # Ignore the exception raised if the frame is still executing.
223 pass
224 tb = tb.tb_next
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300225
226
227class FrameSummary:
228 """A single frame from a traceback.
229
230 - :attr:`filename` The filename for the frame.
231 - :attr:`lineno` The line within filename for the frame that was
232 active when the frame was captured.
233 - :attr:`name` The name of the function or method that was executing
234 when the frame was captured.
235 - :attr:`line` The text from the linecache module for the
236 of code that was running when the frame was captured.
237 - :attr:`locals` Either None if locals were not supplied, or a dict
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300238 mapping the name to the repr() of the variable.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300239 """
240
241 __slots__ = ('filename', 'lineno', 'name', '_line', 'locals')
242
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300243 def __init__(self, filename, lineno, name, *, lookup_line=True,
244 locals=None, line=None):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300245 """Construct a FrameSummary.
246
247 :param lookup_line: If True, `linecache` is consulted for the source
248 code line. Otherwise, the line will be looked up when first needed.
249 :param locals: If supplied the frame locals, which will be captured as
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300250 object representations.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300251 :param line: If provided, use this instead of looking up the line in
252 the linecache.
253 """
254 self.filename = filename
255 self.lineno = lineno
256 self.name = name
257 self._line = line
258 if lookup_line:
259 self.line
Jon Dufresne39726282017-05-18 07:35:54 -0700260 self.locals = {k: repr(v) for k, v in locals.items()} if locals else None
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300261
262 def __eq__(self, other):
Serhiy Storchaka3066fc42015-09-29 22:33:36 +0300263 if isinstance(other, FrameSummary):
264 return (self.filename == other.filename and
265 self.lineno == other.lineno and
266 self.name == other.name and
267 self.locals == other.locals)
268 if isinstance(other, tuple):
269 return (self.filename, self.lineno, self.name, self.line) == other
270 return NotImplemented
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300271
272 def __getitem__(self, pos):
273 return (self.filename, self.lineno, self.name, self.line)[pos]
274
275 def __iter__(self):
276 return iter([self.filename, self.lineno, self.name, self.line])
277
278 def __repr__(self):
279 return "<FrameSummary file {filename}, line {lineno} in {name}>".format(
280 filename=self.filename, lineno=self.lineno, name=self.name)
281
282 @property
283 def line(self):
284 if self._line is None:
285 self._line = linecache.getline(self.filename, self.lineno).strip()
286 return self._line
287
288
289def walk_stack(f):
290 """Walk a stack yielding the frame and line number for each frame.
291
292 This will follow f.f_back from the given frame. If no frame is given, the
293 current stack is used. Usually used with StackSummary.extract.
294 """
295 if f is None:
296 f = sys._getframe().f_back.f_back
297 while f is not None:
298 yield f, f.f_lineno
299 f = f.f_back
300
301
302def walk_tb(tb):
303 """Walk a traceback yielding the frame and line number for each frame.
304
305 This will follow tb.tb_next (and thus is in the opposite order to
306 walk_stack). Usually used with StackSummary.extract.
307 """
308 while tb is not None:
309 yield tb.tb_frame, tb.tb_lineno
310 tb = tb.tb_next
311
312
313class StackSummary(list):
314 """A stack of frames."""
315
316 @classmethod
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300317 def extract(klass, frame_gen, *, limit=None, lookup_lines=True,
318 capture_locals=False):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300319 """Create a StackSummary from a traceback or stack object.
320
321 :param frame_gen: A generator that yields (frame, lineno) tuples to
322 include in the stack.
323 :param limit: None to include all frames or the number of frames to
324 include.
325 :param lookup_lines: If True, lookup lines for each frame immediately,
326 otherwise lookup is deferred until the frame is rendered.
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300327 :param capture_locals: If True, the local variables from each frame will
328 be captured as object representations into the FrameSummary.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300329 """
330 if limit is None:
331 limit = getattr(sys, 'tracebacklimit', None)
Serhiy Storchaka24559e42015-05-03 13:19:46 +0300332 if limit is not None and limit < 0:
333 limit = 0
334 if limit is not None:
335 if limit >= 0:
336 frame_gen = itertools.islice(frame_gen, limit)
337 else:
338 frame_gen = collections.deque(frame_gen, maxlen=-limit)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300339
340 result = klass()
341 fnames = set()
Serhiy Storchaka24559e42015-05-03 13:19:46 +0300342 for f, lineno in frame_gen:
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300343 co = f.f_code
344 filename = co.co_filename
345 name = co.co_name
346
347 fnames.add(filename)
348 linecache.lazycache(filename, f.f_globals)
349 # Must defer line lookups until we have called checkcache.
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300350 if capture_locals:
351 f_locals = f.f_locals
352 else:
353 f_locals = None
354 result.append(FrameSummary(
355 filename, lineno, name, lookup_line=False, locals=f_locals))
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300356 for filename in fnames:
357 linecache.checkcache(filename)
358 # If immediate lookup was desired, trigger lookups now.
359 if lookup_lines:
360 for f in result:
361 f.line
362 return result
363
364 @classmethod
365 def from_list(klass, a_list):
torsavaf394ee52018-08-02 17:08:59 +0100366 """
367 Create a StackSummary object from a supplied list of
368 FrameSummary objects or old-style list of tuples.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300369 """
Robert Collinsbbb8ade2015-03-16 15:27:16 +1300370 # While doing a fast-path check for isinstance(a_list, StackSummary) is
371 # appealing, idlelib.run.cleanup_traceback and other similar code may
372 # break this by making arbitrary frames plain tuples, so we need to
373 # check on a frame by frame basis.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300374 result = StackSummary()
Robert Collinsbbb8ade2015-03-16 15:27:16 +1300375 for frame in a_list:
376 if isinstance(frame, FrameSummary):
377 result.append(frame)
378 else:
379 filename, lineno, name, line = frame
380 result.append(FrameSummary(filename, lineno, name, line=line))
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300381 return result
382
383 def format(self):
384 """Format the stack ready for printing.
385
386 Returns a list of strings ready for printing. Each string in the
387 resulting list corresponds to a single frame from the stack.
388 Each string ends in a newline; the strings may contain internal
389 newlines as well, for those items with source text lines.
Nick Coghland0034232016-08-15 13:11:34 +1000390
391 For long sequences of the same frame and line, the first few
392 repetitions are shown, followed by a summary line stating the exact
393 number of further repetitions.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300394 """
395 result = []
Nick Coghland0034232016-08-15 13:11:34 +1000396 last_file = None
397 last_line = None
398 last_name = None
399 count = 0
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300400 for frame in self:
Nick Coghland0034232016-08-15 13:11:34 +1000401 if (last_file is not None and last_file == frame.filename and
402 last_line is not None and last_line == frame.lineno and
403 last_name is not None and last_name == frame.name):
404 count += 1
405 else:
406 if count > 3:
Eric V. Smith451d0e32016-09-09 21:56:20 -0400407 result.append(f' [Previous line repeated {count-3} more times]\n')
Nick Coghland0034232016-08-15 13:11:34 +1000408 last_file = frame.filename
409 last_line = frame.lineno
410 last_name = frame.name
411 count = 0
412 if count >= 3:
413 continue
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300414 row = []
415 row.append(' File "{}", line {}, in {}\n'.format(
416 frame.filename, frame.lineno, frame.name))
417 if frame.line:
418 row.append(' {}\n'.format(frame.line.strip()))
419 if frame.locals:
420 for name, value in sorted(frame.locals.items()):
421 row.append(' {name} = {value}\n'.format(name=name, value=value))
422 result.append(''.join(row))
Nick Coghland0034232016-08-15 13:11:34 +1000423 if count > 3:
Eric V. Smith451d0e32016-09-09 21:56:20 -0400424 result.append(f' [Previous line repeated {count-3} more times]\n')
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300425 return result
426
427
428class TracebackException:
429 """An exception ready for rendering.
430
431 The traceback module captures enough attributes from the original exception
432 to this intermediary form to ensure that no references are held, while
433 still being able to fully print or format it.
434
435 Use `from_exception` to create TracebackException instances from exception
436 objects, or the constructor to create TracebackException instances from
437 individual components.
438
439 - :attr:`__cause__` A TracebackException of the original *__cause__*.
440 - :attr:`__context__` A TracebackException of the original *__context__*.
441 - :attr:`__suppress_context__` The *__suppress_context__* value from the
442 original exception.
443 - :attr:`stack` A `StackSummary` representing the traceback.
444 - :attr:`exc_type` The class of the original traceback.
445 - :attr:`filename` For syntax errors - the filename where the error
Martin Panter46f50722016-05-26 05:35:26 +0000446 occurred.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300447 - :attr:`lineno` For syntax errors - the linenumber where the error
Martin Panter46f50722016-05-26 05:35:26 +0000448 occurred.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300449 - :attr:`text` For syntax errors - the text where the error
Martin Panter46f50722016-05-26 05:35:26 +0000450 occurred.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300451 - :attr:`offset` For syntax errors - the offset into the text where the
Martin Panter46f50722016-05-26 05:35:26 +0000452 error occurred.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300453 - :attr:`msg` For syntax errors - the compiler error message.
454 """
455
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300456 def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
457 lookup_lines=True, capture_locals=False, _seen=None):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300458 # NB: we need to accept exc_traceback, exc_value, exc_traceback to
459 # permit backwards compat with the existing API, otherwise we
460 # need stub thunk objects just to glue it together.
461 # Handle loops in __cause__ or __context__.
462 if _seen is None:
463 _seen = set()
Zane Bitterde860732017-10-17 17:29:39 -0400464 _seen.add(id(exc_value))
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300465 # Gracefully handle (the way Python 2.4 and earlier did) the case of
466 # being called with no type or value (None, None, None).
467 if (exc_value and exc_value.__cause__ is not None
Zane Bitterde860732017-10-17 17:29:39 -0400468 and id(exc_value.__cause__) not in _seen):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300469 cause = TracebackException(
470 type(exc_value.__cause__),
471 exc_value.__cause__,
472 exc_value.__cause__.__traceback__,
473 limit=limit,
474 lookup_lines=False,
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300475 capture_locals=capture_locals,
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300476 _seen=_seen)
477 else:
478 cause = None
479 if (exc_value and exc_value.__context__ is not None
Zane Bitterde860732017-10-17 17:29:39 -0400480 and id(exc_value.__context__) not in _seen):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300481 context = TracebackException(
482 type(exc_value.__context__),
483 exc_value.__context__,
484 exc_value.__context__.__traceback__,
485 limit=limit,
486 lookup_lines=False,
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300487 capture_locals=capture_locals,
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300488 _seen=_seen)
489 else:
490 context = None
Berker Peksagc3f417d2015-07-24 17:36:21 +0300491 self.exc_traceback = exc_traceback
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300492 self.__cause__ = cause
493 self.__context__ = context
494 self.__suppress_context__ = \
495 exc_value.__suppress_context__ if exc_value else False
496 # 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
507 self.lineno = str(exc_value.lineno)
508 self.text = exc_value.text
509 self.offset = exc_value.offset
510 self.msg = exc_value.msg
511 if lookup_lines:
512 self._load_lines()
513
514 @classmethod
Robert Collinsaece8242015-07-26 06:50:51 +1200515 def from_exception(cls, exc, *args, **kwargs):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300516 """Create a TracebackException from an exception."""
Robert Collinsaece8242015-07-26 06:50:51 +1200517 return cls(type(exc), exc, exc.__traceback__, *args, **kwargs)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300518
519 def _load_lines(self):
520 """Private API. force all lines in the stack to be loaded."""
521 for frame in self.stack:
522 frame.line
523 if self.__context__:
524 self.__context__._load_lines()
525 if self.__cause__:
526 self.__cause__._load_lines()
527
528 def __eq__(self, other):
529 return self.__dict__ == other.__dict__
530
531 def __str__(self):
532 return self._str
533
534 def format_exception_only(self):
535 """Format the exception part of the traceback.
536
537 The return value is a generator of strings, each ending in a newline.
538
539 Normally, the generator emits a single string; however, for
540 SyntaxError exceptions, it emites several lines that (when
541 printed) display detailed information about where the syntax
542 error occurred.
543
544 The message indicating which exception occurred is always the last
545 string in the output.
546 """
547 if self.exc_type is None:
548 yield _format_final_exc_line(None, self._str)
549 return
550
551 stype = self.exc_type.__qualname__
552 smod = self.exc_type.__module__
553 if smod not in ("__main__", "builtins"):
554 stype = smod + '.' + stype
555
556 if not issubclass(self.exc_type, SyntaxError):
557 yield _format_final_exc_line(stype, self._str)
558 return
559
560 # It was a syntax error; show exactly where the problem was found.
561 filename = self.filename or "<string>"
562 lineno = str(self.lineno) or '?'
563 yield ' File "{}", line {}\n'.format(filename, lineno)
564
565 badline = self.text
566 offset = self.offset
567 if badline is not None:
568 yield ' {}\n'.format(badline.strip())
569 if offset is not None:
570 caretspace = badline.rstrip('\n')
571 offset = min(len(caretspace), offset) - 1
572 caretspace = caretspace[:offset].lstrip()
573 # non-space whitespace (likes tabs) must be kept for alignment
574 caretspace = ((c.isspace() and c or ' ') for c in caretspace)
575 yield ' {}^\n'.format(''.join(caretspace))
576 msg = self.msg or "<no detail available>"
577 yield "{}: {}\n".format(stype, msg)
578
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300579 def format(self, *, chain=True):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300580 """Format the exception.
581
582 If chain is not *True*, *__cause__* and *__context__* will not be formatted.
583
584 The return value is a generator of strings, each ending in a newline and
585 some containing internal newlines. `print_exception` is a wrapper around
586 this method which just prints the lines to a file.
587
588 The message indicating which exception occurred is always the last
589 string in the output.
590 """
591 if chain:
592 if self.__cause__ is not None:
593 yield from self.__cause__.format(chain=chain)
594 yield _cause_message
595 elif (self.__context__ is not None and
596 not self.__suppress_context__):
597 yield from self.__context__.format(chain=chain)
598 yield _context_message
Berker Peksagc3f417d2015-07-24 17:36:21 +0300599 if self.exc_traceback is not None:
600 yield 'Traceback (most recent call last):\n'
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300601 yield from self.stack.format()
602 yield from self.format_exception_only()