Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 1 | """Extract, format and print information about Python stack traces.""" |
Guido van Rossum | 526beed | 1994-07-01 15:36:46 +0000 | [diff] [blame] | 2 | |
Serhiy Storchaka | 24559e4 | 2015-05-03 13:19:46 +0300 | [diff] [blame] | 3 | import collections |
| 4 | import itertools |
Guido van Rossum | 526beed | 1994-07-01 15:36:46 +0000 | [diff] [blame] | 5 | import linecache |
Guido van Rossum | 526beed | 1994-07-01 15:36:46 +0000 | [diff] [blame] | 6 | import sys |
| 7 | |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 8 | __all__ = ['extract_stack', 'extract_tb', 'format_exception', |
| 9 | 'format_exception_only', 'format_list', 'format_stack', |
Neil Schemenauer | f607fc5 | 2003-11-05 23:03:00 +0000 | [diff] [blame] | 10 | 'format_tb', 'print_exc', 'format_exc', 'print_exception', |
Berker Peksag | 716b3d3 | 2015-04-08 09:47:14 +0300 | [diff] [blame] | 11 | 'print_last', 'print_stack', 'print_tb', 'clear_frames', |
| 12 | 'FrameSummary', 'StackSummary', 'TracebackException', |
| 13 | 'walk_stack', 'walk_tb'] |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 14 | |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 15 | # |
| 16 | # Formatting and printing lists of traceback lines. |
| 17 | # |
Guido van Rossum | dcc057a | 1996-08-12 23:18:13 +0000 | [diff] [blame] | 18 | |
Guido van Rossum | dcc057a | 1996-08-12 23:18:13 +0000 | [diff] [blame] | 19 | def print_list(extracted_list, file=None): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 20 | """Print the list of tuples as returned by extract_tb() or |
| 21 | extract_stack() as a formatted stack trace to the given file.""" |
Raymond Hettinger | 10ff706 | 2002-06-02 03:04:52 +0000 | [diff] [blame] | 22 | if file is None: |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 23 | file = sys.stderr |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 24 | for item in StackSummary.from_list(extracted_list).format(): |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 25 | print(item, file=file, end="") |
Guido van Rossum | dcc057a | 1996-08-12 23:18:13 +0000 | [diff] [blame] | 26 | |
| 27 | def format_list(extracted_list): |
torsava | f394ee5 | 2018-08-02 17:08:59 +0100 | [diff] [blame] | 28 | """Format a list of tuples or FrameSummary objects for printing. |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 29 | |
torsava | f394ee5 | 2018-08-02 17:08:59 +0100 | [diff] [blame] | 30 | 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 Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 34 | 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 Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 39 | return StackSummary.from_list(extracted_list).format() |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 40 | |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 41 | # |
| 42 | # Printing and Extracting Tracebacks. |
| 43 | # |
| 44 | |
Guido van Rossum | 194e20a | 1995-09-20 20:31:51 +0000 | [diff] [blame] | 45 | def print_tb(tb, limit=None, file=None): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 46 | """Print up to 'limit' stack trace entries from the traceback 'tb'. |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 47 | |
| 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 Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 53 | print_list(extract_tb(tb, limit=limit), file=file) |
Guido van Rossum | 526beed | 1994-07-01 15:36:46 +0000 | [diff] [blame] | 54 | |
Georg Brandl | 2ad07c3 | 2009-09-16 14:24:29 +0000 | [diff] [blame] | 55 | def format_tb(tb, limit=None): |
Georg Brandl | 9e091e1 | 2013-10-13 23:32:14 +0200 | [diff] [blame] | 56 | """A shorthand for 'format_list(extract_tb(tb, limit))'.""" |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 57 | return extract_tb(tb, limit=limit).format() |
Guido van Rossum | 28e99fe | 1995-08-04 04:30:30 +0000 | [diff] [blame] | 58 | |
Georg Brandl | 2ad07c3 | 2009-09-16 14:24:29 +0000 | [diff] [blame] | 59 | def extract_tb(tb, limit=None): |
torsava | f394ee5 | 2018-08-02 17:08:59 +0100 | [diff] [blame] | 60 | """ |
| 61 | Return a StackSummary object representing a list of |
| 62 | pre-processed entries from traceback. |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 63 | |
| 64 | This is useful for alternate formatting of stack traces. If |
| 65 | 'limit' is omitted or None, all entries are extracted. A |
torsava | f394ee5 | 2018-08-02 17:08:59 +0100 | [diff] [blame] | 66 | 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 Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 71 | """ |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 72 | return StackSummary.extract(walk_tb(tb), limit=limit) |
Guido van Rossum | 526beed | 1994-07-01 15:36:46 +0000 | [diff] [blame] | 73 | |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 74 | # |
| 75 | # Exception formatting and output. |
| 76 | # |
Guido van Rossum | 28e99fe | 1995-08-04 04:30:30 +0000 | [diff] [blame] | 77 | |
Benjamin Peterson | e652821 | 2008-07-15 15:32:09 +0000 | [diff] [blame] | 78 | _cause_message = ( |
| 79 | "\nThe above exception was the direct cause " |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 80 | "of the following exception:\n\n") |
Benjamin Peterson | e652821 | 2008-07-15 15:32:09 +0000 | [diff] [blame] | 81 | |
| 82 | _context_message = ( |
| 83 | "\nDuring handling of the above exception, " |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 84 | "another exception occurred:\n\n") |
Benjamin Peterson | e652821 | 2008-07-15 15:32:09 +0000 | [diff] [blame] | 85 | |
Benjamin Peterson | e652821 | 2008-07-15 15:32:09 +0000 | [diff] [blame] | 86 | |
Zackery Spytz | 91e9379 | 2020-11-05 15:18:44 -0700 | [diff] [blame] | 87 | _sentinel = object() |
| 88 | |
| 89 | |
| 90 | def _parse_value_tb(exc, value, tb): |
| 91 | if (value is _sentinel) != (tb is _sentinel): |
| 92 | raise ValueError("Both or neither of value and tb must be given") |
| 93 | if value is tb is _sentinel: |
Irit Katriel | b798ab0 | 2021-02-23 17:43:04 +0000 | [diff] [blame] | 94 | if exc is not None: |
| 95 | return exc, exc.__traceback__ |
| 96 | else: |
| 97 | return None, None |
Zackery Spytz | 91e9379 | 2020-11-05 15:18:44 -0700 | [diff] [blame] | 98 | return value, tb |
| 99 | |
| 100 | |
| 101 | def print_exception(exc, /, value=_sentinel, tb=_sentinel, limit=None, \ |
| 102 | file=None, chain=True): |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 103 | """Print exception up to 'limit' stack trace entries from 'tb' to 'file'. |
| 104 | |
| 105 | This differs from print_tb() in the following ways: (1) if |
| 106 | traceback is not None, it prints a header "Traceback (most recent |
| 107 | call last):"; (2) it prints the exception type and value after the |
| 108 | stack trace; (3) if type is SyntaxError and value has the |
| 109 | appropriate format, it prints the line where the syntax error |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 110 | occurred with a caret on the next line indicating the approximate |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 111 | position of the error. |
| 112 | """ |
Zackery Spytz | 91e9379 | 2020-11-05 15:18:44 -0700 | [diff] [blame] | 113 | value, tb = _parse_value_tb(exc, value, tb) |
Raymond Hettinger | 10ff706 | 2002-06-02 03:04:52 +0000 | [diff] [blame] | 114 | if file is None: |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 115 | file = sys.stderr |
Irit Katriel | 4c94d74 | 2021-01-15 02:45:02 +0000 | [diff] [blame] | 116 | te = TracebackException(type(value), value, tb, limit=limit, compact=True) |
| 117 | for line in te.format(chain=chain): |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 118 | print(line, file=file, end="") |
Guido van Rossum | 28e99fe | 1995-08-04 04:30:30 +0000 | [diff] [blame] | 119 | |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 120 | |
Zackery Spytz | 91e9379 | 2020-11-05 15:18:44 -0700 | [diff] [blame] | 121 | def format_exception(exc, /, value=_sentinel, tb=_sentinel, limit=None, \ |
| 122 | chain=True): |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 123 | """Format a stack trace and the exception information. |
| 124 | |
| 125 | The arguments have the same meaning as the corresponding arguments |
| 126 | to print_exception(). The return value is a list of strings, each |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 127 | ending in a newline and some containing internal newlines. When |
| 128 | these lines are concatenated and printed, exactly the same text is |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 129 | printed as does print_exception(). |
| 130 | """ |
Zackery Spytz | 91e9379 | 2020-11-05 15:18:44 -0700 | [diff] [blame] | 131 | value, tb = _parse_value_tb(exc, value, tb) |
Irit Katriel | 4c94d74 | 2021-01-15 02:45:02 +0000 | [diff] [blame] | 132 | te = TracebackException(type(value), value, tb, limit=limit, compact=True) |
| 133 | return list(te.format(chain=chain)) |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 134 | |
Guido van Rossum | 28e99fe | 1995-08-04 04:30:30 +0000 | [diff] [blame] | 135 | |
Zackery Spytz | 91e9379 | 2020-11-05 15:18:44 -0700 | [diff] [blame] | 136 | def format_exception_only(exc, /, value=_sentinel): |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 137 | """Format the exception part of a traceback. |
| 138 | |
Zackery Spytz | 91e9379 | 2020-11-05 15:18:44 -0700 | [diff] [blame] | 139 | The return value is a list of strings, each ending in a newline. |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 140 | |
| 141 | Normally, the list contains a single string; however, for |
| 142 | SyntaxError exceptions, it contains several lines that (when |
| 143 | printed) display detailed information about where the syntax |
| 144 | error occurred. |
| 145 | |
| 146 | The message indicating which exception occurred is always the last |
| 147 | string in the list. |
| 148 | |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 149 | """ |
Zackery Spytz | 91e9379 | 2020-11-05 15:18:44 -0700 | [diff] [blame] | 150 | if value is _sentinel: |
| 151 | value = exc |
Irit Katriel | 4c94d74 | 2021-01-15 02:45:02 +0000 | [diff] [blame] | 152 | te = TracebackException(type(value), value, None, compact=True) |
| 153 | return list(te.format_exception_only()) |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 154 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 155 | |
Martin Panter | 46f5072 | 2016-05-26 05:35:26 +0000 | [diff] [blame] | 156 | # -- not official API but folk probably use these two functions. |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 157 | |
| 158 | def _format_final_exc_line(etype, value): |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 159 | valuestr = _some_str(value) |
Martin Panter | bb8b1cb | 2016-09-22 09:37:39 +0000 | [diff] [blame] | 160 | if value is None or not valuestr: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 161 | line = "%s\n" % etype |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 162 | else: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 163 | line = "%s: %s\n" % (etype, valuestr) |
| 164 | return line |
Guido van Rossum | 28e99fe | 1995-08-04 04:30:30 +0000 | [diff] [blame] | 165 | |
Guido van Rossum | 2823f03 | 2000-08-22 02:04:46 +0000 | [diff] [blame] | 166 | def _some_str(value): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 167 | try: |
| 168 | return str(value) |
| 169 | except: |
| 170 | return '<unprintable %s object>' % type(value).__name__ |
Guido van Rossum | 2823f03 | 2000-08-22 02:04:46 +0000 | [diff] [blame] | 171 | |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 172 | # -- |
| 173 | |
Benjamin Peterson | e652821 | 2008-07-15 15:32:09 +0000 | [diff] [blame] | 174 | def print_exc(limit=None, file=None, chain=True): |
Neal Norwitz | ac3625f | 2006-03-17 05:49:33 +0000 | [diff] [blame] | 175 | """Shorthand for 'print_exception(*sys.exc_info(), limit, file)'.""" |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 176 | print_exception(*sys.exc_info(), limit=limit, file=file, chain=chain) |
Neil Schemenauer | f607fc5 | 2003-11-05 23:03:00 +0000 | [diff] [blame] | 177 | |
Benjamin Peterson | e652821 | 2008-07-15 15:32:09 +0000 | [diff] [blame] | 178 | def format_exc(limit=None, chain=True): |
Neil Schemenauer | f607fc5 | 2003-11-05 23:03:00 +0000 | [diff] [blame] | 179 | """Like print_exc() but return a string.""" |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 180 | return "".join(format_exception(*sys.exc_info(), limit=limit, chain=chain)) |
Neil Schemenauer | f607fc5 | 2003-11-05 23:03:00 +0000 | [diff] [blame] | 181 | |
Benjamin Peterson | e652821 | 2008-07-15 15:32:09 +0000 | [diff] [blame] | 182 | def print_last(limit=None, file=None, chain=True): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 183 | """This is a shorthand for 'print_exception(sys.last_type, |
| 184 | sys.last_value, sys.last_traceback, limit, file)'.""" |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 185 | if not hasattr(sys, "last_type"): |
| 186 | raise ValueError("no last exception") |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 187 | print_exception(sys.last_type, sys.last_value, sys.last_traceback, |
Benjamin Peterson | e652821 | 2008-07-15 15:32:09 +0000 | [diff] [blame] | 188 | limit, file, chain) |
Guido van Rossum | dcc057a | 1996-08-12 23:18:13 +0000 | [diff] [blame] | 189 | |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 190 | # |
| 191 | # Printing and Extracting Stacks. |
| 192 | # |
| 193 | |
Guido van Rossum | dcc057a | 1996-08-12 23:18:13 +0000 | [diff] [blame] | 194 | def print_stack(f=None, limit=None, file=None): |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 195 | """Print a stack trace from its invocation point. |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 196 | |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 197 | The optional 'f' argument can be used to specify an alternate |
| 198 | stack frame at which to start. The optional 'limit' and 'file' |
| 199 | arguments have the same meaning as for print_exception(). |
| 200 | """ |
Serhiy Storchaka | e953ba7 | 2015-09-18 10:04:47 +0300 | [diff] [blame] | 201 | if f is None: |
| 202 | f = sys._getframe().f_back |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 203 | print_list(extract_stack(f, limit=limit), file=file) |
| 204 | |
Guido van Rossum | dcc057a | 1996-08-12 23:18:13 +0000 | [diff] [blame] | 205 | |
| 206 | def format_stack(f=None, limit=None): |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 207 | """Shorthand for 'format_list(extract_stack(f, limit))'.""" |
Serhiy Storchaka | e953ba7 | 2015-09-18 10:04:47 +0300 | [diff] [blame] | 208 | if f is None: |
| 209 | f = sys._getframe().f_back |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 210 | return format_list(extract_stack(f, limit=limit)) |
| 211 | |
Guido van Rossum | dcc057a | 1996-08-12 23:18:13 +0000 | [diff] [blame] | 212 | |
Georg Brandl | 2ad07c3 | 2009-09-16 14:24:29 +0000 | [diff] [blame] | 213 | def extract_stack(f=None, limit=None): |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 214 | """Extract the raw traceback from the current stack frame. |
| 215 | |
| 216 | The return value has the same format as for extract_tb(). The |
| 217 | optional 'f' and 'limit' arguments have the same meaning as for |
| 218 | print_stack(). Each item in the list is a quadruple (filename, |
| 219 | line number, function name, text), and the entries are in order |
| 220 | from oldest to newest stack frame. |
| 221 | """ |
Serhiy Storchaka | e953ba7 | 2015-09-18 10:04:47 +0300 | [diff] [blame] | 222 | if f is None: |
| 223 | f = sys._getframe().f_back |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 224 | stack = StackSummary.extract(walk_stack(f), limit=limit) |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 225 | stack.reverse() |
| 226 | return stack |
Andrew Kuchling | 173a157 | 2013-09-15 18:15:56 -0400 | [diff] [blame] | 227 | |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 228 | |
Andrew Kuchling | 173a157 | 2013-09-15 18:15:56 -0400 | [diff] [blame] | 229 | def clear_frames(tb): |
| 230 | "Clear all references to local variables in the frames of a traceback." |
| 231 | while tb is not None: |
| 232 | try: |
| 233 | tb.tb_frame.clear() |
| 234 | except RuntimeError: |
| 235 | # Ignore the exception raised if the frame is still executing. |
| 236 | pass |
| 237 | tb = tb.tb_next |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 238 | |
| 239 | |
| 240 | class FrameSummary: |
| 241 | """A single frame from a traceback. |
| 242 | |
| 243 | - :attr:`filename` The filename for the frame. |
| 244 | - :attr:`lineno` The line within filename for the frame that was |
| 245 | active when the frame was captured. |
| 246 | - :attr:`name` The name of the function or method that was executing |
| 247 | when the frame was captured. |
| 248 | - :attr:`line` The text from the linecache module for the |
| 249 | of code that was running when the frame was captured. |
| 250 | - :attr:`locals` Either None if locals were not supplied, or a dict |
Robert Collins | d7c7e0e | 2015-03-05 20:28:52 +1300 | [diff] [blame] | 251 | mapping the name to the repr() of the variable. |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 252 | """ |
| 253 | |
| 254 | __slots__ = ('filename', 'lineno', 'name', '_line', 'locals') |
| 255 | |
Robert Collins | d7c7e0e | 2015-03-05 20:28:52 +1300 | [diff] [blame] | 256 | def __init__(self, filename, lineno, name, *, lookup_line=True, |
| 257 | locals=None, line=None): |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 258 | """Construct a FrameSummary. |
| 259 | |
| 260 | :param lookup_line: If True, `linecache` is consulted for the source |
| 261 | code line. Otherwise, the line will be looked up when first needed. |
| 262 | :param locals: If supplied the frame locals, which will be captured as |
Robert Collins | d7c7e0e | 2015-03-05 20:28:52 +1300 | [diff] [blame] | 263 | object representations. |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 264 | :param line: If provided, use this instead of looking up the line in |
| 265 | the linecache. |
| 266 | """ |
| 267 | self.filename = filename |
| 268 | self.lineno = lineno |
| 269 | self.name = name |
| 270 | self._line = line |
| 271 | if lookup_line: |
| 272 | self.line |
Jon Dufresne | 3972628 | 2017-05-18 07:35:54 -0700 | [diff] [blame] | 273 | self.locals = {k: repr(v) for k, v in locals.items()} if locals else None |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 274 | |
| 275 | def __eq__(self, other): |
Serhiy Storchaka | 3066fc4 | 2015-09-29 22:33:36 +0300 | [diff] [blame] | 276 | if isinstance(other, FrameSummary): |
| 277 | return (self.filename == other.filename and |
| 278 | self.lineno == other.lineno and |
| 279 | self.name == other.name and |
| 280 | self.locals == other.locals) |
| 281 | if isinstance(other, tuple): |
| 282 | return (self.filename, self.lineno, self.name, self.line) == other |
| 283 | return NotImplemented |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 284 | |
| 285 | def __getitem__(self, pos): |
| 286 | return (self.filename, self.lineno, self.name, self.line)[pos] |
| 287 | |
| 288 | def __iter__(self): |
| 289 | return iter([self.filename, self.lineno, self.name, self.line]) |
| 290 | |
| 291 | def __repr__(self): |
| 292 | return "<FrameSummary file {filename}, line {lineno} in {name}>".format( |
| 293 | filename=self.filename, lineno=self.lineno, name=self.name) |
| 294 | |
Berker Peksag | 9797b7a | 2018-09-10 20:02:33 +0300 | [diff] [blame] | 295 | def __len__(self): |
| 296 | return 4 |
| 297 | |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 298 | @property |
| 299 | def line(self): |
| 300 | if self._line is None: |
| 301 | self._line = linecache.getline(self.filename, self.lineno).strip() |
| 302 | return self._line |
| 303 | |
| 304 | |
| 305 | def walk_stack(f): |
| 306 | """Walk a stack yielding the frame and line number for each frame. |
| 307 | |
| 308 | This will follow f.f_back from the given frame. If no frame is given, the |
| 309 | current stack is used. Usually used with StackSummary.extract. |
| 310 | """ |
| 311 | if f is None: |
| 312 | f = sys._getframe().f_back.f_back |
| 313 | while f is not None: |
| 314 | yield f, f.f_lineno |
| 315 | f = f.f_back |
| 316 | |
| 317 | |
| 318 | def walk_tb(tb): |
| 319 | """Walk a traceback yielding the frame and line number for each frame. |
| 320 | |
| 321 | This will follow tb.tb_next (and thus is in the opposite order to |
| 322 | walk_stack). Usually used with StackSummary.extract. |
| 323 | """ |
| 324 | while tb is not None: |
| 325 | yield tb.tb_frame, tb.tb_lineno |
| 326 | tb = tb.tb_next |
| 327 | |
| 328 | |
Benjamin Peterson | d545869 | 2018-09-10 08:43:10 -0700 | [diff] [blame] | 329 | _RECURSIVE_CUTOFF = 3 # Also hardcoded in traceback.c. |
| 330 | |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 331 | class StackSummary(list): |
| 332 | """A stack of frames.""" |
| 333 | |
| 334 | @classmethod |
Robert Collins | d7c7e0e | 2015-03-05 20:28:52 +1300 | [diff] [blame] | 335 | def extract(klass, frame_gen, *, limit=None, lookup_lines=True, |
| 336 | capture_locals=False): |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 337 | """Create a StackSummary from a traceback or stack object. |
| 338 | |
| 339 | :param frame_gen: A generator that yields (frame, lineno) tuples to |
| 340 | include in the stack. |
| 341 | :param limit: None to include all frames or the number of frames to |
| 342 | include. |
| 343 | :param lookup_lines: If True, lookup lines for each frame immediately, |
| 344 | otherwise lookup is deferred until the frame is rendered. |
Robert Collins | d7c7e0e | 2015-03-05 20:28:52 +1300 | [diff] [blame] | 345 | :param capture_locals: If True, the local variables from each frame will |
| 346 | be captured as object representations into the FrameSummary. |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 347 | """ |
| 348 | if limit is None: |
| 349 | limit = getattr(sys, 'tracebacklimit', None) |
Serhiy Storchaka | 24559e4 | 2015-05-03 13:19:46 +0300 | [diff] [blame] | 350 | if limit is not None and limit < 0: |
| 351 | limit = 0 |
| 352 | if limit is not None: |
| 353 | if limit >= 0: |
| 354 | frame_gen = itertools.islice(frame_gen, limit) |
| 355 | else: |
| 356 | frame_gen = collections.deque(frame_gen, maxlen=-limit) |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 357 | |
| 358 | result = klass() |
| 359 | fnames = set() |
Serhiy Storchaka | 24559e4 | 2015-05-03 13:19:46 +0300 | [diff] [blame] | 360 | for f, lineno in frame_gen: |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 361 | co = f.f_code |
| 362 | filename = co.co_filename |
| 363 | name = co.co_name |
| 364 | |
| 365 | fnames.add(filename) |
| 366 | linecache.lazycache(filename, f.f_globals) |
| 367 | # Must defer line lookups until we have called checkcache. |
Robert Collins | d7c7e0e | 2015-03-05 20:28:52 +1300 | [diff] [blame] | 368 | if capture_locals: |
| 369 | f_locals = f.f_locals |
| 370 | else: |
| 371 | f_locals = None |
| 372 | result.append(FrameSummary( |
| 373 | filename, lineno, name, lookup_line=False, locals=f_locals)) |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 374 | for filename in fnames: |
| 375 | linecache.checkcache(filename) |
| 376 | # If immediate lookup was desired, trigger lookups now. |
| 377 | if lookup_lines: |
| 378 | for f in result: |
| 379 | f.line |
| 380 | return result |
| 381 | |
| 382 | @classmethod |
| 383 | def from_list(klass, a_list): |
torsava | f394ee5 | 2018-08-02 17:08:59 +0100 | [diff] [blame] | 384 | """ |
| 385 | Create a StackSummary object from a supplied list of |
| 386 | FrameSummary objects or old-style list of tuples. |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 387 | """ |
Robert Collins | bbb8ade | 2015-03-16 15:27:16 +1300 | [diff] [blame] | 388 | # While doing a fast-path check for isinstance(a_list, StackSummary) is |
| 389 | # appealing, idlelib.run.cleanup_traceback and other similar code may |
| 390 | # break this by making arbitrary frames plain tuples, so we need to |
| 391 | # check on a frame by frame basis. |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 392 | result = StackSummary() |
Robert Collins | bbb8ade | 2015-03-16 15:27:16 +1300 | [diff] [blame] | 393 | for frame in a_list: |
| 394 | if isinstance(frame, FrameSummary): |
| 395 | result.append(frame) |
| 396 | else: |
| 397 | filename, lineno, name, line = frame |
| 398 | result.append(FrameSummary(filename, lineno, name, line=line)) |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 399 | return result |
| 400 | |
| 401 | def format(self): |
| 402 | """Format the stack ready for printing. |
| 403 | |
| 404 | Returns a list of strings ready for printing. Each string in the |
| 405 | resulting list corresponds to a single frame from the stack. |
| 406 | Each string ends in a newline; the strings may contain internal |
| 407 | newlines as well, for those items with source text lines. |
Nick Coghlan | d003423 | 2016-08-15 13:11:34 +1000 | [diff] [blame] | 408 | |
| 409 | For long sequences of the same frame and line, the first few |
| 410 | repetitions are shown, followed by a summary line stating the exact |
| 411 | number of further repetitions. |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 412 | """ |
| 413 | result = [] |
Nick Coghlan | d003423 | 2016-08-15 13:11:34 +1000 | [diff] [blame] | 414 | last_file = None |
| 415 | last_line = None |
| 416 | last_name = None |
| 417 | count = 0 |
Robert Collins | d7c7e0e | 2015-03-05 20:28:52 +1300 | [diff] [blame] | 418 | for frame in self: |
Benjamin Peterson | d545869 | 2018-09-10 08:43:10 -0700 | [diff] [blame] | 419 | if (last_file is None or last_file != frame.filename or |
| 420 | last_line is None or last_line != frame.lineno or |
| 421 | last_name is None or last_name != frame.name): |
| 422 | if count > _RECURSIVE_CUTOFF: |
| 423 | count -= _RECURSIVE_CUTOFF |
| 424 | result.append( |
| 425 | f' [Previous line repeated {count} more ' |
| 426 | f'time{"s" if count > 1 else ""}]\n' |
| 427 | ) |
Nick Coghlan | d003423 | 2016-08-15 13:11:34 +1000 | [diff] [blame] | 428 | last_file = frame.filename |
| 429 | last_line = frame.lineno |
| 430 | last_name = frame.name |
| 431 | count = 0 |
Benjamin Peterson | d545869 | 2018-09-10 08:43:10 -0700 | [diff] [blame] | 432 | count += 1 |
| 433 | if count > _RECURSIVE_CUTOFF: |
Nick Coghlan | d003423 | 2016-08-15 13:11:34 +1000 | [diff] [blame] | 434 | continue |
Robert Collins | d7c7e0e | 2015-03-05 20:28:52 +1300 | [diff] [blame] | 435 | row = [] |
| 436 | row.append(' File "{}", line {}, in {}\n'.format( |
| 437 | frame.filename, frame.lineno, frame.name)) |
| 438 | if frame.line: |
| 439 | row.append(' {}\n'.format(frame.line.strip())) |
| 440 | if frame.locals: |
| 441 | for name, value in sorted(frame.locals.items()): |
| 442 | row.append(' {name} = {value}\n'.format(name=name, value=value)) |
| 443 | result.append(''.join(row)) |
Benjamin Peterson | d545869 | 2018-09-10 08:43:10 -0700 | [diff] [blame] | 444 | if count > _RECURSIVE_CUTOFF: |
| 445 | count -= _RECURSIVE_CUTOFF |
| 446 | result.append( |
| 447 | f' [Previous line repeated {count} more ' |
| 448 | f'time{"s" if count > 1 else ""}]\n' |
| 449 | ) |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 450 | return result |
| 451 | |
| 452 | |
| 453 | class TracebackException: |
| 454 | """An exception ready for rendering. |
| 455 | |
| 456 | The traceback module captures enough attributes from the original exception |
| 457 | to this intermediary form to ensure that no references are held, while |
| 458 | still being able to fully print or format it. |
| 459 | |
| 460 | Use `from_exception` to create TracebackException instances from exception |
| 461 | objects, or the constructor to create TracebackException instances from |
| 462 | individual components. |
| 463 | |
| 464 | - :attr:`__cause__` A TracebackException of the original *__cause__*. |
| 465 | - :attr:`__context__` A TracebackException of the original *__context__*. |
| 466 | - :attr:`__suppress_context__` The *__suppress_context__* value from the |
| 467 | original exception. |
| 468 | - :attr:`stack` A `StackSummary` representing the traceback. |
| 469 | - :attr:`exc_type` The class of the original traceback. |
| 470 | - :attr:`filename` For syntax errors - the filename where the error |
Martin Panter | 46f5072 | 2016-05-26 05:35:26 +0000 | [diff] [blame] | 471 | occurred. |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 472 | - :attr:`lineno` For syntax errors - the linenumber where the error |
Martin Panter | 46f5072 | 2016-05-26 05:35:26 +0000 | [diff] [blame] | 473 | occurred. |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 474 | - :attr:`text` For syntax errors - the text where the error |
Martin Panter | 46f5072 | 2016-05-26 05:35:26 +0000 | [diff] [blame] | 475 | occurred. |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 476 | - :attr:`offset` For syntax errors - the offset into the text where the |
Martin Panter | 46f5072 | 2016-05-26 05:35:26 +0000 | [diff] [blame] | 477 | error occurred. |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 478 | - :attr:`msg` For syntax errors - the compiler error message. |
| 479 | """ |
| 480 | |
Robert Collins | d7c7e0e | 2015-03-05 20:28:52 +1300 | [diff] [blame] | 481 | def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None, |
Irit Katriel | 4c94d74 | 2021-01-15 02:45:02 +0000 | [diff] [blame] | 482 | lookup_lines=True, capture_locals=False, compact=False, |
| 483 | _seen=None): |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 484 | # NB: we need to accept exc_traceback, exc_value, exc_traceback to |
| 485 | # permit backwards compat with the existing API, otherwise we |
| 486 | # need stub thunk objects just to glue it together. |
| 487 | # Handle loops in __cause__ or __context__. |
Irit Katriel | 6dfd173 | 2021-01-12 22:14:27 +0000 | [diff] [blame] | 488 | is_recursive_call = _seen is not None |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 489 | if _seen is None: |
| 490 | _seen = set() |
Zane Bitter | de86073 | 2017-10-17 17:29:39 -0400 | [diff] [blame] | 491 | _seen.add(id(exc_value)) |
Irit Katriel | 4c94d74 | 2021-01-15 02:45:02 +0000 | [diff] [blame] | 492 | |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 493 | # TODO: locals. |
| 494 | self.stack = StackSummary.extract( |
Robert Collins | d7c7e0e | 2015-03-05 20:28:52 +1300 | [diff] [blame] | 495 | walk_tb(exc_traceback), limit=limit, lookup_lines=lookup_lines, |
| 496 | capture_locals=capture_locals) |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 497 | 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 |
Irit Katriel | 069560b | 2020-12-22 19:53:09 +0000 | [diff] [blame] | 504 | lno = exc_value.lineno |
| 505 | self.lineno = str(lno) if lno is not None else None |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 506 | self.text = exc_value.text |
| 507 | self.offset = exc_value.offset |
| 508 | self.msg = exc_value.msg |
| 509 | if lookup_lines: |
| 510 | self._load_lines() |
Irit Katriel | 6dfd173 | 2021-01-12 22:14:27 +0000 | [diff] [blame] | 511 | self.__suppress_context__ = \ |
Irit Katriel | 4c94d74 | 2021-01-15 02:45:02 +0000 | [diff] [blame] | 512 | exc_value.__suppress_context__ if exc_value is not None else False |
Irit Katriel | 6dfd173 | 2021-01-12 22:14:27 +0000 | [diff] [blame] | 513 | |
| 514 | # Convert __cause__ and __context__ to `TracebackExceptions`s, use a |
| 515 | # queue to avoid recursion (only the top-level call gets _seen == None) |
| 516 | if not is_recursive_call: |
| 517 | queue = [(self, exc_value)] |
| 518 | while queue: |
| 519 | te, e = queue.pop() |
| 520 | if (e and e.__cause__ is not None |
| 521 | and id(e.__cause__) not in _seen): |
| 522 | cause = TracebackException( |
| 523 | type(e.__cause__), |
| 524 | e.__cause__, |
| 525 | e.__cause__.__traceback__, |
| 526 | limit=limit, |
| 527 | lookup_lines=lookup_lines, |
| 528 | capture_locals=capture_locals, |
| 529 | _seen=_seen) |
| 530 | else: |
| 531 | cause = None |
Irit Katriel | 4c94d74 | 2021-01-15 02:45:02 +0000 | [diff] [blame] | 532 | |
| 533 | if compact: |
Irit Katriel | 26f18b8 | 2021-02-23 14:58:47 +0000 | [diff] [blame] | 534 | need_context = (cause is None and |
| 535 | e is not None and |
| 536 | not e.__suppress_context__) |
Irit Katriel | 4c94d74 | 2021-01-15 02:45:02 +0000 | [diff] [blame] | 537 | else: |
| 538 | need_context = True |
Irit Katriel | 6dfd173 | 2021-01-12 22:14:27 +0000 | [diff] [blame] | 539 | if (e and e.__context__ is not None |
Irit Katriel | 4c94d74 | 2021-01-15 02:45:02 +0000 | [diff] [blame] | 540 | and need_context and id(e.__context__) not in _seen): |
Irit Katriel | 6dfd173 | 2021-01-12 22:14:27 +0000 | [diff] [blame] | 541 | context = TracebackException( |
| 542 | type(e.__context__), |
| 543 | e.__context__, |
| 544 | e.__context__.__traceback__, |
| 545 | limit=limit, |
| 546 | lookup_lines=lookup_lines, |
| 547 | capture_locals=capture_locals, |
| 548 | _seen=_seen) |
| 549 | else: |
| 550 | context = None |
| 551 | te.__cause__ = cause |
| 552 | te.__context__ = context |
| 553 | if cause: |
| 554 | queue.append((te.__cause__, e.__cause__)) |
| 555 | if context: |
| 556 | queue.append((te.__context__, e.__context__)) |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 557 | |
| 558 | @classmethod |
Robert Collins | aece824 | 2015-07-26 06:50:51 +1200 | [diff] [blame] | 559 | def from_exception(cls, exc, *args, **kwargs): |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 560 | """Create a TracebackException from an exception.""" |
Robert Collins | aece824 | 2015-07-26 06:50:51 +1200 | [diff] [blame] | 561 | return cls(type(exc), exc, exc.__traceback__, *args, **kwargs) |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 562 | |
| 563 | def _load_lines(self): |
| 564 | """Private API. force all lines in the stack to be loaded.""" |
| 565 | for frame in self.stack: |
| 566 | frame.line |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 567 | |
| 568 | def __eq__(self, other): |
Serhiy Storchaka | 662db12 | 2019-08-08 08:42:54 +0300 | [diff] [blame] | 569 | if isinstance(other, TracebackException): |
| 570 | return self.__dict__ == other.__dict__ |
| 571 | return NotImplemented |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 572 | |
| 573 | def __str__(self): |
| 574 | return self._str |
| 575 | |
| 576 | def format_exception_only(self): |
| 577 | """Format the exception part of the traceback. |
| 578 | |
| 579 | The return value is a generator of strings, each ending in a newline. |
| 580 | |
| 581 | Normally, the generator emits a single string; however, for |
Galden | df8913f | 2020-04-20 10:17:37 +0800 | [diff] [blame] | 582 | SyntaxError exceptions, it emits several lines that (when |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 583 | printed) display detailed information about where the syntax |
| 584 | error occurred. |
| 585 | |
| 586 | The message indicating which exception occurred is always the last |
| 587 | string in the output. |
| 588 | """ |
| 589 | if self.exc_type is None: |
| 590 | yield _format_final_exc_line(None, self._str) |
| 591 | return |
| 592 | |
| 593 | stype = self.exc_type.__qualname__ |
| 594 | smod = self.exc_type.__module__ |
| 595 | if smod not in ("__main__", "builtins"): |
| 596 | stype = smod + '.' + stype |
| 597 | |
| 598 | if not issubclass(self.exc_type, SyntaxError): |
| 599 | yield _format_final_exc_line(stype, self._str) |
Guido van Rossum | 15bc9ab | 2020-05-14 19:22:48 -0700 | [diff] [blame] | 600 | else: |
| 601 | yield from self._format_syntax_error(stype) |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 602 | |
Guido van Rossum | 15bc9ab | 2020-05-14 19:22:48 -0700 | [diff] [blame] | 603 | def _format_syntax_error(self, stype): |
| 604 | """Format SyntaxError exceptions (internal helper).""" |
| 605 | # Show exactly where the problem was found. |
Irit Katriel | 069560b | 2020-12-22 19:53:09 +0000 | [diff] [blame] | 606 | filename_suffix = '' |
| 607 | if self.lineno is not None: |
| 608 | yield ' File "{}", line {}\n'.format( |
| 609 | self.filename or "<string>", self.lineno) |
| 610 | elif self.filename is not None: |
| 611 | filename_suffix = ' ({})'.format(self.filename) |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 612 | |
Guido van Rossum | 15bc9ab | 2020-05-14 19:22:48 -0700 | [diff] [blame] | 613 | text = self.text |
| 614 | if text is not None: |
| 615 | # text = " foo\n" |
| 616 | # rtext = " foo" |
| 617 | # ltext = "foo" |
| 618 | rtext = text.rstrip('\n') |
| 619 | ltext = rtext.lstrip(' \n\f') |
| 620 | spaces = len(rtext) - len(ltext) |
| 621 | yield ' {}\n'.format(ltext) |
| 622 | # Convert 1-based column offset to 0-based index into stripped text |
| 623 | caret = (self.offset or 0) - 1 - spaces |
| 624 | if caret >= 0: |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 625 | # non-space whitespace (likes tabs) must be kept for alignment |
Guido van Rossum | 15bc9ab | 2020-05-14 19:22:48 -0700 | [diff] [blame] | 626 | caretspace = ((c if c.isspace() else ' ') for c in ltext[:caret]) |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 627 | yield ' {}^\n'.format(''.join(caretspace)) |
| 628 | msg = self.msg or "<no detail available>" |
Irit Katriel | 069560b | 2020-12-22 19:53:09 +0000 | [diff] [blame] | 629 | yield "{}: {}{}\n".format(stype, msg, filename_suffix) |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 630 | |
Robert Collins | d7c7e0e | 2015-03-05 20:28:52 +1300 | [diff] [blame] | 631 | def format(self, *, chain=True): |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame] | 632 | """Format the exception. |
| 633 | |
| 634 | If chain is not *True*, *__cause__* and *__context__* will not be formatted. |
| 635 | |
| 636 | The return value is a generator of strings, each ending in a newline and |
| 637 | some containing internal newlines. `print_exception` is a wrapper around |
| 638 | this method which just prints the lines to a file. |
| 639 | |
| 640 | The message indicating which exception occurred is always the last |
| 641 | string in the output. |
| 642 | """ |
Irit Katriel | 6dfd173 | 2021-01-12 22:14:27 +0000 | [diff] [blame] | 643 | |
| 644 | output = [] |
| 645 | exc = self |
| 646 | while exc: |
| 647 | if chain: |
| 648 | if exc.__cause__ is not None: |
| 649 | chained_msg = _cause_message |
| 650 | chained_exc = exc.__cause__ |
| 651 | elif (exc.__context__ is not None and |
| 652 | not exc.__suppress_context__): |
| 653 | chained_msg = _context_message |
| 654 | chained_exc = exc.__context__ |
| 655 | else: |
| 656 | chained_msg = None |
| 657 | chained_exc = None |
| 658 | |
| 659 | output.append((chained_msg, exc)) |
| 660 | exc = chained_exc |
| 661 | else: |
| 662 | output.append((None, exc)) |
| 663 | exc = None |
| 664 | |
| 665 | for msg, exc in reversed(output): |
| 666 | if msg is not None: |
| 667 | yield msg |
| 668 | if exc.stack: |
| 669 | yield 'Traceback (most recent call last):\n' |
| 670 | yield from exc.stack.format() |
| 671 | yield from exc.format_exception_only() |