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 | |
| 3 | import linecache |
Guido van Rossum | 526beed | 1994-07-01 15:36:46 +0000 | [diff] [blame] | 4 | import sys |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 5 | import operator |
Guido van Rossum | 526beed | 1994-07-01 15:36:46 +0000 | [diff] [blame] | 6 | |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 7 | __all__ = ['extract_stack', 'extract_tb', 'format_exception', |
| 8 | 'format_exception_only', 'format_list', 'format_stack', |
Neil Schemenauer | f607fc5 | 2003-11-05 23:03:00 +0000 | [diff] [blame] | 9 | 'format_tb', 'print_exc', 'format_exc', 'print_exception', |
Andrew Kuchling | 173a157 | 2013-09-15 18:15:56 -0400 | [diff] [blame] | 10 | 'print_last', 'print_stack', 'print_tb', |
| 11 | 'clear_frames'] |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 12 | |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 13 | # |
| 14 | # Formatting and printing lists of traceback lines. |
| 15 | # |
Guido van Rossum | dcc057a | 1996-08-12 23:18:13 +0000 | [diff] [blame] | 16 | |
Guido van Rossum | dcc057a | 1996-08-12 23:18:13 +0000 | [diff] [blame] | 17 | def print_list(extracted_list, file=None): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 18 | """Print the list of tuples as returned by extract_tb() or |
| 19 | extract_stack() as a formatted stack trace to the given file.""" |
Raymond Hettinger | 10ff706 | 2002-06-02 03:04:52 +0000 | [diff] [blame] | 20 | if file is None: |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 21 | file = sys.stderr |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame^] | 22 | for item in StackSummary.from_list(extracted_list).format(): |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 23 | print(item, file=file, end="") |
Guido van Rossum | dcc057a | 1996-08-12 23:18:13 +0000 | [diff] [blame] | 24 | |
| 25 | def format_list(extracted_list): |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 26 | """Format a list of traceback entry tuples for printing. |
| 27 | |
| 28 | Given a list of tuples as returned by extract_tb() or |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 29 | extract_stack(), return a list of strings ready for printing. |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 30 | 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 Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame^] | 35 | return StackSummary.from_list(extracted_list).format() |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 36 | |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 37 | # |
| 38 | # Printing and Extracting Tracebacks. |
| 39 | # |
| 40 | |
Guido van Rossum | 194e20a | 1995-09-20 20:31:51 +0000 | [diff] [blame] | 41 | def print_tb(tb, limit=None, file=None): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 42 | """Print up to 'limit' stack trace entries from the traceback 'tb'. |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 43 | |
| 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 Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 49 | print_list(extract_tb(tb, limit=limit), file=file) |
Guido van Rossum | 526beed | 1994-07-01 15:36:46 +0000 | [diff] [blame] | 50 | |
Georg Brandl | 2ad07c3 | 2009-09-16 14:24:29 +0000 | [diff] [blame] | 51 | def format_tb(tb, limit=None): |
Georg Brandl | 9e091e1 | 2013-10-13 23:32:14 +0200 | [diff] [blame] | 52 | """A shorthand for 'format_list(extract_tb(tb, limit))'.""" |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame^] | 53 | return extract_tb(tb, limit=limit).format() |
Guido van Rossum | 28e99fe | 1995-08-04 04:30:30 +0000 | [diff] [blame] | 54 | |
Georg Brandl | 2ad07c3 | 2009-09-16 14:24:29 +0000 | [diff] [blame] | 55 | def extract_tb(tb, limit=None): |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 56 | """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 Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame^] | 66 | return StackSummary.extract(walk_tb(tb), limit=limit) |
Guido van Rossum | 526beed | 1994-07-01 15:36:46 +0000 | [diff] [blame] | 67 | |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 68 | # |
| 69 | # Exception formatting and output. |
| 70 | # |
Guido van Rossum | 28e99fe | 1995-08-04 04:30:30 +0000 | [diff] [blame] | 71 | |
Benjamin Peterson | e652821 | 2008-07-15 15:32:09 +0000 | [diff] [blame] | 72 | _cause_message = ( |
| 73 | "\nThe above exception was the direct cause " |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame^] | 74 | "of the following exception:\n\n") |
Benjamin Peterson | e652821 | 2008-07-15 15:32:09 +0000 | [diff] [blame] | 75 | |
| 76 | _context_message = ( |
| 77 | "\nDuring handling of the above exception, " |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame^] | 78 | "another exception occurred:\n\n") |
Benjamin Peterson | e652821 | 2008-07-15 15:32:09 +0000 | [diff] [blame] | 79 | |
Benjamin Peterson | e652821 | 2008-07-15 15:32:09 +0000 | [diff] [blame] | 80 | |
| 81 | def print_exception(etype, value, tb, limit=None, file=None, chain=True): |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 82 | """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 Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 89 | occurred with a caret on the next line indicating the approximate |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 90 | position of the error. |
| 91 | """ |
Raymond Hettinger | 10ff706 | 2002-06-02 03:04:52 +0000 | [diff] [blame] | 92 | if file is None: |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 93 | file = sys.stderr |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame^] | 94 | for line in TracebackException( |
| 95 | etype, value, tb, limit=limit).format(chain=chain): |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 96 | print(line, file=file, end="") |
Guido van Rossum | 28e99fe | 1995-08-04 04:30:30 +0000 | [diff] [blame] | 97 | |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame^] | 98 | |
Benjamin Peterson | e652821 | 2008-07-15 15:32:09 +0000 | [diff] [blame] | 99 | def format_exception(etype, value, tb, limit=None, chain=True): |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 100 | """Format a stack trace and the exception information. |
| 101 | |
| 102 | The arguments have the same meaning as the corresponding arguments |
| 103 | to print_exception(). The return value is a list of strings, each |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 104 | ending in a newline and some containing internal newlines. When |
| 105 | these lines are concatenated and printed, exactly the same text is |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 106 | printed as does print_exception(). |
| 107 | """ |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame^] | 108 | return list(TracebackException( |
| 109 | etype, value, tb, limit=limit).format(chain=chain)) |
| 110 | |
Guido van Rossum | 28e99fe | 1995-08-04 04:30:30 +0000 | [diff] [blame] | 111 | |
| 112 | def format_exception_only(etype, value): |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 113 | """Format the exception part of a traceback. |
| 114 | |
| 115 | The arguments are the exception type and value such as given by |
| 116 | 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] | 117 | strings, each ending in a newline. |
| 118 | |
| 119 | Normally, the list contains a single string; however, for |
| 120 | SyntaxError exceptions, it contains several lines that (when |
| 121 | printed) display detailed information about where the syntax |
| 122 | error occurred. |
| 123 | |
| 124 | The message indicating which exception occurred is always the last |
| 125 | string in the list. |
| 126 | |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 127 | """ |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame^] | 128 | return list(TracebackException(etype, value, None).format_exception_only()) |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 129 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 130 | |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame^] | 131 | # -- not offical API but folk probably use these two functions. |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 132 | |
| 133 | def _format_final_exc_line(etype, value): |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 134 | valuestr = _some_str(value) |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame^] | 135 | if value == 'None' or value is None or not valuestr: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 136 | line = "%s\n" % etype |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 137 | else: |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 138 | line = "%s: %s\n" % (etype, valuestr) |
| 139 | return line |
Guido van Rossum | 28e99fe | 1995-08-04 04:30:30 +0000 | [diff] [blame] | 140 | |
Guido van Rossum | 2823f03 | 2000-08-22 02:04:46 +0000 | [diff] [blame] | 141 | def _some_str(value): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 142 | try: |
| 143 | return str(value) |
| 144 | except: |
| 145 | return '<unprintable %s object>' % type(value).__name__ |
Guido van Rossum | 2823f03 | 2000-08-22 02:04:46 +0000 | [diff] [blame] | 146 | |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame^] | 147 | # -- |
| 148 | |
Benjamin Peterson | e652821 | 2008-07-15 15:32:09 +0000 | [diff] [blame] | 149 | def print_exc(limit=None, file=None, chain=True): |
Neal Norwitz | ac3625f | 2006-03-17 05:49:33 +0000 | [diff] [blame] | 150 | """Shorthand for 'print_exception(*sys.exc_info(), limit, file)'.""" |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 151 | print_exception(*sys.exc_info(), limit=limit, file=file, chain=chain) |
Neil Schemenauer | f607fc5 | 2003-11-05 23:03:00 +0000 | [diff] [blame] | 152 | |
Benjamin Peterson | e652821 | 2008-07-15 15:32:09 +0000 | [diff] [blame] | 153 | def format_exc(limit=None, chain=True): |
Neil Schemenauer | f607fc5 | 2003-11-05 23:03:00 +0000 | [diff] [blame] | 154 | """Like print_exc() but return a string.""" |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 155 | return "".join(format_exception(*sys.exc_info(), limit=limit, chain=chain)) |
Neil Schemenauer | f607fc5 | 2003-11-05 23:03:00 +0000 | [diff] [blame] | 156 | |
Benjamin Peterson | e652821 | 2008-07-15 15:32:09 +0000 | [diff] [blame] | 157 | def print_last(limit=None, file=None, chain=True): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 158 | """This is a shorthand for 'print_exception(sys.last_type, |
| 159 | sys.last_value, sys.last_traceback, limit, file)'.""" |
Benjamin Peterson | e549ead | 2009-03-28 21:42:05 +0000 | [diff] [blame] | 160 | if not hasattr(sys, "last_type"): |
| 161 | raise ValueError("no last exception") |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 162 | print_exception(sys.last_type, sys.last_value, sys.last_traceback, |
Benjamin Peterson | e652821 | 2008-07-15 15:32:09 +0000 | [diff] [blame] | 163 | limit, file, chain) |
Guido van Rossum | dcc057a | 1996-08-12 23:18:13 +0000 | [diff] [blame] | 164 | |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 165 | # |
| 166 | # Printing and Extracting Stacks. |
| 167 | # |
| 168 | |
Guido van Rossum | dcc057a | 1996-08-12 23:18:13 +0000 | [diff] [blame] | 169 | def print_stack(f=None, limit=None, file=None): |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 170 | """Print a stack trace from its invocation point. |
Tim Peters | a19a168 | 2001-03-29 04:36:09 +0000 | [diff] [blame] | 171 | |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 172 | The optional 'f' argument can be used to specify an alternate |
| 173 | stack frame at which to start. The optional 'limit' and 'file' |
| 174 | arguments have the same meaning as for print_exception(). |
| 175 | """ |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame^] | 176 | print_list(extract_stack(f, limit=limit), file=file) |
| 177 | |
Guido van Rossum | dcc057a | 1996-08-12 23:18:13 +0000 | [diff] [blame] | 178 | |
| 179 | def format_stack(f=None, limit=None): |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 180 | """Shorthand for 'format_list(extract_stack(f, limit))'.""" |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame^] | 181 | return format_list(extract_stack(f, limit=limit)) |
| 182 | |
Guido van Rossum | dcc057a | 1996-08-12 23:18:13 +0000 | [diff] [blame] | 183 | |
Georg Brandl | 2ad07c3 | 2009-09-16 14:24:29 +0000 | [diff] [blame] | 184 | def extract_stack(f=None, limit=None): |
Jeremy Hylton | 69e9e8b | 2001-03-21 19:09:31 +0000 | [diff] [blame] | 185 | """Extract the raw traceback from the current stack frame. |
| 186 | |
| 187 | The return value has the same format as for extract_tb(). The |
| 188 | optional 'f' and 'limit' arguments have the same meaning as for |
| 189 | print_stack(). Each item in the list is a quadruple (filename, |
| 190 | line number, function name, text), and the entries are in order |
| 191 | from oldest to newest stack frame. |
| 192 | """ |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame^] | 193 | stack = StackSummary.extract(walk_stack(f), limit=limit) |
Benjamin Peterson | d9fec15 | 2013-04-29 16:09:39 -0400 | [diff] [blame] | 194 | stack.reverse() |
| 195 | return stack |
Andrew Kuchling | 173a157 | 2013-09-15 18:15:56 -0400 | [diff] [blame] | 196 | |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame^] | 197 | |
Andrew Kuchling | 173a157 | 2013-09-15 18:15:56 -0400 | [diff] [blame] | 198 | def clear_frames(tb): |
| 199 | "Clear all references to local variables in the frames of a traceback." |
| 200 | while tb is not None: |
| 201 | try: |
| 202 | tb.tb_frame.clear() |
| 203 | except RuntimeError: |
| 204 | # Ignore the exception raised if the frame is still executing. |
| 205 | pass |
| 206 | tb = tb.tb_next |
Robert Collins | 6bc2c1e | 2015-03-05 12:07:57 +1300 | [diff] [blame^] | 207 | |
| 208 | |
| 209 | class FrameSummary: |
| 210 | """A single frame from a traceback. |
| 211 | |
| 212 | - :attr:`filename` The filename for the frame. |
| 213 | - :attr:`lineno` The line within filename for the frame that was |
| 214 | active when the frame was captured. |
| 215 | - :attr:`name` The name of the function or method that was executing |
| 216 | when the frame was captured. |
| 217 | - :attr:`line` The text from the linecache module for the |
| 218 | of code that was running when the frame was captured. |
| 219 | - :attr:`locals` Either None if locals were not supplied, or a dict |
| 220 | mapping the name to the str() of the variable. |
| 221 | """ |
| 222 | |
| 223 | __slots__ = ('filename', 'lineno', 'name', '_line', 'locals') |
| 224 | |
| 225 | def __init__(self, filename, lineno, name, lookup_line=True, locals=None, |
| 226 | line=None): |
| 227 | """Construct a FrameSummary. |
| 228 | |
| 229 | :param lookup_line: If True, `linecache` is consulted for the source |
| 230 | code line. Otherwise, the line will be looked up when first needed. |
| 231 | :param locals: If supplied the frame locals, which will be captured as |
| 232 | strings. |
| 233 | :param line: If provided, use this instead of looking up the line in |
| 234 | the linecache. |
| 235 | """ |
| 236 | self.filename = filename |
| 237 | self.lineno = lineno |
| 238 | self.name = name |
| 239 | self._line = line |
| 240 | if lookup_line: |
| 241 | self.line |
| 242 | self.locals = \ |
| 243 | dict((k, str(v)) for k, v in locals.items()) if locals else None |
| 244 | |
| 245 | def __eq__(self, other): |
| 246 | return (self.filename == other.filename and |
| 247 | self.lineno == other.lineno and |
| 248 | self.name == other.name and |
| 249 | self.locals == other.locals) |
| 250 | |
| 251 | def __getitem__(self, pos): |
| 252 | return (self.filename, self.lineno, self.name, self.line)[pos] |
| 253 | |
| 254 | def __iter__(self): |
| 255 | return iter([self.filename, self.lineno, self.name, self.line]) |
| 256 | |
| 257 | def __repr__(self): |
| 258 | return "<FrameSummary file {filename}, line {lineno} in {name}>".format( |
| 259 | filename=self.filename, lineno=self.lineno, name=self.name) |
| 260 | |
| 261 | @property |
| 262 | def line(self): |
| 263 | if self._line is None: |
| 264 | self._line = linecache.getline(self.filename, self.lineno).strip() |
| 265 | return self._line |
| 266 | |
| 267 | |
| 268 | def walk_stack(f): |
| 269 | """Walk a stack yielding the frame and line number for each frame. |
| 270 | |
| 271 | This will follow f.f_back from the given frame. If no frame is given, the |
| 272 | current stack is used. Usually used with StackSummary.extract. |
| 273 | """ |
| 274 | if f is None: |
| 275 | f = sys._getframe().f_back.f_back |
| 276 | while f is not None: |
| 277 | yield f, f.f_lineno |
| 278 | f = f.f_back |
| 279 | |
| 280 | |
| 281 | def walk_tb(tb): |
| 282 | """Walk a traceback yielding the frame and line number for each frame. |
| 283 | |
| 284 | This will follow tb.tb_next (and thus is in the opposite order to |
| 285 | walk_stack). Usually used with StackSummary.extract. |
| 286 | """ |
| 287 | while tb is not None: |
| 288 | yield tb.tb_frame, tb.tb_lineno |
| 289 | tb = tb.tb_next |
| 290 | |
| 291 | |
| 292 | class StackSummary(list): |
| 293 | """A stack of frames.""" |
| 294 | |
| 295 | @classmethod |
| 296 | def extract(klass, frame_gen, limit=None, lookup_lines=True): |
| 297 | """Create a StackSummary from a traceback or stack object. |
| 298 | |
| 299 | :param frame_gen: A generator that yields (frame, lineno) tuples to |
| 300 | include in the stack. |
| 301 | :param limit: None to include all frames or the number of frames to |
| 302 | include. |
| 303 | :param lookup_lines: If True, lookup lines for each frame immediately, |
| 304 | otherwise lookup is deferred until the frame is rendered. |
| 305 | """ |
| 306 | if limit is None: |
| 307 | limit = getattr(sys, 'tracebacklimit', None) |
| 308 | |
| 309 | result = klass() |
| 310 | fnames = set() |
| 311 | for pos, (f, lineno) in enumerate(frame_gen): |
| 312 | if limit is not None and pos >= limit: |
| 313 | break |
| 314 | co = f.f_code |
| 315 | filename = co.co_filename |
| 316 | name = co.co_name |
| 317 | |
| 318 | fnames.add(filename) |
| 319 | linecache.lazycache(filename, f.f_globals) |
| 320 | # Must defer line lookups until we have called checkcache. |
| 321 | result.append(FrameSummary(filename, lineno, name, lookup_line=False)) |
| 322 | for filename in fnames: |
| 323 | linecache.checkcache(filename) |
| 324 | # If immediate lookup was desired, trigger lookups now. |
| 325 | if lookup_lines: |
| 326 | for f in result: |
| 327 | f.line |
| 328 | return result |
| 329 | |
| 330 | @classmethod |
| 331 | def from_list(klass, a_list): |
| 332 | """Create a StackSummary from a simple list of tuples. |
| 333 | |
| 334 | This method supports the older Python API. Each tuple should be a |
| 335 | 4-tuple with (filename, lineno, name, line) elements. |
| 336 | """ |
| 337 | if isinstance(a_list, StackSummary): |
| 338 | return StackSummary(a_list) |
| 339 | result = StackSummary() |
| 340 | for filename, lineno, name, line in a_list: |
| 341 | result.append(FrameSummary(filename, lineno, name, line=line)) |
| 342 | return result |
| 343 | |
| 344 | def format(self): |
| 345 | """Format the stack ready for printing. |
| 346 | |
| 347 | Returns a list of strings ready for printing. Each string in the |
| 348 | resulting list corresponds to a single frame from the stack. |
| 349 | Each string ends in a newline; the strings may contain internal |
| 350 | newlines as well, for those items with source text lines. |
| 351 | """ |
| 352 | result = [] |
| 353 | for filename, lineno, name, line in self: |
| 354 | item = ' File "{}", line {}, in {}\n'.format(filename, lineno, name) |
| 355 | if line: |
| 356 | item = item + ' {}\n'.format(line.strip()) |
| 357 | result.append(item) |
| 358 | return result |
| 359 | |
| 360 | |
| 361 | class TracebackException: |
| 362 | """An exception ready for rendering. |
| 363 | |
| 364 | The traceback module captures enough attributes from the original exception |
| 365 | to this intermediary form to ensure that no references are held, while |
| 366 | still being able to fully print or format it. |
| 367 | |
| 368 | Use `from_exception` to create TracebackException instances from exception |
| 369 | objects, or the constructor to create TracebackException instances from |
| 370 | individual components. |
| 371 | |
| 372 | - :attr:`__cause__` A TracebackException of the original *__cause__*. |
| 373 | - :attr:`__context__` A TracebackException of the original *__context__*. |
| 374 | - :attr:`__suppress_context__` The *__suppress_context__* value from the |
| 375 | original exception. |
| 376 | - :attr:`stack` A `StackSummary` representing the traceback. |
| 377 | - :attr:`exc_type` The class of the original traceback. |
| 378 | - :attr:`filename` For syntax errors - the filename where the error |
| 379 | occured. |
| 380 | - :attr:`lineno` For syntax errors - the linenumber where the error |
| 381 | occured. |
| 382 | - :attr:`text` For syntax errors - the text where the error |
| 383 | occured. |
| 384 | - :attr:`offset` For syntax errors - the offset into the text where the |
| 385 | error occured. |
| 386 | - :attr:`msg` For syntax errors - the compiler error message. |
| 387 | """ |
| 388 | |
| 389 | def __init__(self, exc_type, exc_value, exc_traceback, limit=None, |
| 390 | lookup_lines=True, _seen=None): |
| 391 | # NB: we need to accept exc_traceback, exc_value, exc_traceback to |
| 392 | # permit backwards compat with the existing API, otherwise we |
| 393 | # need stub thunk objects just to glue it together. |
| 394 | # Handle loops in __cause__ or __context__. |
| 395 | if _seen is None: |
| 396 | _seen = set() |
| 397 | _seen.add(exc_value) |
| 398 | # Gracefully handle (the way Python 2.4 and earlier did) the case of |
| 399 | # being called with no type or value (None, None, None). |
| 400 | if (exc_value and exc_value.__cause__ is not None |
| 401 | and exc_value.__cause__ not in _seen): |
| 402 | cause = TracebackException( |
| 403 | type(exc_value.__cause__), |
| 404 | exc_value.__cause__, |
| 405 | exc_value.__cause__.__traceback__, |
| 406 | limit=limit, |
| 407 | lookup_lines=False, |
| 408 | _seen=_seen) |
| 409 | else: |
| 410 | cause = None |
| 411 | if (exc_value and exc_value.__context__ is not None |
| 412 | and exc_value.__context__ not in _seen): |
| 413 | context = TracebackException( |
| 414 | type(exc_value.__context__), |
| 415 | exc_value.__context__, |
| 416 | exc_value.__context__.__traceback__, |
| 417 | limit=limit, |
| 418 | lookup_lines=False, |
| 419 | _seen=_seen) |
| 420 | else: |
| 421 | context = None |
| 422 | self.__cause__ = cause |
| 423 | self.__context__ = context |
| 424 | self.__suppress_context__ = \ |
| 425 | exc_value.__suppress_context__ if exc_value else False |
| 426 | # TODO: locals. |
| 427 | self.stack = StackSummary.extract( |
| 428 | walk_tb(exc_traceback), limit=limit, lookup_lines=lookup_lines) |
| 429 | self.exc_type = exc_type |
| 430 | # Capture now to permit freeing resources: only complication is in the |
| 431 | # unofficial API _format_final_exc_line |
| 432 | self._str = _some_str(exc_value) |
| 433 | if exc_type and issubclass(exc_type, SyntaxError): |
| 434 | # Handle SyntaxError's specially |
| 435 | self.filename = exc_value.filename |
| 436 | self.lineno = str(exc_value.lineno) |
| 437 | self.text = exc_value.text |
| 438 | self.offset = exc_value.offset |
| 439 | self.msg = exc_value.msg |
| 440 | if lookup_lines: |
| 441 | self._load_lines() |
| 442 | |
| 443 | @classmethod |
| 444 | def from_exception(self, exc, *args, **kwargs): |
| 445 | """Create a TracebackException from an exception.""" |
| 446 | return TracebackException( |
| 447 | type(exc), exc, exc.__traceback__, *args, **kwargs) |
| 448 | |
| 449 | def _load_lines(self): |
| 450 | """Private API. force all lines in the stack to be loaded.""" |
| 451 | for frame in self.stack: |
| 452 | frame.line |
| 453 | if self.__context__: |
| 454 | self.__context__._load_lines() |
| 455 | if self.__cause__: |
| 456 | self.__cause__._load_lines() |
| 457 | |
| 458 | def __eq__(self, other): |
| 459 | return self.__dict__ == other.__dict__ |
| 460 | |
| 461 | def __str__(self): |
| 462 | return self._str |
| 463 | |
| 464 | def format_exception_only(self): |
| 465 | """Format the exception part of the traceback. |
| 466 | |
| 467 | The return value is a generator of strings, each ending in a newline. |
| 468 | |
| 469 | Normally, the generator emits a single string; however, for |
| 470 | SyntaxError exceptions, it emites several lines that (when |
| 471 | printed) display detailed information about where the syntax |
| 472 | error occurred. |
| 473 | |
| 474 | The message indicating which exception occurred is always the last |
| 475 | string in the output. |
| 476 | """ |
| 477 | if self.exc_type is None: |
| 478 | yield _format_final_exc_line(None, self._str) |
| 479 | return |
| 480 | |
| 481 | stype = self.exc_type.__qualname__ |
| 482 | smod = self.exc_type.__module__ |
| 483 | if smod not in ("__main__", "builtins"): |
| 484 | stype = smod + '.' + stype |
| 485 | |
| 486 | if not issubclass(self.exc_type, SyntaxError): |
| 487 | yield _format_final_exc_line(stype, self._str) |
| 488 | return |
| 489 | |
| 490 | # It was a syntax error; show exactly where the problem was found. |
| 491 | filename = self.filename or "<string>" |
| 492 | lineno = str(self.lineno) or '?' |
| 493 | yield ' File "{}", line {}\n'.format(filename, lineno) |
| 494 | |
| 495 | badline = self.text |
| 496 | offset = self.offset |
| 497 | if badline is not None: |
| 498 | yield ' {}\n'.format(badline.strip()) |
| 499 | if offset is not None: |
| 500 | caretspace = badline.rstrip('\n') |
| 501 | offset = min(len(caretspace), offset) - 1 |
| 502 | caretspace = caretspace[:offset].lstrip() |
| 503 | # non-space whitespace (likes tabs) must be kept for alignment |
| 504 | caretspace = ((c.isspace() and c or ' ') for c in caretspace) |
| 505 | yield ' {}^\n'.format(''.join(caretspace)) |
| 506 | msg = self.msg or "<no detail available>" |
| 507 | yield "{}: {}\n".format(stype, msg) |
| 508 | |
| 509 | def format(self, chain=True): |
| 510 | """Format the exception. |
| 511 | |
| 512 | If chain is not *True*, *__cause__* and *__context__* will not be formatted. |
| 513 | |
| 514 | The return value is a generator of strings, each ending in a newline and |
| 515 | some containing internal newlines. `print_exception` is a wrapper around |
| 516 | this method which just prints the lines to a file. |
| 517 | |
| 518 | The message indicating which exception occurred is always the last |
| 519 | string in the output. |
| 520 | """ |
| 521 | if chain: |
| 522 | if self.__cause__ is not None: |
| 523 | yield from self.__cause__.format(chain=chain) |
| 524 | yield _cause_message |
| 525 | elif (self.__context__ is not None and |
| 526 | not self.__suppress_context__): |
| 527 | yield from self.__context__.format(chain=chain) |
| 528 | yield _context_message |
| 529 | yield 'Traceback (most recent call last):\n' |
| 530 | yield from self.stack.format() |
| 531 | yield from self.format_exception_only() |