blob: ee8c73914032e14818d3b3468cd706869649b564 [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):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000028 """Format a list of traceback entry tuples for printing.
29
30 Given a list of tuples as returned by extract_tb() or
Tim Petersb90f89a2001-01-15 03:26:36 +000031 extract_stack(), return a list of strings ready for printing.
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000032 Each string in the resulting list corresponds to the item with the
33 same index in the argument list. Each string ends in a newline;
34 the strings may contain internal newlines as well, for those items
35 whose source text line is not None.
36 """
Robert Collins6bc2c1e2015-03-05 12:07:57 +130037 return StackSummary.from_list(extracted_list).format()
Tim Petersb90f89a2001-01-15 03:26:36 +000038
Benjamin Petersond9fec152013-04-29 16:09:39 -040039#
40# Printing and Extracting Tracebacks.
41#
42
Guido van Rossum194e20a1995-09-20 20:31:51 +000043def print_tb(tb, limit=None, file=None):
Tim Petersb90f89a2001-01-15 03:26:36 +000044 """Print up to 'limit' stack trace entries from the traceback 'tb'.
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000045
46 If 'limit' is omitted or None, all entries are printed. If 'file'
47 is omitted or None, the output goes to sys.stderr; otherwise
48 'file' should be an open file or file-like object with a write()
49 method.
50 """
Benjamin Petersond9fec152013-04-29 16:09:39 -040051 print_list(extract_tb(tb, limit=limit), file=file)
Guido van Rossum526beed1994-07-01 15:36:46 +000052
Georg Brandl2ad07c32009-09-16 14:24:29 +000053def format_tb(tb, limit=None):
Georg Brandl9e091e12013-10-13 23:32:14 +020054 """A shorthand for 'format_list(extract_tb(tb, limit))'."""
Robert Collins6bc2c1e2015-03-05 12:07:57 +130055 return extract_tb(tb, limit=limit).format()
Guido van Rossum28e99fe1995-08-04 04:30:30 +000056
Georg Brandl2ad07c32009-09-16 14:24:29 +000057def extract_tb(tb, limit=None):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000058 """Return list of up to limit pre-processed entries from traceback.
59
60 This is useful for alternate formatting of stack traces. If
61 'limit' is omitted or None, all entries are extracted. A
62 pre-processed stack trace entry is a quadruple (filename, line
63 number, function name, text) representing the information that is
64 usually printed for a stack trace. The text is a string with
65 leading and trailing whitespace stripped; if the source is not
66 available it is None.
67 """
Robert Collins6bc2c1e2015-03-05 12:07:57 +130068 return StackSummary.extract(walk_tb(tb), limit=limit)
Guido van Rossum526beed1994-07-01 15:36:46 +000069
Benjamin Petersond9fec152013-04-29 16:09:39 -040070#
71# Exception formatting and output.
72#
Guido van Rossum28e99fe1995-08-04 04:30:30 +000073
Benjamin Petersone6528212008-07-15 15:32:09 +000074_cause_message = (
75 "\nThe above exception was the direct cause "
Robert Collins6bc2c1e2015-03-05 12:07:57 +130076 "of the following exception:\n\n")
Benjamin Petersone6528212008-07-15 15:32:09 +000077
78_context_message = (
79 "\nDuring handling of the above exception, "
Robert Collins6bc2c1e2015-03-05 12:07:57 +130080 "another exception occurred:\n\n")
Benjamin Petersone6528212008-07-15 15:32:09 +000081
Benjamin Petersone6528212008-07-15 15:32:09 +000082
83def print_exception(etype, value, tb, limit=None, file=None, chain=True):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000084 """Print exception up to 'limit' stack trace entries from 'tb' to 'file'.
85
86 This differs from print_tb() in the following ways: (1) if
87 traceback is not None, it prints a header "Traceback (most recent
88 call last):"; (2) it prints the exception type and value after the
89 stack trace; (3) if type is SyntaxError and value has the
90 appropriate format, it prints the line where the syntax error
Tim Petersb90f89a2001-01-15 03:26:36 +000091 occurred with a caret on the next line indicating the approximate
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000092 position of the error.
93 """
Robert Collins2f0441f2015-03-05 15:45:01 +130094 # format_exception has ignored etype for some time, and code such as cgitb
95 # passes in bogus values as a result. For compatibility with such code we
96 # ignore it here (rather than in the new TracebackException API).
Raymond Hettinger10ff7062002-06-02 03:04:52 +000097 if file is None:
Tim Petersb90f89a2001-01-15 03:26:36 +000098 file = sys.stderr
Robert Collins6bc2c1e2015-03-05 12:07:57 +130099 for line in TracebackException(
Robert Collins2f0441f2015-03-05 15:45:01 +1300100 type(value), value, tb, limit=limit).format(chain=chain):
Benjamin Petersond9fec152013-04-29 16:09:39 -0400101 print(line, file=file, end="")
Guido van Rossum28e99fe1995-08-04 04:30:30 +0000102
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300103
Benjamin Petersone6528212008-07-15 15:32:09 +0000104def format_exception(etype, value, tb, limit=None, chain=True):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000105 """Format a stack trace and the exception information.
106
107 The arguments have the same meaning as the corresponding arguments
108 to print_exception(). The return value is a list of strings, each
Tim Petersb90f89a2001-01-15 03:26:36 +0000109 ending in a newline and some containing internal newlines. When
110 these lines are concatenated and printed, exactly the same text is
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000111 printed as does print_exception().
112 """
Robert Collins2f0441f2015-03-05 15:45:01 +1300113 # format_exception has ignored etype for some time, and code such as cgitb
114 # passes in bogus values as a result. For compatibility with such code we
115 # ignore it here (rather than in the new TracebackException API).
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300116 return list(TracebackException(
Robert Collins2f0441f2015-03-05 15:45:01 +1300117 type(value), value, tb, limit=limit).format(chain=chain))
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300118
Guido van Rossum28e99fe1995-08-04 04:30:30 +0000119
120def format_exception_only(etype, value):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000121 """Format the exception part of a traceback.
122
123 The arguments are the exception type and value such as given by
124 sys.last_type and sys.last_value. The return value is a list of
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000125 strings, each ending in a newline.
126
127 Normally, the list contains a single string; however, for
128 SyntaxError exceptions, it contains several lines that (when
129 printed) display detailed information about where the syntax
130 error occurred.
131
132 The message indicating which exception occurred is always the last
133 string in the list.
134
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000135 """
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300136 return list(TracebackException(etype, value, None).format_exception_only())
Benjamin Petersond9fec152013-04-29 16:09:39 -0400137
Thomas Wouters89f507f2006-12-13 04:49:30 +0000138
Martin Panter46f50722016-05-26 05:35:26 +0000139# -- not official API but folk probably use these two functions.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000140
141def _format_final_exc_line(etype, value):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000142 valuestr = _some_str(value)
Martin Panterbb8b1cb2016-09-22 09:37:39 +0000143 if value is None or not valuestr:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000144 line = "%s\n" % etype
Tim Petersb90f89a2001-01-15 03:26:36 +0000145 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000146 line = "%s: %s\n" % (etype, valuestr)
147 return line
Guido van Rossum28e99fe1995-08-04 04:30:30 +0000148
Guido van Rossum2823f032000-08-22 02:04:46 +0000149def _some_str(value):
Tim Petersb90f89a2001-01-15 03:26:36 +0000150 try:
151 return str(value)
152 except:
153 return '<unprintable %s object>' % type(value).__name__
Guido van Rossum2823f032000-08-22 02:04:46 +0000154
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300155# --
156
Benjamin Petersone6528212008-07-15 15:32:09 +0000157def print_exc(limit=None, file=None, chain=True):
Neal Norwitzac3625f2006-03-17 05:49:33 +0000158 """Shorthand for 'print_exception(*sys.exc_info(), limit, file)'."""
Benjamin Petersond9fec152013-04-29 16:09:39 -0400159 print_exception(*sys.exc_info(), limit=limit, file=file, chain=chain)
Neil Schemenauerf607fc52003-11-05 23:03:00 +0000160
Benjamin Petersone6528212008-07-15 15:32:09 +0000161def format_exc(limit=None, chain=True):
Neil Schemenauerf607fc52003-11-05 23:03:00 +0000162 """Like print_exc() but return a string."""
Benjamin Petersond9fec152013-04-29 16:09:39 -0400163 return "".join(format_exception(*sys.exc_info(), limit=limit, chain=chain))
Neil Schemenauerf607fc52003-11-05 23:03:00 +0000164
Benjamin Petersone6528212008-07-15 15:32:09 +0000165def print_last(limit=None, file=None, chain=True):
Tim Petersb90f89a2001-01-15 03:26:36 +0000166 """This is a shorthand for 'print_exception(sys.last_type,
167 sys.last_value, sys.last_traceback, limit, file)'."""
Benjamin Petersone549ead2009-03-28 21:42:05 +0000168 if not hasattr(sys, "last_type"):
169 raise ValueError("no last exception")
Tim Petersb90f89a2001-01-15 03:26:36 +0000170 print_exception(sys.last_type, sys.last_value, sys.last_traceback,
Benjamin Petersone6528212008-07-15 15:32:09 +0000171 limit, file, chain)
Guido van Rossumdcc057a1996-08-12 23:18:13 +0000172
Benjamin Petersond9fec152013-04-29 16:09:39 -0400173#
174# Printing and Extracting Stacks.
175#
176
Guido van Rossumdcc057a1996-08-12 23:18:13 +0000177def print_stack(f=None, limit=None, file=None):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000178 """Print a stack trace from its invocation point.
Tim Petersa19a1682001-03-29 04:36:09 +0000179
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000180 The optional 'f' argument can be used to specify an alternate
181 stack frame at which to start. The optional 'limit' and 'file'
182 arguments have the same meaning as for print_exception().
183 """
Serhiy Storchakae953ba72015-09-18 10:04:47 +0300184 if f is None:
185 f = sys._getframe().f_back
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300186 print_list(extract_stack(f, limit=limit), file=file)
187
Guido van Rossumdcc057a1996-08-12 23:18:13 +0000188
189def format_stack(f=None, limit=None):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000190 """Shorthand for 'format_list(extract_stack(f, limit))'."""
Serhiy Storchakae953ba72015-09-18 10:04:47 +0300191 if f is None:
192 f = sys._getframe().f_back
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300193 return format_list(extract_stack(f, limit=limit))
194
Guido van Rossumdcc057a1996-08-12 23:18:13 +0000195
Georg Brandl2ad07c32009-09-16 14:24:29 +0000196def extract_stack(f=None, limit=None):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000197 """Extract the raw traceback from the current stack frame.
198
199 The return value has the same format as for extract_tb(). The
200 optional 'f' and 'limit' arguments have the same meaning as for
201 print_stack(). Each item in the list is a quadruple (filename,
202 line number, function name, text), and the entries are in order
203 from oldest to newest stack frame.
204 """
Serhiy Storchakae953ba72015-09-18 10:04:47 +0300205 if f is None:
206 f = sys._getframe().f_back
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300207 stack = StackSummary.extract(walk_stack(f), limit=limit)
Benjamin Petersond9fec152013-04-29 16:09:39 -0400208 stack.reverse()
209 return stack
Andrew Kuchling173a1572013-09-15 18:15:56 -0400210
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300211
Andrew Kuchling173a1572013-09-15 18:15:56 -0400212def clear_frames(tb):
213 "Clear all references to local variables in the frames of a traceback."
214 while tb is not None:
215 try:
216 tb.tb_frame.clear()
217 except RuntimeError:
218 # Ignore the exception raised if the frame is still executing.
219 pass
220 tb = tb.tb_next
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300221
222
223class FrameSummary:
224 """A single frame from a traceback.
225
226 - :attr:`filename` The filename for the frame.
227 - :attr:`lineno` The line within filename for the frame that was
228 active when the frame was captured.
229 - :attr:`name` The name of the function or method that was executing
230 when the frame was captured.
231 - :attr:`line` The text from the linecache module for the
232 of code that was running when the frame was captured.
233 - :attr:`locals` Either None if locals were not supplied, or a dict
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300234 mapping the name to the repr() of the variable.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300235 """
236
237 __slots__ = ('filename', 'lineno', 'name', '_line', 'locals')
238
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300239 def __init__(self, filename, lineno, name, *, lookup_line=True,
240 locals=None, line=None):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300241 """Construct a FrameSummary.
242
243 :param lookup_line: If True, `linecache` is consulted for the source
244 code line. Otherwise, the line will be looked up when first needed.
245 :param locals: If supplied the frame locals, which will be captured as
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300246 object representations.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300247 :param line: If provided, use this instead of looking up the line in
248 the linecache.
249 """
250 self.filename = filename
251 self.lineno = lineno
252 self.name = name
253 self._line = line
254 if lookup_line:
255 self.line
Jon Dufresne39726282017-05-18 07:35:54 -0700256 self.locals = {k: repr(v) for k, v in locals.items()} if locals else None
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300257
258 def __eq__(self, other):
Serhiy Storchaka3066fc42015-09-29 22:33:36 +0300259 if isinstance(other, FrameSummary):
260 return (self.filename == other.filename and
261 self.lineno == other.lineno and
262 self.name == other.name and
263 self.locals == other.locals)
264 if isinstance(other, tuple):
265 return (self.filename, self.lineno, self.name, self.line) == other
266 return NotImplemented
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300267
268 def __getitem__(self, pos):
269 return (self.filename, self.lineno, self.name, self.line)[pos]
270
271 def __iter__(self):
272 return iter([self.filename, self.lineno, self.name, self.line])
273
274 def __repr__(self):
275 return "<FrameSummary file {filename}, line {lineno} in {name}>".format(
276 filename=self.filename, lineno=self.lineno, name=self.name)
277
278 @property
279 def line(self):
280 if self._line is None:
281 self._line = linecache.getline(self.filename, self.lineno).strip()
282 return self._line
283
284
285def walk_stack(f):
286 """Walk a stack yielding the frame and line number for each frame.
287
288 This will follow f.f_back from the given frame. If no frame is given, the
289 current stack is used. Usually used with StackSummary.extract.
290 """
291 if f is None:
292 f = sys._getframe().f_back.f_back
293 while f is not None:
294 yield f, f.f_lineno
295 f = f.f_back
296
297
298def walk_tb(tb):
299 """Walk a traceback yielding the frame and line number for each frame.
300
301 This will follow tb.tb_next (and thus is in the opposite order to
302 walk_stack). Usually used with StackSummary.extract.
303 """
304 while tb is not None:
305 yield tb.tb_frame, tb.tb_lineno
306 tb = tb.tb_next
307
308
309class StackSummary(list):
310 """A stack of frames."""
311
312 @classmethod
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300313 def extract(klass, frame_gen, *, limit=None, lookup_lines=True,
314 capture_locals=False):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300315 """Create a StackSummary from a traceback or stack object.
316
317 :param frame_gen: A generator that yields (frame, lineno) tuples to
318 include in the stack.
319 :param limit: None to include all frames or the number of frames to
320 include.
321 :param lookup_lines: If True, lookup lines for each frame immediately,
322 otherwise lookup is deferred until the frame is rendered.
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300323 :param capture_locals: If True, the local variables from each frame will
324 be captured as object representations into the FrameSummary.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300325 """
326 if limit is None:
327 limit = getattr(sys, 'tracebacklimit', None)
Serhiy Storchaka24559e42015-05-03 13:19:46 +0300328 if limit is not None and limit < 0:
329 limit = 0
330 if limit is not None:
331 if limit >= 0:
332 frame_gen = itertools.islice(frame_gen, limit)
333 else:
334 frame_gen = collections.deque(frame_gen, maxlen=-limit)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300335
336 result = klass()
337 fnames = set()
Serhiy Storchaka24559e42015-05-03 13:19:46 +0300338 for f, lineno in frame_gen:
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300339 co = f.f_code
340 filename = co.co_filename
341 name = co.co_name
342
343 fnames.add(filename)
344 linecache.lazycache(filename, f.f_globals)
345 # Must defer line lookups until we have called checkcache.
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300346 if capture_locals:
347 f_locals = f.f_locals
348 else:
349 f_locals = None
350 result.append(FrameSummary(
351 filename, lineno, name, lookup_line=False, locals=f_locals))
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300352 for filename in fnames:
353 linecache.checkcache(filename)
354 # If immediate lookup was desired, trigger lookups now.
355 if lookup_lines:
356 for f in result:
357 f.line
358 return result
359
360 @classmethod
361 def from_list(klass, a_list):
362 """Create a StackSummary from a simple list of tuples.
363
364 This method supports the older Python API. Each tuple should be a
365 4-tuple with (filename, lineno, name, line) elements.
366 """
Robert Collinsbbb8ade2015-03-16 15:27:16 +1300367 # While doing a fast-path check for isinstance(a_list, StackSummary) is
368 # appealing, idlelib.run.cleanup_traceback and other similar code may
369 # break this by making arbitrary frames plain tuples, so we need to
370 # check on a frame by frame basis.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300371 result = StackSummary()
Robert Collinsbbb8ade2015-03-16 15:27:16 +1300372 for frame in a_list:
373 if isinstance(frame, FrameSummary):
374 result.append(frame)
375 else:
376 filename, lineno, name, line = frame
377 result.append(FrameSummary(filename, lineno, name, line=line))
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300378 return result
379
380 def format(self):
381 """Format the stack ready for printing.
382
383 Returns a list of strings ready for printing. Each string in the
384 resulting list corresponds to a single frame from the stack.
385 Each string ends in a newline; the strings may contain internal
386 newlines as well, for those items with source text lines.
Nick Coghland0034232016-08-15 13:11:34 +1000387
388 For long sequences of the same frame and line, the first few
389 repetitions are shown, followed by a summary line stating the exact
390 number of further repetitions.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300391 """
392 result = []
Nick Coghland0034232016-08-15 13:11:34 +1000393 last_file = None
394 last_line = None
395 last_name = None
396 count = 0
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300397 for frame in self:
Nick Coghland0034232016-08-15 13:11:34 +1000398 if (last_file is not None and last_file == frame.filename and
399 last_line is not None and last_line == frame.lineno and
400 last_name is not None and last_name == frame.name):
401 count += 1
402 else:
403 if count > 3:
Eric V. Smith451d0e32016-09-09 21:56:20 -0400404 result.append(f' [Previous line repeated {count-3} more times]\n')
Nick Coghland0034232016-08-15 13:11:34 +1000405 last_file = frame.filename
406 last_line = frame.lineno
407 last_name = frame.name
408 count = 0
409 if count >= 3:
410 continue
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300411 row = []
412 row.append(' File "{}", line {}, in {}\n'.format(
413 frame.filename, frame.lineno, frame.name))
414 if frame.line:
415 row.append(' {}\n'.format(frame.line.strip()))
416 if frame.locals:
417 for name, value in sorted(frame.locals.items()):
418 row.append(' {name} = {value}\n'.format(name=name, value=value))
419 result.append(''.join(row))
Nick Coghland0034232016-08-15 13:11:34 +1000420 if count > 3:
Eric V. Smith451d0e32016-09-09 21:56:20 -0400421 result.append(f' [Previous line repeated {count-3} more times]\n')
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300422 return result
423
424
425class TracebackException:
426 """An exception ready for rendering.
427
428 The traceback module captures enough attributes from the original exception
429 to this intermediary form to ensure that no references are held, while
430 still being able to fully print or format it.
431
432 Use `from_exception` to create TracebackException instances from exception
433 objects, or the constructor to create TracebackException instances from
434 individual components.
435
436 - :attr:`__cause__` A TracebackException of the original *__cause__*.
437 - :attr:`__context__` A TracebackException of the original *__context__*.
438 - :attr:`__suppress_context__` The *__suppress_context__* value from the
439 original exception.
440 - :attr:`stack` A `StackSummary` representing the traceback.
441 - :attr:`exc_type` The class of the original traceback.
442 - :attr:`filename` For syntax errors - the filename where the error
Martin Panter46f50722016-05-26 05:35:26 +0000443 occurred.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300444 - :attr:`lineno` For syntax errors - the linenumber where the error
Martin Panter46f50722016-05-26 05:35:26 +0000445 occurred.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300446 - :attr:`text` For syntax errors - the text where the error
Martin Panter46f50722016-05-26 05:35:26 +0000447 occurred.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300448 - :attr:`offset` For syntax errors - the offset into the text where the
Martin Panter46f50722016-05-26 05:35:26 +0000449 error occurred.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300450 - :attr:`msg` For syntax errors - the compiler error message.
451 """
452
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300453 def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
454 lookup_lines=True, capture_locals=False, _seen=None):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300455 # NB: we need to accept exc_traceback, exc_value, exc_traceback to
456 # permit backwards compat with the existing API, otherwise we
457 # need stub thunk objects just to glue it together.
458 # Handle loops in __cause__ or __context__.
459 if _seen is None:
460 _seen = set()
Zane Bitterde860732017-10-17 17:29:39 -0400461 _seen.add(id(exc_value))
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300462 # Gracefully handle (the way Python 2.4 and earlier did) the case of
463 # being called with no type or value (None, None, None).
464 if (exc_value and exc_value.__cause__ is not None
Zane Bitterde860732017-10-17 17:29:39 -0400465 and id(exc_value.__cause__) not in _seen):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300466 cause = TracebackException(
467 type(exc_value.__cause__),
468 exc_value.__cause__,
469 exc_value.__cause__.__traceback__,
470 limit=limit,
471 lookup_lines=False,
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300472 capture_locals=capture_locals,
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300473 _seen=_seen)
474 else:
475 cause = None
476 if (exc_value and exc_value.__context__ is not None
Zane Bitterde860732017-10-17 17:29:39 -0400477 and id(exc_value.__context__) not in _seen):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300478 context = TracebackException(
479 type(exc_value.__context__),
480 exc_value.__context__,
481 exc_value.__context__.__traceback__,
482 limit=limit,
483 lookup_lines=False,
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300484 capture_locals=capture_locals,
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300485 _seen=_seen)
486 else:
487 context = None
Berker Peksagc3f417d2015-07-24 17:36:21 +0300488 self.exc_traceback = exc_traceback
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300489 self.__cause__ = cause
490 self.__context__ = context
491 self.__suppress_context__ = \
492 exc_value.__suppress_context__ if exc_value else False
493 # TODO: locals.
494 self.stack = StackSummary.extract(
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300495 walk_tb(exc_traceback), limit=limit, lookup_lines=lookup_lines,
496 capture_locals=capture_locals)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300497 self.exc_type = exc_type
498 # Capture now to permit freeing resources: only complication is in the
499 # unofficial API _format_final_exc_line
500 self._str = _some_str(exc_value)
501 if exc_type and issubclass(exc_type, SyntaxError):
502 # Handle SyntaxError's specially
503 self.filename = exc_value.filename
504 self.lineno = str(exc_value.lineno)
505 self.text = exc_value.text
506 self.offset = exc_value.offset
507 self.msg = exc_value.msg
508 if lookup_lines:
509 self._load_lines()
510
511 @classmethod
Robert Collinsaece8242015-07-26 06:50:51 +1200512 def from_exception(cls, exc, *args, **kwargs):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300513 """Create a TracebackException from an exception."""
Robert Collinsaece8242015-07-26 06:50:51 +1200514 return cls(type(exc), exc, exc.__traceback__, *args, **kwargs)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300515
516 def _load_lines(self):
517 """Private API. force all lines in the stack to be loaded."""
518 for frame in self.stack:
519 frame.line
520 if self.__context__:
521 self.__context__._load_lines()
522 if self.__cause__:
523 self.__cause__._load_lines()
524
525 def __eq__(self, other):
526 return self.__dict__ == other.__dict__
527
528 def __str__(self):
529 return self._str
530
531 def format_exception_only(self):
532 """Format the exception part of the traceback.
533
534 The return value is a generator of strings, each ending in a newline.
535
536 Normally, the generator emits a single string; however, for
537 SyntaxError exceptions, it emites several lines that (when
538 printed) display detailed information about where the syntax
539 error occurred.
540
541 The message indicating which exception occurred is always the last
542 string in the output.
543 """
544 if self.exc_type is None:
545 yield _format_final_exc_line(None, self._str)
546 return
547
548 stype = self.exc_type.__qualname__
549 smod = self.exc_type.__module__
550 if smod not in ("__main__", "builtins"):
551 stype = smod + '.' + stype
552
553 if not issubclass(self.exc_type, SyntaxError):
554 yield _format_final_exc_line(stype, self._str)
555 return
556
557 # It was a syntax error; show exactly where the problem was found.
558 filename = self.filename or "<string>"
559 lineno = str(self.lineno) or '?'
560 yield ' File "{}", line {}\n'.format(filename, lineno)
561
562 badline = self.text
563 offset = self.offset
564 if badline is not None:
565 yield ' {}\n'.format(badline.strip())
566 if offset is not None:
567 caretspace = badline.rstrip('\n')
568 offset = min(len(caretspace), offset) - 1
569 caretspace = caretspace[:offset].lstrip()
570 # non-space whitespace (likes tabs) must be kept for alignment
571 caretspace = ((c.isspace() and c or ' ') for c in caretspace)
572 yield ' {}^\n'.format(''.join(caretspace))
573 msg = self.msg or "<no detail available>"
574 yield "{}: {}\n".format(stype, msg)
575
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300576 def format(self, *, chain=True):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300577 """Format the exception.
578
579 If chain is not *True*, *__cause__* and *__context__* will not be formatted.
580
581 The return value is a generator of strings, each ending in a newline and
582 some containing internal newlines. `print_exception` is a wrapper around
583 this method which just prints the lines to a file.
584
585 The message indicating which exception occurred is always the last
586 string in the output.
587 """
588 if chain:
589 if self.__cause__ is not None:
590 yield from self.__cause__.format(chain=chain)
591 yield _cause_message
592 elif (self.__context__ is not None and
593 not self.__suppress_context__):
594 yield from self.__context__.format(chain=chain)
595 yield _context_message
Berker Peksagc3f417d2015-07-24 17:36:21 +0300596 if self.exc_traceback is not None:
597 yield 'Traceback (most recent call last):\n'
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300598 yield from self.stack.format()
599 yield from self.format_exception_only()