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