blob: 89ecb615d54093556b1d2b381d7126991fa61d04 [file] [log] [blame]
Guido van Rossume7b146f2000-02-04 15:28:42 +00001"""Extract, format and print information about Python stack traces."""
Guido van Rossum526beed1994-07-01 15:36:46 +00002
3import linecache
Guido van Rossum526beed1994-07-01 15:36:46 +00004import sys
Guido van Rossumc7acf2a1995-02-27 13:15:45 +00005import types
Guido van Rossum526beed1994-07-01 15:36:46 +00006
Skip Montanaro40fc1602001-03-01 04:27:19 +00007__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 Rossum194e20a1995-09-20 20:31:51 +000012def _print(file, str='', terminator='\n'):
Tim Petersb90f89a2001-01-15 03:26:36 +000013 file.write(str+terminator)
Guido van Rossumdcc057a1996-08-12 23:18:13 +000014
15
16def print_list(extracted_list, file=None):
Tim Petersb90f89a2001-01-15 03:26:36 +000017 """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. Raymondec3bbde2001-02-09 09:39:08 +000025 _print(file, ' %s' % line.strip())
Guido van Rossumdcc057a1996-08-12 23:18:13 +000026
27def format_list(extracted_list):
Tim Petersb90f89a2001-01-15 03:26:36 +000028 """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. Raymondec3bbde2001-02-09 09:39:08 +000038 item = item + ' %s\n' % line.strip()
Tim Petersb90f89a2001-01-15 03:26:36 +000039 list.append(item)
40 return list
41
Guido van Rossum194e20a1995-09-20 20:31:51 +000042
43def print_tb(tb, limit=None, file=None):
Tim Petersb90f89a2001-01-15 03:26:36 +000044 """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. Raymondec3bbde2001-02-09 09:39:08 +000063 if line: _print(file, ' ' + line.strip())
Tim Petersb90f89a2001-01-15 03:26:36 +000064 tb = tb.tb_next
65 n = n+1
Guido van Rossum526beed1994-07-01 15:36:46 +000066
Guido van Rossum28e99fe1995-08-04 04:30:30 +000067def format_tb(tb, limit = None):
Tim Petersb90f89a2001-01-15 03:26:36 +000068 """A shorthand for 'format_list(extract_stack(f, limit))."""
69 return format_list(extract_tb(tb, limit))
Guido van Rossum28e99fe1995-08-04 04:30:30 +000070
Guido van Rossum526beed1994-07-01 15:36:46 +000071def extract_tb(tb, limit = None):
Tim Petersb90f89a2001-01-15 03:26:36 +000072 """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. Raymondec3bbde2001-02-09 09:39:08 +000092 if line: line = line.strip()
Tim Petersb90f89a2001-01-15 03:26:36 +000093 else: line = None
94 list.append((filename, lineno, name, line))
95 tb = tb.tb_next
96 n = n+1
97 return list
Guido van Rossum526beed1994-07-01 15:36:46 +000098
Guido van Rossum28e99fe1995-08-04 04:30:30 +000099
Guido van Rossum194e20a1995-09-20 20:31:51 +0000100def print_exception(etype, value, tb, limit=None, file=None):
Tim Petersb90f89a2001-01-15 03:26:36 +0000101 """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 Rossum28e99fe1995-08-04 04:30:30 +0000118
119def format_exception(etype, value, tb, limit = None):
Tim Petersb90f89a2001-01-15 03:26:36 +0000120 """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 Rossum28e99fe1995-08-04 04:30:30 +0000133
134def format_exception_only(etype, value):
Tim Petersb90f89a2001-01-15 03:26:36 +0000135 """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. Raymond6e025bc2001-02-10 00:22:33 +0000161 while i < len(line) and line[i].isspace():
Tim Petersb90f89a2001-01-15 03:26:36 +0000162 i = i+1
Eric S. Raymondec3bbde2001-02-09 09:39:08 +0000163 list.append(' %s\n' % line.strip())
Tim Petersb90f89a2001-01-15 03:26:36 +0000164 s = ' '
165 for c in line[i:offset-1]:
Eric S. Raymond6e025bc2001-02-10 00:22:33 +0000166 if c.isspace():
Tim Petersb90f89a2001-01-15 03:26:36 +0000167 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 Rossum28e99fe1995-08-04 04:30:30 +0000178
Guido van Rossum2823f032000-08-22 02:04:46 +0000179def _some_str(value):
Tim Petersb90f89a2001-01-15 03:26:36 +0000180 try:
181 return str(value)
182 except:
183 return '<unprintable %s object>' % type(value).__name__
Guido van Rossum2823f032000-08-22 02:04:46 +0000184
Guido van Rossum526beed1994-07-01 15:36:46 +0000185
Guido van Rossum194e20a1995-09-20 20:31:51 +0000186def print_exc(limit=None, file=None):
Tim Petersb90f89a2001-01-15 03:26:36 +0000187 """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 Rossum526beed1994-07-01 15:36:46 +0000198
Guido van Rossum194e20a1995-09-20 20:31:51 +0000199def print_last(limit=None, file=None):
Tim Petersb90f89a2001-01-15 03:26:36 +0000200 """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 Rossumdcc057a1996-08-12 23:18:13 +0000206
207
208def print_stack(f=None, limit=None, file=None):
Tim Petersb90f89a2001-01-15 03:26:36 +0000209 """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 Rossumdcc057a1996-08-12 23:18:13 +0000219
220def format_stack(f=None, limit=None):
Tim Petersb90f89a2001-01-15 03:26:36 +0000221 """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 Rossumdcc057a1996-08-12 23:18:13 +0000228
229def extract_stack(f=None, limit = None):
Tim Petersb90f89a2001-01-15 03:26:36 +0000230 """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. Raymondec3bbde2001-02-09 09:39:08 +0000252 if line: line = line.strip()
Tim Petersb90f89a2001-01-15 03:26:36 +0000253 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 Rossum47529661997-09-26 22:43:02 +0000259
Guido van Rossum47529661997-09-26 22:43:02 +0000260def tb_lineno(tb):
Tim Petersb90f89a2001-01-15 03:26:36 +0000261 """Calculate the correct line number of the traceback given in tb
262 (even with -O on)."""
Guido van Rossume7b146f2000-02-04 15:28:42 +0000263
Tim Petersb90f89a2001-01-15 03:26:36 +0000264 # 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 Rossume7b146f2000-02-04 15:28:42 +0000267
Tim Petersb90f89a2001-01-15 03:26:36 +0000268 c = tb.tb_frame.f_code
269 if not hasattr(c, 'co_lnotab'):
270 return tb.tb_lineno
Guido van Rossum6e73af71998-02-26 17:25:02 +0000271
Tim Petersb90f89a2001-01-15 03:26:36 +0000272 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