blob: 8a554cfc0683b4148962be02c9efeaf49e865014 [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
3import linecache
Guido van Rossum526beed1994-07-01 15:36:46 +00004import sys
Benjamin Petersond9fec152013-04-29 16:09:39 -04005import operator
Guido van Rossum526beed1994-07-01 15:36:46 +00006
Skip Montanaro40fc1602001-03-01 04:27:19 +00007__all__ = ['extract_stack', 'extract_tb', 'format_exception',
8 'format_exception_only', 'format_list', 'format_stack',
Neil Schemenauerf607fc52003-11-05 23:03:00 +00009 'format_tb', 'print_exc', 'format_exc', 'print_exception',
Berker Peksag716b3d32015-04-08 09:47:14 +030010 'print_last', 'print_stack', 'print_tb', 'clear_frames',
11 'FrameSummary', 'StackSummary', 'TracebackException',
12 'walk_stack', 'walk_tb']
Skip Montanaro40fc1602001-03-01 04:27:19 +000013
Benjamin Petersond9fec152013-04-29 16:09:39 -040014#
15# Formatting and printing lists of traceback lines.
16#
Guido van Rossumdcc057a1996-08-12 23:18:13 +000017
Guido van Rossumdcc057a1996-08-12 23:18:13 +000018def print_list(extracted_list, file=None):
Tim Petersb90f89a2001-01-15 03:26:36 +000019 """Print the list of tuples as returned by extract_tb() or
20 extract_stack() as a formatted stack trace to the given file."""
Raymond Hettinger10ff7062002-06-02 03:04:52 +000021 if file is None:
Tim Petersb90f89a2001-01-15 03:26:36 +000022 file = sys.stderr
Robert Collins6bc2c1e2015-03-05 12:07:57 +130023 for item in StackSummary.from_list(extracted_list).format():
Benjamin Petersond9fec152013-04-29 16:09:39 -040024 print(item, file=file, end="")
Guido van Rossumdcc057a1996-08-12 23:18:13 +000025
26def format_list(extracted_list):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000027 """Format a list of traceback entry tuples for printing.
28
29 Given a list of tuples as returned by extract_tb() or
Tim Petersb90f89a2001-01-15 03:26:36 +000030 extract_stack(), return a list of strings ready for printing.
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000031 Each string in the resulting list corresponds to the item with the
32 same index in the argument list. Each string ends in a newline;
33 the strings may contain internal newlines as well, for those items
34 whose source text line is not None.
35 """
Robert Collins6bc2c1e2015-03-05 12:07:57 +130036 return StackSummary.from_list(extracted_list).format()
Tim Petersb90f89a2001-01-15 03:26:36 +000037
Benjamin Petersond9fec152013-04-29 16:09:39 -040038#
39# Printing and Extracting Tracebacks.
40#
41
Guido van Rossum194e20a1995-09-20 20:31:51 +000042def print_tb(tb, limit=None, file=None):
Tim Petersb90f89a2001-01-15 03:26:36 +000043 """Print up to 'limit' stack trace entries from the traceback 'tb'.
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000044
45 If 'limit' is omitted or None, all entries are printed. If 'file'
46 is omitted or None, the output goes to sys.stderr; otherwise
47 'file' should be an open file or file-like object with a write()
48 method.
49 """
Benjamin Petersond9fec152013-04-29 16:09:39 -040050 print_list(extract_tb(tb, limit=limit), file=file)
Guido van Rossum526beed1994-07-01 15:36:46 +000051
Georg Brandl2ad07c32009-09-16 14:24:29 +000052def format_tb(tb, limit=None):
Georg Brandl9e091e12013-10-13 23:32:14 +020053 """A shorthand for 'format_list(extract_tb(tb, limit))'."""
Robert Collins6bc2c1e2015-03-05 12:07:57 +130054 return extract_tb(tb, limit=limit).format()
Guido van Rossum28e99fe1995-08-04 04:30:30 +000055
Georg Brandl2ad07c32009-09-16 14:24:29 +000056def extract_tb(tb, limit=None):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000057 """Return list of up to limit pre-processed entries from traceback.
58
59 This is useful for alternate formatting of stack traces. If
60 'limit' is omitted or None, all entries are extracted. A
61 pre-processed stack trace entry is a quadruple (filename, line
62 number, function name, text) representing the information that is
63 usually printed for a stack trace. The text is a string with
64 leading and trailing whitespace stripped; if the source is not
65 available it is None.
66 """
Robert Collins6bc2c1e2015-03-05 12:07:57 +130067 return StackSummary.extract(walk_tb(tb), limit=limit)
Guido van Rossum526beed1994-07-01 15:36:46 +000068
Benjamin Petersond9fec152013-04-29 16:09:39 -040069#
70# Exception formatting and output.
71#
Guido van Rossum28e99fe1995-08-04 04:30:30 +000072
Benjamin Petersone6528212008-07-15 15:32:09 +000073_cause_message = (
74 "\nThe above exception was the direct cause "
Robert Collins6bc2c1e2015-03-05 12:07:57 +130075 "of the following exception:\n\n")
Benjamin Petersone6528212008-07-15 15:32:09 +000076
77_context_message = (
78 "\nDuring handling of the above exception, "
Robert Collins6bc2c1e2015-03-05 12:07:57 +130079 "another exception occurred:\n\n")
Benjamin Petersone6528212008-07-15 15:32:09 +000080
Benjamin Petersone6528212008-07-15 15:32:09 +000081
82def print_exception(etype, value, tb, limit=None, file=None, chain=True):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000083 """Print exception up to 'limit' stack trace entries from 'tb' to 'file'.
84
85 This differs from print_tb() in the following ways: (1) if
86 traceback is not None, it prints a header "Traceback (most recent
87 call last):"; (2) it prints the exception type and value after the
88 stack trace; (3) if type is SyntaxError and value has the
89 appropriate format, it prints the line where the syntax error
Tim Petersb90f89a2001-01-15 03:26:36 +000090 occurred with a caret on the next line indicating the approximate
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000091 position of the error.
92 """
Robert Collins2f0441f2015-03-05 15:45:01 +130093 # format_exception has ignored etype for some time, and code such as cgitb
94 # passes in bogus values as a result. For compatibility with such code we
95 # ignore it here (rather than in the new TracebackException API).
Raymond Hettinger10ff7062002-06-02 03:04:52 +000096 if file is None:
Tim Petersb90f89a2001-01-15 03:26:36 +000097 file = sys.stderr
Robert Collins6bc2c1e2015-03-05 12:07:57 +130098 for line in TracebackException(
Robert Collins2f0441f2015-03-05 15:45:01 +130099 type(value), value, tb, limit=limit).format(chain=chain):
Benjamin Petersond9fec152013-04-29 16:09:39 -0400100 print(line, file=file, end="")
Guido van Rossum28e99fe1995-08-04 04:30:30 +0000101
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300102
Benjamin Petersone6528212008-07-15 15:32:09 +0000103def format_exception(etype, value, tb, limit=None, chain=True):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000104 """Format a stack trace and the exception information.
105
106 The arguments have the same meaning as the corresponding arguments
107 to print_exception(). The return value is a list of strings, each
Tim Petersb90f89a2001-01-15 03:26:36 +0000108 ending in a newline and some containing internal newlines. When
109 these lines are concatenated and printed, exactly the same text is
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000110 printed as does print_exception().
111 """
Robert Collins2f0441f2015-03-05 15:45:01 +1300112 # format_exception has ignored etype for some time, and code such as cgitb
113 # passes in bogus values as a result. For compatibility with such code we
114 # ignore it here (rather than in the new TracebackException API).
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300115 return list(TracebackException(
Robert Collins2f0441f2015-03-05 15:45:01 +1300116 type(value), value, tb, limit=limit).format(chain=chain))
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300117
Guido van Rossum28e99fe1995-08-04 04:30:30 +0000118
119def format_exception_only(etype, value):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000120 """Format the exception part of a traceback.
121
122 The arguments are the exception type and value such as given by
123 sys.last_type and sys.last_value. The return value is a list of
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000124 strings, each ending in a newline.
125
126 Normally, the list contains a single string; however, for
127 SyntaxError exceptions, it contains several lines that (when
128 printed) display detailed information about where the syntax
129 error occurred.
130
131 The message indicating which exception occurred is always the last
132 string in the list.
133
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000134 """
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300135 return list(TracebackException(etype, value, None).format_exception_only())
Benjamin Petersond9fec152013-04-29 16:09:39 -0400136
Thomas Wouters89f507f2006-12-13 04:49:30 +0000137
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300138# -- not offical API but folk probably use these two functions.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000139
140def _format_final_exc_line(etype, value):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000141 valuestr = _some_str(value)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300142 if value == 'None' or value is None or not valuestr:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000143 line = "%s\n" % etype
Tim Petersb90f89a2001-01-15 03:26:36 +0000144 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000145 line = "%s: %s\n" % (etype, valuestr)
146 return line
Guido van Rossum28e99fe1995-08-04 04:30:30 +0000147
Guido van Rossum2823f032000-08-22 02:04:46 +0000148def _some_str(value):
Tim Petersb90f89a2001-01-15 03:26:36 +0000149 try:
150 return str(value)
151 except:
152 return '<unprintable %s object>' % type(value).__name__
Guido van Rossum2823f032000-08-22 02:04:46 +0000153
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300154# --
155
Benjamin Petersone6528212008-07-15 15:32:09 +0000156def print_exc(limit=None, file=None, chain=True):
Neal Norwitzac3625f2006-03-17 05:49:33 +0000157 """Shorthand for 'print_exception(*sys.exc_info(), limit, file)'."""
Benjamin Petersond9fec152013-04-29 16:09:39 -0400158 print_exception(*sys.exc_info(), limit=limit, file=file, chain=chain)
Neil Schemenauerf607fc52003-11-05 23:03:00 +0000159
Benjamin Petersone6528212008-07-15 15:32:09 +0000160def format_exc(limit=None, chain=True):
Neil Schemenauerf607fc52003-11-05 23:03:00 +0000161 """Like print_exc() but return a string."""
Benjamin Petersond9fec152013-04-29 16:09:39 -0400162 return "".join(format_exception(*sys.exc_info(), limit=limit, chain=chain))
Neil Schemenauerf607fc52003-11-05 23:03:00 +0000163
Benjamin Petersone6528212008-07-15 15:32:09 +0000164def print_last(limit=None, file=None, chain=True):
Tim Petersb90f89a2001-01-15 03:26:36 +0000165 """This is a shorthand for 'print_exception(sys.last_type,
166 sys.last_value, sys.last_traceback, limit, file)'."""
Benjamin Petersone549ead2009-03-28 21:42:05 +0000167 if not hasattr(sys, "last_type"):
168 raise ValueError("no last exception")
Tim Petersb90f89a2001-01-15 03:26:36 +0000169 print_exception(sys.last_type, sys.last_value, sys.last_traceback,
Benjamin Petersone6528212008-07-15 15:32:09 +0000170 limit, file, chain)
Guido van Rossumdcc057a1996-08-12 23:18:13 +0000171
Benjamin Petersond9fec152013-04-29 16:09:39 -0400172#
173# Printing and Extracting Stacks.
174#
175
Guido van Rossumdcc057a1996-08-12 23:18:13 +0000176def print_stack(f=None, limit=None, file=None):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000177 """Print a stack trace from its invocation point.
Tim Petersa19a1682001-03-29 04:36:09 +0000178
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000179 The optional 'f' argument can be used to specify an alternate
180 stack frame at which to start. The optional 'limit' and 'file'
181 arguments have the same meaning as for print_exception().
182 """
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300183 print_list(extract_stack(f, limit=limit), file=file)
184
Guido van Rossumdcc057a1996-08-12 23:18:13 +0000185
186def format_stack(f=None, limit=None):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000187 """Shorthand for 'format_list(extract_stack(f, limit))'."""
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300188 return format_list(extract_stack(f, limit=limit))
189
Guido van Rossumdcc057a1996-08-12 23:18:13 +0000190
Georg Brandl2ad07c32009-09-16 14:24:29 +0000191def extract_stack(f=None, limit=None):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000192 """Extract the raw traceback from the current stack frame.
193
194 The return value has the same format as for extract_tb(). The
195 optional 'f' and 'limit' arguments have the same meaning as for
196 print_stack(). Each item in the list is a quadruple (filename,
197 line number, function name, text), and the entries are in order
198 from oldest to newest stack frame.
199 """
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300200 stack = StackSummary.extract(walk_stack(f), limit=limit)
Benjamin Petersond9fec152013-04-29 16:09:39 -0400201 stack.reverse()
202 return stack
Andrew Kuchling173a1572013-09-15 18:15:56 -0400203
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300204
Andrew Kuchling173a1572013-09-15 18:15:56 -0400205def clear_frames(tb):
206 "Clear all references to local variables in the frames of a traceback."
207 while tb is not None:
208 try:
209 tb.tb_frame.clear()
210 except RuntimeError:
211 # Ignore the exception raised if the frame is still executing.
212 pass
213 tb = tb.tb_next
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300214
215
216class FrameSummary:
217 """A single frame from a traceback.
218
219 - :attr:`filename` The filename for the frame.
220 - :attr:`lineno` The line within filename for the frame that was
221 active when the frame was captured.
222 - :attr:`name` The name of the function or method that was executing
223 when the frame was captured.
224 - :attr:`line` The text from the linecache module for the
225 of code that was running when the frame was captured.
226 - :attr:`locals` Either None if locals were not supplied, or a dict
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300227 mapping the name to the repr() of the variable.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300228 """
229
230 __slots__ = ('filename', 'lineno', 'name', '_line', 'locals')
231
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300232 def __init__(self, filename, lineno, name, *, lookup_line=True,
233 locals=None, line=None):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300234 """Construct a FrameSummary.
235
236 :param lookup_line: If True, `linecache` is consulted for the source
237 code line. Otherwise, the line will be looked up when first needed.
238 :param locals: If supplied the frame locals, which will be captured as
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300239 object representations.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300240 :param line: If provided, use this instead of looking up the line in
241 the linecache.
242 """
243 self.filename = filename
244 self.lineno = lineno
245 self.name = name
246 self._line = line
247 if lookup_line:
248 self.line
249 self.locals = \
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300250 dict((k, repr(v)) for k, v in locals.items()) if locals else None
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300251
252 def __eq__(self, other):
253 return (self.filename == other.filename and
254 self.lineno == other.lineno and
255 self.name == other.name and
256 self.locals == other.locals)
257
258 def __getitem__(self, pos):
259 return (self.filename, self.lineno, self.name, self.line)[pos]
260
261 def __iter__(self):
262 return iter([self.filename, self.lineno, self.name, self.line])
263
264 def __repr__(self):
265 return "<FrameSummary file {filename}, line {lineno} in {name}>".format(
266 filename=self.filename, lineno=self.lineno, name=self.name)
267
268 @property
269 def line(self):
270 if self._line is None:
271 self._line = linecache.getline(self.filename, self.lineno).strip()
272 return self._line
273
274
275def walk_stack(f):
276 """Walk a stack yielding the frame and line number for each frame.
277
278 This will follow f.f_back from the given frame. If no frame is given, the
279 current stack is used. Usually used with StackSummary.extract.
280 """
281 if f is None:
282 f = sys._getframe().f_back.f_back
283 while f is not None:
284 yield f, f.f_lineno
285 f = f.f_back
286
287
288def walk_tb(tb):
289 """Walk a traceback yielding the frame and line number for each frame.
290
291 This will follow tb.tb_next (and thus is in the opposite order to
292 walk_stack). Usually used with StackSummary.extract.
293 """
294 while tb is not None:
295 yield tb.tb_frame, tb.tb_lineno
296 tb = tb.tb_next
297
298
299class StackSummary(list):
300 """A stack of frames."""
301
302 @classmethod
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300303 def extract(klass, frame_gen, *, limit=None, lookup_lines=True,
304 capture_locals=False):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300305 """Create a StackSummary from a traceback or stack object.
306
307 :param frame_gen: A generator that yields (frame, lineno) tuples to
308 include in the stack.
309 :param limit: None to include all frames or the number of frames to
310 include.
311 :param lookup_lines: If True, lookup lines for each frame immediately,
312 otherwise lookup is deferred until the frame is rendered.
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300313 :param capture_locals: If True, the local variables from each frame will
314 be captured as object representations into the FrameSummary.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300315 """
316 if limit is None:
317 limit = getattr(sys, 'tracebacklimit', None)
318
319 result = klass()
320 fnames = set()
321 for pos, (f, lineno) in enumerate(frame_gen):
322 if limit is not None and pos >= limit:
323 break
324 co = f.f_code
325 filename = co.co_filename
326 name = co.co_name
327
328 fnames.add(filename)
329 linecache.lazycache(filename, f.f_globals)
330 # Must defer line lookups until we have called checkcache.
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300331 if capture_locals:
332 f_locals = f.f_locals
333 else:
334 f_locals = None
335 result.append(FrameSummary(
336 filename, lineno, name, lookup_line=False, locals=f_locals))
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300337 for filename in fnames:
338 linecache.checkcache(filename)
339 # If immediate lookup was desired, trigger lookups now.
340 if lookup_lines:
341 for f in result:
342 f.line
343 return result
344
345 @classmethod
346 def from_list(klass, a_list):
347 """Create a StackSummary from a simple list of tuples.
348
349 This method supports the older Python API. Each tuple should be a
350 4-tuple with (filename, lineno, name, line) elements.
351 """
Robert Collinsbbb8ade2015-03-16 15:27:16 +1300352 # While doing a fast-path check for isinstance(a_list, StackSummary) is
353 # appealing, idlelib.run.cleanup_traceback and other similar code may
354 # break this by making arbitrary frames plain tuples, so we need to
355 # check on a frame by frame basis.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300356 result = StackSummary()
Robert Collinsbbb8ade2015-03-16 15:27:16 +1300357 for frame in a_list:
358 if isinstance(frame, FrameSummary):
359 result.append(frame)
360 else:
361 filename, lineno, name, line = frame
362 result.append(FrameSummary(filename, lineno, name, line=line))
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300363 return result
364
365 def format(self):
366 """Format the stack ready for printing.
367
368 Returns a list of strings ready for printing. Each string in the
369 resulting list corresponds to a single frame from the stack.
370 Each string ends in a newline; the strings may contain internal
371 newlines as well, for those items with source text lines.
372 """
373 result = []
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300374 for frame in self:
375 row = []
376 row.append(' File "{}", line {}, in {}\n'.format(
377 frame.filename, frame.lineno, frame.name))
378 if frame.line:
379 row.append(' {}\n'.format(frame.line.strip()))
380 if frame.locals:
381 for name, value in sorted(frame.locals.items()):
382 row.append(' {name} = {value}\n'.format(name=name, value=value))
383 result.append(''.join(row))
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300384 return result
385
386
387class TracebackException:
388 """An exception ready for rendering.
389
390 The traceback module captures enough attributes from the original exception
391 to this intermediary form to ensure that no references are held, while
392 still being able to fully print or format it.
393
394 Use `from_exception` to create TracebackException instances from exception
395 objects, or the constructor to create TracebackException instances from
396 individual components.
397
398 - :attr:`__cause__` A TracebackException of the original *__cause__*.
399 - :attr:`__context__` A TracebackException of the original *__context__*.
400 - :attr:`__suppress_context__` The *__suppress_context__* value from the
401 original exception.
402 - :attr:`stack` A `StackSummary` representing the traceback.
403 - :attr:`exc_type` The class of the original traceback.
404 - :attr:`filename` For syntax errors - the filename where the error
405 occured.
406 - :attr:`lineno` For syntax errors - the linenumber where the error
407 occured.
408 - :attr:`text` For syntax errors - the text where the error
409 occured.
410 - :attr:`offset` For syntax errors - the offset into the text where the
411 error occured.
412 - :attr:`msg` For syntax errors - the compiler error message.
413 """
414
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300415 def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
416 lookup_lines=True, capture_locals=False, _seen=None):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300417 # NB: we need to accept exc_traceback, exc_value, exc_traceback to
418 # permit backwards compat with the existing API, otherwise we
419 # need stub thunk objects just to glue it together.
420 # Handle loops in __cause__ or __context__.
421 if _seen is None:
422 _seen = set()
423 _seen.add(exc_value)
424 # Gracefully handle (the way Python 2.4 and earlier did) the case of
425 # being called with no type or value (None, None, None).
426 if (exc_value and exc_value.__cause__ is not None
427 and exc_value.__cause__ not in _seen):
428 cause = TracebackException(
429 type(exc_value.__cause__),
430 exc_value.__cause__,
431 exc_value.__cause__.__traceback__,
432 limit=limit,
433 lookup_lines=False,
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300434 capture_locals=capture_locals,
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300435 _seen=_seen)
436 else:
437 cause = None
438 if (exc_value and exc_value.__context__ is not None
439 and exc_value.__context__ not in _seen):
440 context = TracebackException(
441 type(exc_value.__context__),
442 exc_value.__context__,
443 exc_value.__context__.__traceback__,
444 limit=limit,
445 lookup_lines=False,
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300446 capture_locals=capture_locals,
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300447 _seen=_seen)
448 else:
449 context = None
450 self.__cause__ = cause
451 self.__context__ = context
452 self.__suppress_context__ = \
453 exc_value.__suppress_context__ if exc_value else False
454 # TODO: locals.
455 self.stack = StackSummary.extract(
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300456 walk_tb(exc_traceback), limit=limit, lookup_lines=lookup_lines,
457 capture_locals=capture_locals)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300458 self.exc_type = exc_type
459 # Capture now to permit freeing resources: only complication is in the
460 # unofficial API _format_final_exc_line
461 self._str = _some_str(exc_value)
462 if exc_type and issubclass(exc_type, SyntaxError):
463 # Handle SyntaxError's specially
464 self.filename = exc_value.filename
465 self.lineno = str(exc_value.lineno)
466 self.text = exc_value.text
467 self.offset = exc_value.offset
468 self.msg = exc_value.msg
469 if lookup_lines:
470 self._load_lines()
471
472 @classmethod
473 def from_exception(self, exc, *args, **kwargs):
474 """Create a TracebackException from an exception."""
475 return TracebackException(
476 type(exc), exc, exc.__traceback__, *args, **kwargs)
477
478 def _load_lines(self):
479 """Private API. force all lines in the stack to be loaded."""
480 for frame in self.stack:
481 frame.line
482 if self.__context__:
483 self.__context__._load_lines()
484 if self.__cause__:
485 self.__cause__._load_lines()
486
487 def __eq__(self, other):
488 return self.__dict__ == other.__dict__
489
490 def __str__(self):
491 return self._str
492
493 def format_exception_only(self):
494 """Format the exception part of the traceback.
495
496 The return value is a generator of strings, each ending in a newline.
497
498 Normally, the generator emits a single string; however, for
499 SyntaxError exceptions, it emites several lines that (when
500 printed) display detailed information about where the syntax
501 error occurred.
502
503 The message indicating which exception occurred is always the last
504 string in the output.
505 """
506 if self.exc_type is None:
507 yield _format_final_exc_line(None, self._str)
508 return
509
510 stype = self.exc_type.__qualname__
511 smod = self.exc_type.__module__
512 if smod not in ("__main__", "builtins"):
513 stype = smod + '.' + stype
514
515 if not issubclass(self.exc_type, SyntaxError):
516 yield _format_final_exc_line(stype, self._str)
517 return
518
519 # It was a syntax error; show exactly where the problem was found.
520 filename = self.filename or "<string>"
521 lineno = str(self.lineno) or '?'
522 yield ' File "{}", line {}\n'.format(filename, lineno)
523
524 badline = self.text
525 offset = self.offset
526 if badline is not None:
527 yield ' {}\n'.format(badline.strip())
528 if offset is not None:
529 caretspace = badline.rstrip('\n')
530 offset = min(len(caretspace), offset) - 1
531 caretspace = caretspace[:offset].lstrip()
532 # non-space whitespace (likes tabs) must be kept for alignment
533 caretspace = ((c.isspace() and c or ' ') for c in caretspace)
534 yield ' {}^\n'.format(''.join(caretspace))
535 msg = self.msg or "<no detail available>"
536 yield "{}: {}\n".format(stype, msg)
537
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300538 def format(self, *, chain=True):
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300539 """Format the exception.
540
541 If chain is not *True*, *__cause__* and *__context__* will not be formatted.
542
543 The return value is a generator of strings, each ending in a newline and
544 some containing internal newlines. `print_exception` is a wrapper around
545 this method which just prints the lines to a file.
546
547 The message indicating which exception occurred is always the last
548 string in the output.
549 """
550 if chain:
551 if self.__cause__ is not None:
552 yield from self.__cause__.format(chain=chain)
553 yield _cause_message
554 elif (self.__context__ is not None and
555 not self.__suppress_context__):
556 yield from self.__context__.format(chain=chain)
557 yield _context_message
558 yield 'Traceback (most recent call last):\n'
559 yield from self.stack.format()
560 yield from self.format_exception_only()