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