blob: b4fe05096565515bb8a1e8e13ba0356072cefceb [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
Guido van Rossum194e20a1995-09-20 20:31:51 +00007def _print(file, str='', terminator='\n'):
Tim Petersb90f89a2001-01-15 03:26:36 +00008 file.write(str+terminator)
Guido van Rossumdcc057a1996-08-12 23:18:13 +00009
10
11def print_list(extracted_list, file=None):
Tim Petersb90f89a2001-01-15 03:26:36 +000012 """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. Raymondec3bbde2001-02-09 09:39:08 +000020 _print(file, ' %s' % line.strip())
Guido van Rossumdcc057a1996-08-12 23:18:13 +000021
22def format_list(extracted_list):
Tim Petersb90f89a2001-01-15 03:26:36 +000023 """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. Raymondec3bbde2001-02-09 09:39:08 +000033 item = item + ' %s\n' % line.strip()
Tim Petersb90f89a2001-01-15 03:26:36 +000034 list.append(item)
35 return list
36
Guido van Rossum194e20a1995-09-20 20:31:51 +000037
38def print_tb(tb, limit=None, file=None):
Tim Petersb90f89a2001-01-15 03:26:36 +000039 """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. Raymondec3bbde2001-02-09 09:39:08 +000058 if line: _print(file, ' ' + line.strip())
Tim Petersb90f89a2001-01-15 03:26:36 +000059 tb = tb.tb_next
60 n = n+1
Guido van Rossum526beed1994-07-01 15:36:46 +000061
Guido van Rossum28e99fe1995-08-04 04:30:30 +000062def format_tb(tb, limit = None):
Tim Petersb90f89a2001-01-15 03:26:36 +000063 """A shorthand for 'format_list(extract_stack(f, limit))."""
64 return format_list(extract_tb(tb, limit))
Guido van Rossum28e99fe1995-08-04 04:30:30 +000065
Guido van Rossum526beed1994-07-01 15:36:46 +000066def extract_tb(tb, limit = None):
Tim Petersb90f89a2001-01-15 03:26:36 +000067 """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. Raymondec3bbde2001-02-09 09:39:08 +000087 if line: line = line.strip()
Tim Petersb90f89a2001-01-15 03:26:36 +000088 else: line = None
89 list.append((filename, lineno, name, line))
90 tb = tb.tb_next
91 n = n+1
92 return list
Guido van Rossum526beed1994-07-01 15:36:46 +000093
Guido van Rossum28e99fe1995-08-04 04:30:30 +000094
Guido van Rossum194e20a1995-09-20 20:31:51 +000095def print_exception(etype, value, tb, limit=None, file=None):
Tim Petersb90f89a2001-01-15 03:26:36 +000096 """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 Rossum28e99fe1995-08-04 04:30:30 +0000113
114def format_exception(etype, value, tb, limit = None):
Tim Petersb90f89a2001-01-15 03:26:36 +0000115 """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 Rossum28e99fe1995-08-04 04:30:30 +0000128
129def format_exception_only(etype, value):
Tim Petersb90f89a2001-01-15 03:26:36 +0000130 """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. Raymond6e025bc2001-02-10 00:22:33 +0000156 while i < len(line) and line[i].isspace():
Tim Petersb90f89a2001-01-15 03:26:36 +0000157 i = i+1
Eric S. Raymondec3bbde2001-02-09 09:39:08 +0000158 list.append(' %s\n' % line.strip())
Tim Petersb90f89a2001-01-15 03:26:36 +0000159 s = ' '
160 for c in line[i:offset-1]:
Eric S. Raymond6e025bc2001-02-10 00:22:33 +0000161 if c.isspace():
Tim Petersb90f89a2001-01-15 03:26:36 +0000162 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 Rossum28e99fe1995-08-04 04:30:30 +0000173
Guido van Rossum2823f032000-08-22 02:04:46 +0000174def _some_str(value):
Tim Petersb90f89a2001-01-15 03:26:36 +0000175 try:
176 return str(value)
177 except:
178 return '<unprintable %s object>' % type(value).__name__
Guido van Rossum2823f032000-08-22 02:04:46 +0000179
Guido van Rossum526beed1994-07-01 15:36:46 +0000180
Guido van Rossum194e20a1995-09-20 20:31:51 +0000181def print_exc(limit=None, file=None):
Tim Petersb90f89a2001-01-15 03:26:36 +0000182 """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 Rossum526beed1994-07-01 15:36:46 +0000193
Guido van Rossum194e20a1995-09-20 20:31:51 +0000194def print_last(limit=None, file=None):
Tim Petersb90f89a2001-01-15 03:26:36 +0000195 """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 Rossumdcc057a1996-08-12 23:18:13 +0000201
202
203def print_stack(f=None, limit=None, file=None):
Tim Petersb90f89a2001-01-15 03:26:36 +0000204 """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 Rossumdcc057a1996-08-12 23:18:13 +0000214
215def format_stack(f=None, limit=None):
Tim Petersb90f89a2001-01-15 03:26:36 +0000216 """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 Rossumdcc057a1996-08-12 23:18:13 +0000223
224def extract_stack(f=None, limit = None):
Tim Petersb90f89a2001-01-15 03:26:36 +0000225 """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. Raymondec3bbde2001-02-09 09:39:08 +0000247 if line: line = line.strip()
Tim Petersb90f89a2001-01-15 03:26:36 +0000248 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 Rossum47529661997-09-26 22:43:02 +0000254
Guido van Rossum47529661997-09-26 22:43:02 +0000255def tb_lineno(tb):
Tim Petersb90f89a2001-01-15 03:26:36 +0000256 """Calculate the correct line number of the traceback given in tb
257 (even with -O on)."""
Guido van Rossume7b146f2000-02-04 15:28:42 +0000258
Tim Petersb90f89a2001-01-15 03:26:36 +0000259 # 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 Rossume7b146f2000-02-04 15:28:42 +0000262
Tim Petersb90f89a2001-01-15 03:26:36 +0000263 c = tb.tb_frame.f_code
264 if not hasattr(c, 'co_lnotab'):
265 return tb.tb_lineno
Guido van Rossum6e73af71998-02-26 17:25:02 +0000266
Tim Petersb90f89a2001-01-15 03:26:36 +0000267 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