blob: 72e1e2a9f93affaf1646c3c94a3a69fab7256c06 [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',
Andrew Kuchling173a1572013-09-15 18:15:56 -040010 'print_last', 'print_stack', 'print_tb',
11 'clear_frames']
Skip Montanaro40fc1602001-03-01 04:27:19 +000012
Benjamin Petersond9fec152013-04-29 16:09:39 -040013#
14# Formatting and printing lists of traceback lines.
15#
Guido van Rossumdcc057a1996-08-12 23:18:13 +000016
Guido van Rossumdcc057a1996-08-12 23:18:13 +000017def print_list(extracted_list, file=None):
Tim Petersb90f89a2001-01-15 03:26:36 +000018 """Print the list of tuples as returned by extract_tb() or
19 extract_stack() as a formatted stack trace to the given file."""
Raymond Hettinger10ff7062002-06-02 03:04:52 +000020 if file is None:
Tim Petersb90f89a2001-01-15 03:26:36 +000021 file = sys.stderr
Robert Collins6bc2c1e2015-03-05 12:07:57 +130022 for item in StackSummary.from_list(extracted_list).format():
Benjamin Petersond9fec152013-04-29 16:09:39 -040023 print(item, file=file, end="")
Guido van Rossumdcc057a1996-08-12 23:18:13 +000024
25def format_list(extracted_list):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000026 """Format a list of traceback entry tuples for printing.
27
28 Given a list of tuples as returned by extract_tb() or
Tim Petersb90f89a2001-01-15 03:26:36 +000029 extract_stack(), return a list of strings ready for printing.
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000030 Each string in the resulting list corresponds to the item with the
31 same index in the argument list. Each string ends in a newline;
32 the strings may contain internal newlines as well, for those items
33 whose source text line is not None.
34 """
Robert Collins6bc2c1e2015-03-05 12:07:57 +130035 return StackSummary.from_list(extracted_list).format()
Tim Petersb90f89a2001-01-15 03:26:36 +000036
Benjamin Petersond9fec152013-04-29 16:09:39 -040037#
38# Printing and Extracting Tracebacks.
39#
40
Guido van Rossum194e20a1995-09-20 20:31:51 +000041def print_tb(tb, limit=None, file=None):
Tim Petersb90f89a2001-01-15 03:26:36 +000042 """Print up to 'limit' stack trace entries from the traceback 'tb'.
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000043
44 If 'limit' is omitted or None, all entries are printed. If 'file'
45 is omitted or None, the output goes to sys.stderr; otherwise
46 'file' should be an open file or file-like object with a write()
47 method.
48 """
Benjamin Petersond9fec152013-04-29 16:09:39 -040049 print_list(extract_tb(tb, limit=limit), file=file)
Guido van Rossum526beed1994-07-01 15:36:46 +000050
Georg Brandl2ad07c32009-09-16 14:24:29 +000051def format_tb(tb, limit=None):
Georg Brandl9e091e12013-10-13 23:32:14 +020052 """A shorthand for 'format_list(extract_tb(tb, limit))'."""
Robert Collins6bc2c1e2015-03-05 12:07:57 +130053 return extract_tb(tb, limit=limit).format()
Guido van Rossum28e99fe1995-08-04 04:30:30 +000054
Georg Brandl2ad07c32009-09-16 14:24:29 +000055def extract_tb(tb, limit=None):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000056 """Return list of up to limit pre-processed entries from traceback.
57
58 This is useful for alternate formatting of stack traces. If
59 'limit' is omitted or None, all entries are extracted. A
60 pre-processed stack trace entry is a quadruple (filename, line
61 number, function name, text) representing the information that is
62 usually printed for a stack trace. The text is a string with
63 leading and trailing whitespace stripped; if the source is not
64 available it is None.
65 """
Robert Collins6bc2c1e2015-03-05 12:07:57 +130066 return StackSummary.extract(walk_tb(tb), limit=limit)
Guido van Rossum526beed1994-07-01 15:36:46 +000067
Benjamin Petersond9fec152013-04-29 16:09:39 -040068#
69# Exception formatting and output.
70#
Guido van Rossum28e99fe1995-08-04 04:30:30 +000071
Benjamin Petersone6528212008-07-15 15:32:09 +000072_cause_message = (
73 "\nThe above exception was the direct cause "
Robert Collins6bc2c1e2015-03-05 12:07:57 +130074 "of the following exception:\n\n")
Benjamin Petersone6528212008-07-15 15:32:09 +000075
76_context_message = (
77 "\nDuring handling of the above exception, "
Robert Collins6bc2c1e2015-03-05 12:07:57 +130078 "another exception occurred:\n\n")
Benjamin Petersone6528212008-07-15 15:32:09 +000079
Benjamin Petersone6528212008-07-15 15:32:09 +000080
81def print_exception(etype, value, tb, limit=None, file=None, chain=True):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000082 """Print exception up to 'limit' stack trace entries from 'tb' to 'file'.
83
84 This differs from print_tb() in the following ways: (1) if
85 traceback is not None, it prints a header "Traceback (most recent
86 call last):"; (2) it prints the exception type and value after the
87 stack trace; (3) if type is SyntaxError and value has the
88 appropriate format, it prints the line where the syntax error
Tim Petersb90f89a2001-01-15 03:26:36 +000089 occurred with a caret on the next line indicating the approximate
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +000090 position of the error.
91 """
Robert Collins2f0441f2015-03-05 15:45:01 +130092 # format_exception has ignored etype for some time, and code such as cgitb
93 # passes in bogus values as a result. For compatibility with such code we
94 # ignore it here (rather than in the new TracebackException API).
Raymond Hettinger10ff7062002-06-02 03:04:52 +000095 if file is None:
Tim Petersb90f89a2001-01-15 03:26:36 +000096 file = sys.stderr
Robert Collins6bc2c1e2015-03-05 12:07:57 +130097 for line in TracebackException(
Robert Collins2f0441f2015-03-05 15:45:01 +130098 type(value), value, tb, limit=limit).format(chain=chain):
Benjamin Petersond9fec152013-04-29 16:09:39 -040099 print(line, file=file, end="")
Guido van Rossum28e99fe1995-08-04 04:30:30 +0000100
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300101
Benjamin Petersone6528212008-07-15 15:32:09 +0000102def format_exception(etype, value, tb, limit=None, chain=True):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000103 """Format a stack trace and the exception information.
104
105 The arguments have the same meaning as the corresponding arguments
106 to print_exception(). The return value is a list of strings, each
Tim Petersb90f89a2001-01-15 03:26:36 +0000107 ending in a newline and some containing internal newlines. When
108 these lines are concatenated and printed, exactly the same text is
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000109 printed as does print_exception().
110 """
Robert Collins2f0441f2015-03-05 15:45:01 +1300111 # format_exception has ignored etype for some time, and code such as cgitb
112 # passes in bogus values as a result. For compatibility with such code we
113 # ignore it here (rather than in the new TracebackException API).
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300114 return list(TracebackException(
Robert Collins2f0441f2015-03-05 15:45:01 +1300115 type(value), value, tb, limit=limit).format(chain=chain))
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300116
Guido van Rossum28e99fe1995-08-04 04:30:30 +0000117
118def format_exception_only(etype, value):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000119 """Format the exception part of a traceback.
120
121 The arguments are the exception type and value such as given by
122 sys.last_type and sys.last_value. The return value is a list of
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000123 strings, each ending in a newline.
124
125 Normally, the list contains a single string; however, for
126 SyntaxError exceptions, it contains several lines that (when
127 printed) display detailed information about where the syntax
128 error occurred.
129
130 The message indicating which exception occurred is always the last
131 string in the list.
132
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000133 """
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300134 return list(TracebackException(etype, value, None).format_exception_only())
Benjamin Petersond9fec152013-04-29 16:09:39 -0400135
Thomas Wouters89f507f2006-12-13 04:49:30 +0000136
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300137# -- not offical API but folk probably use these two functions.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000138
139def _format_final_exc_line(etype, value):
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000140 valuestr = _some_str(value)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300141 if value == 'None' or value is None or not valuestr:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000142 line = "%s\n" % etype
Tim Petersb90f89a2001-01-15 03:26:36 +0000143 else:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000144 line = "%s: %s\n" % (etype, valuestr)
145 return line
Guido van Rossum28e99fe1995-08-04 04:30:30 +0000146
Guido van Rossum2823f032000-08-22 02:04:46 +0000147def _some_str(value):
Tim Petersb90f89a2001-01-15 03:26:36 +0000148 try:
149 return str(value)
150 except:
151 return '<unprintable %s object>' % type(value).__name__
Guido van Rossum2823f032000-08-22 02:04:46 +0000152
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300153# --
154
Benjamin Petersone6528212008-07-15 15:32:09 +0000155def print_exc(limit=None, file=None, chain=True):
Neal Norwitzac3625f2006-03-17 05:49:33 +0000156 """Shorthand for 'print_exception(*sys.exc_info(), limit, file)'."""
Benjamin Petersond9fec152013-04-29 16:09:39 -0400157 print_exception(*sys.exc_info(), limit=limit, file=file, chain=chain)
Neil Schemenauerf607fc52003-11-05 23:03:00 +0000158
Benjamin Petersone6528212008-07-15 15:32:09 +0000159def format_exc(limit=None, chain=True):
Neil Schemenauerf607fc52003-11-05 23:03:00 +0000160 """Like print_exc() but return a string."""
Benjamin Petersond9fec152013-04-29 16:09:39 -0400161 return "".join(format_exception(*sys.exc_info(), limit=limit, chain=chain))
Neil Schemenauerf607fc52003-11-05 23:03:00 +0000162
Benjamin Petersone6528212008-07-15 15:32:09 +0000163def print_last(limit=None, file=None, chain=True):
Tim Petersb90f89a2001-01-15 03:26:36 +0000164 """This is a shorthand for 'print_exception(sys.last_type,
165 sys.last_value, sys.last_traceback, limit, file)'."""
Benjamin Petersone549ead2009-03-28 21:42:05 +0000166 if not hasattr(sys, "last_type"):
167 raise ValueError("no last exception")
Tim Petersb90f89a2001-01-15 03:26:36 +0000168 print_exception(sys.last_type, sys.last_value, sys.last_traceback,
Benjamin Petersone6528212008-07-15 15:32:09 +0000169 limit, file, chain)
Guido van Rossumdcc057a1996-08-12 23:18:13 +0000170
Benjamin Petersond9fec152013-04-29 16:09:39 -0400171#
172# Printing and Extracting Stacks.
173#
174
Guido van Rossumdcc057a1996-08-12 23:18:13 +0000175def print_stack(f=None, limit=None, file=None):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000176 """Print a stack trace from its invocation point.
Tim Petersa19a1682001-03-29 04:36:09 +0000177
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000178 The optional 'f' argument can be used to specify an alternate
179 stack frame at which to start. The optional 'limit' and 'file'
180 arguments have the same meaning as for print_exception().
181 """
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300182 print_list(extract_stack(f, limit=limit), file=file)
183
Guido van Rossumdcc057a1996-08-12 23:18:13 +0000184
185def format_stack(f=None, limit=None):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000186 """Shorthand for 'format_list(extract_stack(f, limit))'."""
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300187 return format_list(extract_stack(f, limit=limit))
188
Guido van Rossumdcc057a1996-08-12 23:18:13 +0000189
Georg Brandl2ad07c32009-09-16 14:24:29 +0000190def extract_stack(f=None, limit=None):
Jeremy Hylton69e9e8b2001-03-21 19:09:31 +0000191 """Extract the raw traceback from the current stack frame.
192
193 The return value has the same format as for extract_tb(). The
194 optional 'f' and 'limit' arguments have the same meaning as for
195 print_stack(). Each item in the list is a quadruple (filename,
196 line number, function name, text), and the entries are in order
197 from oldest to newest stack frame.
198 """
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300199 stack = StackSummary.extract(walk_stack(f), limit=limit)
Benjamin Petersond9fec152013-04-29 16:09:39 -0400200 stack.reverse()
201 return stack
Andrew Kuchling173a1572013-09-15 18:15:56 -0400202
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300203
Andrew Kuchling173a1572013-09-15 18:15:56 -0400204def clear_frames(tb):
205 "Clear all references to local variables in the frames of a traceback."
206 while tb is not None:
207 try:
208 tb.tb_frame.clear()
209 except RuntimeError:
210 # Ignore the exception raised if the frame is still executing.
211 pass
212 tb = tb.tb_next
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300213
214
215class FrameSummary:
216 """A single frame from a traceback.
217
218 - :attr:`filename` The filename for the frame.
219 - :attr:`lineno` The line within filename for the frame that was
220 active when the frame was captured.
221 - :attr:`name` The name of the function or method that was executing
222 when the frame was captured.
223 - :attr:`line` The text from the linecache module for the
224 of code that was running when the frame was captured.
225 - :attr:`locals` Either None if locals were not supplied, or a dict
226 mapping the name to the str() of the variable.
227 """
228
229 __slots__ = ('filename', 'lineno', 'name', '_line', 'locals')
230
231 def __init__(self, filename, lineno, name, lookup_line=True, locals=None,
232 line=None):
233 """Construct a FrameSummary.
234
235 :param lookup_line: If True, `linecache` is consulted for the source
236 code line. Otherwise, the line will be looked up when first needed.
237 :param locals: If supplied the frame locals, which will be captured as
238 strings.
239 :param line: If provided, use this instead of looking up the line in
240 the linecache.
241 """
242 self.filename = filename
243 self.lineno = lineno
244 self.name = name
245 self._line = line
246 if lookup_line:
247 self.line
248 self.locals = \
249 dict((k, str(v)) for k, v in locals.items()) if locals else None
250
251 def __eq__(self, other):
252 return (self.filename == other.filename and
253 self.lineno == other.lineno and
254 self.name == other.name and
255 self.locals == other.locals)
256
257 def __getitem__(self, pos):
258 return (self.filename, self.lineno, self.name, self.line)[pos]
259
260 def __iter__(self):
261 return iter([self.filename, self.lineno, self.name, self.line])
262
263 def __repr__(self):
264 return "<FrameSummary file {filename}, line {lineno} in {name}>".format(
265 filename=self.filename, lineno=self.lineno, name=self.name)
266
267 @property
268 def line(self):
269 if self._line is None:
270 self._line = linecache.getline(self.filename, self.lineno).strip()
271 return self._line
272
273
274def walk_stack(f):
275 """Walk a stack yielding the frame and line number for each frame.
276
277 This will follow f.f_back from the given frame. If no frame is given, the
278 current stack is used. Usually used with StackSummary.extract.
279 """
280 if f is None:
281 f = sys._getframe().f_back.f_back
282 while f is not None:
283 yield f, f.f_lineno
284 f = f.f_back
285
286
287def walk_tb(tb):
288 """Walk a traceback yielding the frame and line number for each frame.
289
290 This will follow tb.tb_next (and thus is in the opposite order to
291 walk_stack). Usually used with StackSummary.extract.
292 """
293 while tb is not None:
294 yield tb.tb_frame, tb.tb_lineno
295 tb = tb.tb_next
296
297
298class StackSummary(list):
299 """A stack of frames."""
300
301 @classmethod
302 def extract(klass, frame_gen, limit=None, lookup_lines=True):
303 """Create a StackSummary from a traceback or stack object.
304
305 :param frame_gen: A generator that yields (frame, lineno) tuples to
306 include in the stack.
307 :param limit: None to include all frames or the number of frames to
308 include.
309 :param lookup_lines: If True, lookup lines for each frame immediately,
310 otherwise lookup is deferred until the frame is rendered.
311 """
312 if limit is None:
313 limit = getattr(sys, 'tracebacklimit', None)
314
315 result = klass()
316 fnames = set()
317 for pos, (f, lineno) in enumerate(frame_gen):
318 if limit is not None and pos >= limit:
319 break
320 co = f.f_code
321 filename = co.co_filename
322 name = co.co_name
323
324 fnames.add(filename)
325 linecache.lazycache(filename, f.f_globals)
326 # Must defer line lookups until we have called checkcache.
327 result.append(FrameSummary(filename, lineno, name, lookup_line=False))
328 for filename in fnames:
329 linecache.checkcache(filename)
330 # If immediate lookup was desired, trigger lookups now.
331 if lookup_lines:
332 for f in result:
333 f.line
334 return result
335
336 @classmethod
337 def from_list(klass, a_list):
338 """Create a StackSummary from a simple list of tuples.
339
340 This method supports the older Python API. Each tuple should be a
341 4-tuple with (filename, lineno, name, line) elements.
342 """
343 if isinstance(a_list, StackSummary):
344 return StackSummary(a_list)
345 result = StackSummary()
346 for filename, lineno, name, line in a_list:
347 result.append(FrameSummary(filename, lineno, name, line=line))
348 return result
349
350 def format(self):
351 """Format the stack ready for printing.
352
353 Returns a list of strings ready for printing. Each string in the
354 resulting list corresponds to a single frame from the stack.
355 Each string ends in a newline; the strings may contain internal
356 newlines as well, for those items with source text lines.
357 """
358 result = []
359 for filename, lineno, name, line in self:
360 item = ' File "{}", line {}, in {}\n'.format(filename, lineno, name)
361 if line:
362 item = item + ' {}\n'.format(line.strip())
363 result.append(item)
364 return result
365
366
367class TracebackException:
368 """An exception ready for rendering.
369
370 The traceback module captures enough attributes from the original exception
371 to this intermediary form to ensure that no references are held, while
372 still being able to fully print or format it.
373
374 Use `from_exception` to create TracebackException instances from exception
375 objects, or the constructor to create TracebackException instances from
376 individual components.
377
378 - :attr:`__cause__` A TracebackException of the original *__cause__*.
379 - :attr:`__context__` A TracebackException of the original *__context__*.
380 - :attr:`__suppress_context__` The *__suppress_context__* value from the
381 original exception.
382 - :attr:`stack` A `StackSummary` representing the traceback.
383 - :attr:`exc_type` The class of the original traceback.
384 - :attr:`filename` For syntax errors - the filename where the error
385 occured.
386 - :attr:`lineno` For syntax errors - the linenumber where the error
387 occured.
388 - :attr:`text` For syntax errors - the text where the error
389 occured.
390 - :attr:`offset` For syntax errors - the offset into the text where the
391 error occured.
392 - :attr:`msg` For syntax errors - the compiler error message.
393 """
394
395 def __init__(self, exc_type, exc_value, exc_traceback, limit=None,
396 lookup_lines=True, _seen=None):
397 # NB: we need to accept exc_traceback, exc_value, exc_traceback to
398 # permit backwards compat with the existing API, otherwise we
399 # need stub thunk objects just to glue it together.
400 # Handle loops in __cause__ or __context__.
401 if _seen is None:
402 _seen = set()
403 _seen.add(exc_value)
404 # Gracefully handle (the way Python 2.4 and earlier did) the case of
405 # being called with no type or value (None, None, None).
406 if (exc_value and exc_value.__cause__ is not None
407 and exc_value.__cause__ not in _seen):
408 cause = TracebackException(
409 type(exc_value.__cause__),
410 exc_value.__cause__,
411 exc_value.__cause__.__traceback__,
412 limit=limit,
413 lookup_lines=False,
414 _seen=_seen)
415 else:
416 cause = None
417 if (exc_value and exc_value.__context__ is not None
418 and exc_value.__context__ not in _seen):
419 context = TracebackException(
420 type(exc_value.__context__),
421 exc_value.__context__,
422 exc_value.__context__.__traceback__,
423 limit=limit,
424 lookup_lines=False,
425 _seen=_seen)
426 else:
427 context = None
428 self.__cause__ = cause
429 self.__context__ = context
430 self.__suppress_context__ = \
431 exc_value.__suppress_context__ if exc_value else False
432 # TODO: locals.
433 self.stack = StackSummary.extract(
434 walk_tb(exc_traceback), limit=limit, lookup_lines=lookup_lines)
435 self.exc_type = exc_type
436 # Capture now to permit freeing resources: only complication is in the
437 # unofficial API _format_final_exc_line
438 self._str = _some_str(exc_value)
439 if exc_type and issubclass(exc_type, SyntaxError):
440 # Handle SyntaxError's specially
441 self.filename = exc_value.filename
442 self.lineno = str(exc_value.lineno)
443 self.text = exc_value.text
444 self.offset = exc_value.offset
445 self.msg = exc_value.msg
446 if lookup_lines:
447 self._load_lines()
448
449 @classmethod
450 def from_exception(self, exc, *args, **kwargs):
451 """Create a TracebackException from an exception."""
452 return TracebackException(
453 type(exc), exc, exc.__traceback__, *args, **kwargs)
454
455 def _load_lines(self):
456 """Private API. force all lines in the stack to be loaded."""
457 for frame in self.stack:
458 frame.line
459 if self.__context__:
460 self.__context__._load_lines()
461 if self.__cause__:
462 self.__cause__._load_lines()
463
464 def __eq__(self, other):
465 return self.__dict__ == other.__dict__
466
467 def __str__(self):
468 return self._str
469
470 def format_exception_only(self):
471 """Format the exception part of the traceback.
472
473 The return value is a generator of strings, each ending in a newline.
474
475 Normally, the generator emits a single string; however, for
476 SyntaxError exceptions, it emites several lines that (when
477 printed) display detailed information about where the syntax
478 error occurred.
479
480 The message indicating which exception occurred is always the last
481 string in the output.
482 """
483 if self.exc_type is None:
484 yield _format_final_exc_line(None, self._str)
485 return
486
487 stype = self.exc_type.__qualname__
488 smod = self.exc_type.__module__
489 if smod not in ("__main__", "builtins"):
490 stype = smod + '.' + stype
491
492 if not issubclass(self.exc_type, SyntaxError):
493 yield _format_final_exc_line(stype, self._str)
494 return
495
496 # It was a syntax error; show exactly where the problem was found.
497 filename = self.filename or "<string>"
498 lineno = str(self.lineno) or '?'
499 yield ' File "{}", line {}\n'.format(filename, lineno)
500
501 badline = self.text
502 offset = self.offset
503 if badline is not None:
504 yield ' {}\n'.format(badline.strip())
505 if offset is not None:
506 caretspace = badline.rstrip('\n')
507 offset = min(len(caretspace), offset) - 1
508 caretspace = caretspace[:offset].lstrip()
509 # non-space whitespace (likes tabs) must be kept for alignment
510 caretspace = ((c.isspace() and c or ' ') for c in caretspace)
511 yield ' {}^\n'.format(''.join(caretspace))
512 msg = self.msg or "<no detail available>"
513 yield "{}: {}\n".format(stype, msg)
514
515 def format(self, chain=True):
516 """Format the exception.
517
518 If chain is not *True*, *__cause__* and *__context__* will not be formatted.
519
520 The return value is a generator of strings, each ending in a newline and
521 some containing internal newlines. `print_exception` is a wrapper around
522 this method which just prints the lines to a file.
523
524 The message indicating which exception occurred is always the last
525 string in the output.
526 """
527 if chain:
528 if self.__cause__ is not None:
529 yield from self.__cause__.format(chain=chain)
530 yield _cause_message
531 elif (self.__context__ is not None and
532 not self.__suppress_context__):
533 yield from self.__context__.format(chain=chain)
534 yield _context_message
535 yield 'Traceback (most recent call last):\n'
536 yield from self.stack.format()
537 yield from self.format_exception_only()