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 |
Guido van Rossum | c7acf2a | 1995-02-27 13:15:45 +0000 | [diff] [blame] | 5 | import types |
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', |
| 9 | 'format_tb', 'print_exc', 'print_exception', 'print_last', |
| 10 | 'print_stack', 'print_tb', 'tb_lineno'] |
| 11 | |
Guido van Rossum | 194e20a | 1995-09-20 20:31:51 +0000 | [diff] [blame] | 12 | def _print(file, str='', terminator='\n'): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 13 | file.write(str+terminator) |
Guido van Rossum | dcc057a | 1996-08-12 23:18:13 +0000 | [diff] [blame] | 14 | |
| 15 | |
| 16 | def print_list(extracted_list, file=None): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 17 | """Print the list of tuples as returned by extract_tb() or |
| 18 | extract_stack() as a formatted stack trace to the given file.""" |
| 19 | if not file: |
| 20 | file = sys.stderr |
| 21 | for filename, lineno, name, line in extracted_list: |
| 22 | _print(file, |
| 23 | ' File "%s", line %d, in %s' % (filename,lineno,name)) |
| 24 | if line: |
Eric S. Raymond | ec3bbde | 2001-02-09 09:39:08 +0000 | [diff] [blame] | 25 | _print(file, ' %s' % line.strip()) |
Guido van Rossum | dcc057a | 1996-08-12 23:18:13 +0000 | [diff] [blame] | 26 | |
| 27 | def format_list(extracted_list): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 28 | """Given a list of tuples as returned by extract_tb() or |
| 29 | extract_stack(), return a list of strings ready for printing. |
| 30 | Each string in the resulting list corresponds to the item with |
| 31 | the same index in the argument list. Each string ends in a |
| 32 | newline; the strings may contain internal newlines as well, for |
| 33 | those items whose source text line is not None.""" |
| 34 | list = [] |
| 35 | for filename, lineno, name, line in extracted_list: |
| 36 | item = ' File "%s", line %d, in %s\n' % (filename,lineno,name) |
| 37 | if line: |
Eric S. Raymond | ec3bbde | 2001-02-09 09:39:08 +0000 | [diff] [blame] | 38 | item = item + ' %s\n' % line.strip() |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 39 | list.append(item) |
| 40 | return list |
| 41 | |
Guido van Rossum | 194e20a | 1995-09-20 20:31:51 +0000 | [diff] [blame] | 42 | |
| 43 | def print_tb(tb, limit=None, file=None): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 44 | """Print up to 'limit' stack trace entries from the traceback 'tb'. |
| 45 | If 'limit' is omitted or None, all entries are printed. If 'file' is |
| 46 | omitted or None, the output goes to sys.stderr; otherwise 'file' |
| 47 | should be an open file or file-like object with a write() method.""" |
| 48 | if not file: |
| 49 | file = sys.stderr |
| 50 | if limit is None: |
| 51 | if hasattr(sys, 'tracebacklimit'): |
| 52 | limit = sys.tracebacklimit |
| 53 | n = 0 |
| 54 | while tb is not None and (limit is None or n < limit): |
| 55 | f = tb.tb_frame |
| 56 | lineno = tb_lineno(tb) |
| 57 | co = f.f_code |
| 58 | filename = co.co_filename |
| 59 | name = co.co_name |
| 60 | _print(file, |
| 61 | ' File "%s", line %d, in %s' % (filename,lineno,name)) |
| 62 | line = linecache.getline(filename, lineno) |
Eric S. Raymond | ec3bbde | 2001-02-09 09:39:08 +0000 | [diff] [blame] | 63 | if line: _print(file, ' ' + line.strip()) |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 64 | tb = tb.tb_next |
| 65 | n = n+1 |
Guido van Rossum | 526beed | 1994-07-01 15:36:46 +0000 | [diff] [blame] | 66 | |
Guido van Rossum | 28e99fe | 1995-08-04 04:30:30 +0000 | [diff] [blame] | 67 | def format_tb(tb, limit = None): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 68 | """A shorthand for 'format_list(extract_stack(f, limit)).""" |
| 69 | return format_list(extract_tb(tb, limit)) |
Guido van Rossum | 28e99fe | 1995-08-04 04:30:30 +0000 | [diff] [blame] | 70 | |
Guido van Rossum | 526beed | 1994-07-01 15:36:46 +0000 | [diff] [blame] | 71 | def extract_tb(tb, limit = None): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 72 | """Return a list of up to 'limit' pre-processed stack trace entries |
| 73 | extracted from the traceback object 'traceback'. This is useful for |
| 74 | alternate formatting of stack traces. If 'limit' is omitted or None, |
| 75 | all entries are extracted. A pre-processed stack trace entry is a |
| 76 | quadruple (filename, line number, function name, text) representing |
| 77 | the information that is usually printed for a stack trace. The text |
| 78 | is a string with leading and trailing whitespace stripped; if the |
| 79 | source is not available it is None.""" |
| 80 | if limit is None: |
| 81 | if hasattr(sys, 'tracebacklimit'): |
| 82 | limit = sys.tracebacklimit |
| 83 | list = [] |
| 84 | n = 0 |
| 85 | while tb is not None and (limit is None or n < limit): |
| 86 | f = tb.tb_frame |
| 87 | lineno = tb_lineno(tb) |
| 88 | co = f.f_code |
| 89 | filename = co.co_filename |
| 90 | name = co.co_name |
| 91 | line = linecache.getline(filename, lineno) |
Eric S. Raymond | ec3bbde | 2001-02-09 09:39:08 +0000 | [diff] [blame] | 92 | if line: line = line.strip() |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 93 | else: line = None |
| 94 | list.append((filename, lineno, name, line)) |
| 95 | tb = tb.tb_next |
| 96 | n = n+1 |
| 97 | return list |
Guido van Rossum | 526beed | 1994-07-01 15:36:46 +0000 | [diff] [blame] | 98 | |
Guido van Rossum | 28e99fe | 1995-08-04 04:30:30 +0000 | [diff] [blame] | 99 | |
Guido van Rossum | 194e20a | 1995-09-20 20:31:51 +0000 | [diff] [blame] | 100 | def print_exception(etype, value, tb, limit=None, file=None): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 101 | """Print exception information and up to 'limit' stack trace entries |
| 102 | from the traceback 'tb' to 'file'. This differs from print_tb() in |
| 103 | the following ways: (1) if traceback is not None, it prints a header |
| 104 | "Traceback (most recent call last):"; (2) it prints the exception type and |
| 105 | value after the stack trace; (3) if type is SyntaxError and value has |
| 106 | the appropriate format, it prints the line where the syntax error |
| 107 | occurred with a caret on the next line indicating the approximate |
| 108 | position of the error.""" |
| 109 | if not file: |
| 110 | file = sys.stderr |
| 111 | if tb: |
| 112 | _print(file, 'Traceback (most recent call last):') |
| 113 | print_tb(tb, limit, file) |
| 114 | lines = format_exception_only(etype, value) |
| 115 | for line in lines[:-1]: |
| 116 | _print(file, line, ' ') |
| 117 | _print(file, lines[-1], '') |
Guido van Rossum | 28e99fe | 1995-08-04 04:30:30 +0000 | [diff] [blame] | 118 | |
| 119 | def format_exception(etype, value, tb, limit = None): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 120 | """Format a stack trace and the exception information. The arguments |
| 121 | have the same meaning as the corresponding arguments to |
| 122 | print_exception(). The return value is a list of strings, each |
| 123 | ending in a newline and some containing internal newlines. When |
| 124 | these lines are concatenated and printed, exactly the same text is |
| 125 | printed as does print_exception().""" |
| 126 | if tb: |
| 127 | list = ['Traceback (most recent call last):\n'] |
| 128 | list = list + format_tb(tb, limit) |
| 129 | else: |
| 130 | list = [] |
| 131 | list = list + format_exception_only(etype, value) |
| 132 | return list |
Guido van Rossum | 28e99fe | 1995-08-04 04:30:30 +0000 | [diff] [blame] | 133 | |
| 134 | def format_exception_only(etype, value): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 135 | """Format the exception part of a traceback. The arguments are the |
| 136 | exception type and value such as given by sys.last_type and |
| 137 | sys.last_value. The return value is a list of strings, each ending |
| 138 | in a newline. Normally, the list contains a single string; |
| 139 | however, for SyntaxError exceptions, it contains several lines that |
| 140 | (when printed) display detailed information about where the syntax |
| 141 | error occurred. The message indicating which exception occurred is |
| 142 | the always last string in the list.""" |
| 143 | list = [] |
| 144 | if type(etype) == types.ClassType: |
| 145 | stype = etype.__name__ |
| 146 | else: |
| 147 | stype = etype |
| 148 | if value is None: |
| 149 | list.append(str(stype) + '\n') |
| 150 | else: |
| 151 | if etype is SyntaxError: |
| 152 | try: |
| 153 | msg, (filename, lineno, offset, line) = value |
| 154 | except: |
| 155 | pass |
| 156 | else: |
| 157 | if not filename: filename = "<string>" |
| 158 | list.append(' File "%s", line %d\n' % |
| 159 | (filename, lineno)) |
| 160 | i = 0 |
Eric S. Raymond | 6e025bc | 2001-02-10 00:22:33 +0000 | [diff] [blame] | 161 | while i < len(line) and line[i].isspace(): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 162 | i = i+1 |
Eric S. Raymond | ec3bbde | 2001-02-09 09:39:08 +0000 | [diff] [blame] | 163 | list.append(' %s\n' % line.strip()) |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 164 | s = ' ' |
| 165 | for c in line[i:offset-1]: |
Eric S. Raymond | 6e025bc | 2001-02-10 00:22:33 +0000 | [diff] [blame] | 166 | if c.isspace(): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 167 | s = s + c |
| 168 | else: |
| 169 | s = s + ' ' |
| 170 | list.append('%s^\n' % s) |
| 171 | value = msg |
| 172 | s = _some_str(value) |
| 173 | if s: |
| 174 | list.append('%s: %s\n' % (str(stype), s)) |
| 175 | else: |
| 176 | list.append('%s\n' % str(stype)) |
| 177 | return list |
Guido van Rossum | 28e99fe | 1995-08-04 04:30:30 +0000 | [diff] [blame] | 178 | |
Guido van Rossum | 2823f03 | 2000-08-22 02:04:46 +0000 | [diff] [blame] | 179 | def _some_str(value): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 180 | try: |
| 181 | return str(value) |
| 182 | except: |
| 183 | return '<unprintable %s object>' % type(value).__name__ |
Guido van Rossum | 2823f03 | 2000-08-22 02:04:46 +0000 | [diff] [blame] | 184 | |
Guido van Rossum | 526beed | 1994-07-01 15:36:46 +0000 | [diff] [blame] | 185 | |
Guido van Rossum | 194e20a | 1995-09-20 20:31:51 +0000 | [diff] [blame] | 186 | def print_exc(limit=None, file=None): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 187 | """This is a shorthand for 'print_exception(sys.exc_type, |
| 188 | sys.exc_value, sys.exc_traceback, limit, file)'. |
| 189 | (In fact, it uses sys.exc_info() to retrieve the same information |
| 190 | in a thread-safe way.)""" |
| 191 | if not file: |
| 192 | file = sys.stderr |
| 193 | try: |
| 194 | etype, value, tb = sys.exc_info() |
| 195 | print_exception(etype, value, tb, limit, file) |
| 196 | finally: |
| 197 | etype = value = tb = None |
Guido van Rossum | 526beed | 1994-07-01 15:36:46 +0000 | [diff] [blame] | 198 | |
Guido van Rossum | 194e20a | 1995-09-20 20:31:51 +0000 | [diff] [blame] | 199 | def print_last(limit=None, file=None): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 200 | """This is a shorthand for 'print_exception(sys.last_type, |
| 201 | sys.last_value, sys.last_traceback, limit, file)'.""" |
| 202 | if not file: |
| 203 | file = sys.stderr |
| 204 | print_exception(sys.last_type, sys.last_value, sys.last_traceback, |
| 205 | limit, file) |
Guido van Rossum | dcc057a | 1996-08-12 23:18:13 +0000 | [diff] [blame] | 206 | |
| 207 | |
| 208 | def print_stack(f=None, limit=None, file=None): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 209 | """This function prints a stack trace from its invocation point. |
| 210 | The optional 'f' argument can be used to specify an alternate stack |
| 211 | frame at which to start. The optional 'limit' and 'file' arguments |
| 212 | have the same meaning as for print_exception().""" |
| 213 | if f is None: |
| 214 | try: |
| 215 | raise ZeroDivisionError |
| 216 | except ZeroDivisionError: |
| 217 | f = sys.exc_info()[2].tb_frame.f_back |
| 218 | print_list(extract_stack(f, limit), file) |
Guido van Rossum | dcc057a | 1996-08-12 23:18:13 +0000 | [diff] [blame] | 219 | |
| 220 | def format_stack(f=None, limit=None): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 221 | """A shorthand for 'format_list(extract_stack(f, limit))'.""" |
| 222 | if f is None: |
| 223 | try: |
| 224 | raise ZeroDivisionError |
| 225 | except ZeroDivisionError: |
| 226 | f = sys.exc_info()[2].tb_frame.f_back |
| 227 | return format_list(extract_stack(f, limit)) |
Guido van Rossum | dcc057a | 1996-08-12 23:18:13 +0000 | [diff] [blame] | 228 | |
| 229 | def extract_stack(f=None, limit = None): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 230 | """Extract the raw traceback from the current stack frame. The |
| 231 | return value has the same format as for extract_tb(). The optional |
| 232 | 'f' and 'limit' arguments have the same meaning as for print_stack(). |
| 233 | Each item in the list is a quadruple (filename, line number, |
| 234 | function name, text), and the entries are in order from oldest |
| 235 | to newest stack frame.""" |
| 236 | if f is None: |
| 237 | try: |
| 238 | raise ZeroDivisionError |
| 239 | except ZeroDivisionError: |
| 240 | f = sys.exc_info()[2].tb_frame.f_back |
| 241 | if limit is None: |
| 242 | if hasattr(sys, 'tracebacklimit'): |
| 243 | limit = sys.tracebacklimit |
| 244 | list = [] |
| 245 | n = 0 |
| 246 | while f is not None and (limit is None or n < limit): |
| 247 | lineno = f.f_lineno # XXX Too bad if -O is used |
| 248 | co = f.f_code |
| 249 | filename = co.co_filename |
| 250 | name = co.co_name |
| 251 | line = linecache.getline(filename, lineno) |
Eric S. Raymond | ec3bbde | 2001-02-09 09:39:08 +0000 | [diff] [blame] | 252 | if line: line = line.strip() |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 253 | else: line = None |
| 254 | list.append((filename, lineno, name, line)) |
| 255 | f = f.f_back |
| 256 | n = n+1 |
| 257 | list.reverse() |
| 258 | return list |
Guido van Rossum | 4752966 | 1997-09-26 22:43:02 +0000 | [diff] [blame] | 259 | |
Guido van Rossum | 4752966 | 1997-09-26 22:43:02 +0000 | [diff] [blame] | 260 | def tb_lineno(tb): |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 261 | """Calculate the correct line number of the traceback given in tb |
| 262 | (even with -O on).""" |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 263 | |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 264 | # Coded by Marc-Andre Lemburg from the example of PyCode_Addr2Line() |
| 265 | # in compile.c. |
| 266 | # Revised version by Jim Hugunin to work with JPython too. |
Guido van Rossum | e7b146f | 2000-02-04 15:28:42 +0000 | [diff] [blame] | 267 | |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 268 | c = tb.tb_frame.f_code |
| 269 | if not hasattr(c, 'co_lnotab'): |
| 270 | return tb.tb_lineno |
Guido van Rossum | 6e73af7 | 1998-02-26 17:25:02 +0000 | [diff] [blame] | 271 | |
Tim Peters | b90f89a | 2001-01-15 03:26:36 +0000 | [diff] [blame] | 272 | tab = c.co_lnotab |
| 273 | line = c.co_firstlineno |
| 274 | stopat = tb.tb_lasti |
| 275 | addr = 0 |
| 276 | for i in range(0, len(tab), 2): |
| 277 | addr = addr + ord(tab[i]) |
| 278 | if addr > stopat: |
| 279 | break |
| 280 | line = line + ord(tab[i+1]) |
| 281 | return line |