0001 """Extract, format and print information about Python stack traces.""" 0002 0003 import linecache 0004 import sys 0005 import types 0006 0007 __all__ = ['extract_stack', 'extract_tb', 'format_exception', 0008 'format_exception_only', 'format_list', 'format_stack', 0009 'format_tb', 'print_exc', 'format_exc', 'print_exception', 0010 'print_last', 'print_stack', 'print_tb', 'tb_lineno'] 0011 0012 def _print(file, str='', terminator='\n'): 0013 file.write(str+terminator) 0014 0015 0016 def print_list(extracted_list, file=None): 0017 """Print the list of tuples as returned by extract_tb() or 0018 extract_stack() as a formatted stack trace to the given file.""" 0019 if file is None: 0020 file = sys.stderr 0021 for filename, lineno, name, line in extracted_list: 0022 _print(file, 0023 ' File "%s", line %d, in %s' % (filename,lineno,name)) 0024 if line: 0025 _print(file, ' %s' % line.strip()) 0026 0027 def format_list(extracted_list): 0028 """Format a list of traceback entry tuples for printing. 0029 0030 Given a list of tuples as returned by extract_tb() or 0031 extract_stack(), return a list of strings ready for printing. 0032 Each string in the resulting list corresponds to the item with the 0033 same index in the argument list. Each string ends in a newline; 0034 the strings may contain internal newlines as well, for those items 0035 whose source text line is not None. 0036 """ 0037 list = [] 0038 for filename, lineno, name, line in extracted_list: 0039 item = ' File "%s", line %d, in %s\n' % (filename,lineno,name) 0040 if line: 0041 item = item + ' %s\n' % line.strip() 0042 list.append(item) 0043 return list 0044 0045 0046 def print_tb(tb, limit=None, file=None): 0047 """Print up to 'limit' stack trace entries from the traceback 'tb'. 0048 0049 If 'limit' is omitted or None, all entries are printed. If 'file' 0050 is omitted or None, the output goes to sys.stderr; otherwise 0051 'file' should be an open file or file-like object with a write() 0052 method. 0053 """ 0054 if file is None: 0055 file = sys.stderr 0056 if limit is None: 0057 if hasattr(sys, 'tracebacklimit'): 0058 limit = sys.tracebacklimit 0059 n = 0 0060 while tb is not None and (limit is None or n < limit): 0061 f = tb.tb_frame 0062 lineno = tb.tb_lineno 0063 co = f.f_code 0064 filename = co.co_filename 0065 name = co.co_name 0066 _print(file, 0067 ' File "%s", line %d, in %s' % (filename,lineno,name)) 0068 linecache.checkcache(filename) 0069 line = linecache.getline(filename, lineno) 0070 if line: _print(file, ' ' + line.strip()) 0071 tb = tb.tb_next 0072 n = n+1 0073 0074 def format_tb(tb, limit = None): 0075 """A shorthand for 'format_list(extract_stack(f, limit)).""" 0076 return format_list(extract_tb(tb, limit)) 0077 0078 def extract_tb(tb, limit = None): 0079 """Return list of up to limit pre-processed entries from traceback. 0080 0081 This is useful for alternate formatting of stack traces. If 0082 'limit' is omitted or None, all entries are extracted. A 0083 pre-processed stack trace entry is a quadruple (filename, line 0084 number, function name, text) representing the information that is 0085 usually printed for a stack trace. The text is a string with 0086 leading and trailing whitespace stripped; if the source is not 0087 available it is None. 0088 """ 0089 if limit is None: 0090 if hasattr(sys, 'tracebacklimit'): 0091 limit = sys.tracebacklimit 0092 list = [] 0093 n = 0 0094 while tb is not None and (limit is None or n < limit): 0095 f = tb.tb_frame 0096 lineno = tb.tb_lineno 0097 co = f.f_code 0098 filename = co.co_filename 0099 name = co.co_name 0100 linecache.checkcache(filename) 0101 line = linecache.getline(filename, lineno) 0102 if line: line = line.strip() 0103 else: line = None 0104 list.append((filename, lineno, name, line)) 0105 tb = tb.tb_next 0106 n = n+1 0107 return list 0108 0109 0110 def print_exception(etype, value, tb, limit=None, file=None): 0111 """Print exception up to 'limit' stack trace entries from 'tb' to 'file'. 0112 0113 This differs from print_tb() in the following ways: (1) if 0114 traceback is not None, it prints a header "Traceback (most recent 0115 call last):"; (2) it prints the exception type and value after the 0116 stack trace; (3) if type is SyntaxError and value has the 0117 appropriate format, it prints the line where the syntax error 0118 occurred with a caret on the next line indicating the approximate 0119 position of the error. 0120 """ 0121 if file is None: 0122 file = sys.stderr 0123 if tb: 0124 _print(file, 'Traceback (most recent call last):') 0125 print_tb(tb, limit, file) 0126 lines = format_exception_only(etype, value) 0127 for line in lines[:-1]: 0128 _print(file, line, ' ') 0129 _print(file, lines[-1], '') 0130 0131 def format_exception(etype, value, tb, limit = None): 0132 """Format a stack trace and the exception information. 0133 0134 The arguments have the same meaning as the corresponding arguments 0135 to print_exception(). The return value is a list of strings, each 0136 ending in a newline and some containing internal newlines. When 0137 these lines are concatenated and printed, exactly the same text is 0138 printed as does print_exception(). 0139 """ 0140 if tb: 0141 list = ['Traceback (most recent call last):\n'] 0142 list = list + format_tb(tb, limit) 0143 else: 0144 list = [] 0145 list = list + format_exception_only(etype, value) 0146 return list 0147 0148 def format_exception_only(etype, value): 0149 """Format the exception part of a traceback. 0150 0151 The arguments are the exception type and value such as given by 0152 sys.last_type and sys.last_value. The return value is a list of 0153 strings, each ending in a newline. Normally, the list contains a 0154 single string; however, for SyntaxError exceptions, it contains 0155 several lines that (when printed) display detailed information 0156 about where the syntax error occurred. The message indicating 0157 which exception occurred is the always last string in the list. 0158 """ 0159 list = [] 0160 if type(etype) == types.ClassType: 0161 stype = etype.__name__ 0162 else: 0163 stype = etype 0164 if value is None: 0165 list.append(str(stype) + '\n') 0166 else: 0167 if etype is SyntaxError: 0168 try: 0169 msg, (filename, lineno, offset, line) = value 0170 except: 0171 pass 0172 else: 0173 if not filename: filename = "<string>" 0174 list.append(' File "%s", line %d\n' % 0175 (filename, lineno)) 0176 if line is not None: 0177 i = 0 0178 while i < len(line) and line[i].isspace(): 0179 i = i+1 0180 list.append(' %s\n' % line.strip()) 0181 if offset is not None: 0182 s = ' ' 0183 for c in line[i:offset-1]: 0184 if c.isspace(): 0185 s = s + c 0186 else: 0187 s = s + ' ' 0188 list.append('%s^\n' % s) 0189 value = msg 0190 s = _some_str(value) 0191 if s: 0192 list.append('%s: %s\n' % (str(stype), s)) 0193 else: 0194 list.append('%s\n' % str(stype)) 0195 return list 0196 0197 def _some_str(value): 0198 try: 0199 return str(value) 0200 except: 0201 return '<unprintable %s object>' % type(value).__name__ 0202 0203 0204 def print_exc(limit=None, file=None): 0205 """Shorthand for 'print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)'. 0206 (In fact, it uses sys.exc_info() to retrieve the same information 0207 in a thread-safe way.)""" 0208 if file is None: 0209 file = sys.stderr 0210 try: 0211 etype, value, tb = sys.exc_info() 0212 print_exception(etype, value, tb, limit, file) 0213 finally: 0214 etype = value = tb = None 0215 0216 0217 def format_exc(limit=None): 0218 """Like print_exc() but return a string.""" 0219 try: 0220 etype, value, tb = sys.exc_info() 0221 return ''.join(format_exception(etype, value, tb, limit)) 0222 finally: 0223 etype = value = tb = None 0224 0225 0226 def print_last(limit=None, file=None): 0227 """This is a shorthand for 'print_exception(sys.last_type, 0228 sys.last_value, sys.last_traceback, limit, file)'.""" 0229 if file is None: 0230 file = sys.stderr 0231 print_exception(sys.last_type, sys.last_value, sys.last_traceback, 0232 limit, file) 0233 0234 0235 def print_stack(f=None, limit=None, file=None): 0236 """Print a stack trace from its invocation point. 0237 0238 The optional 'f' argument can be used to specify an alternate 0239 stack frame at which to start. The optional 'limit' and 'file' 0240 arguments have the same meaning as for print_exception(). 0241 """ 0242 if f is None: 0243 try: 0244 raise ZeroDivisionError 0245 except ZeroDivisionError: 0246 f = sys.exc_info()[2].tb_frame.f_back 0247 print_list(extract_stack(f, limit), file) 0248 0249 def format_stack(f=None, limit=None): 0250 """Shorthand for 'format_list(extract_stack(f, limit))'.""" 0251 if f is None: 0252 try: 0253 raise ZeroDivisionError 0254 except ZeroDivisionError: 0255 f = sys.exc_info()[2].tb_frame.f_back 0256 return format_list(extract_stack(f, limit)) 0257 0258 def extract_stack(f=None, limit = None): 0259 """Extract the raw traceback from the current stack frame. 0260 0261 The return value has the same format as for extract_tb(). The 0262 optional 'f' and 'limit' arguments have the same meaning as for 0263 print_stack(). Each item in the list is a quadruple (filename, 0264 line number, function name, text), and the entries are in order 0265 from oldest to newest stack frame. 0266 """ 0267 if f is None: 0268 try: 0269 raise ZeroDivisionError 0270 except ZeroDivisionError: 0271 f = sys.exc_info()[2].tb_frame.f_back 0272 if limit is None: 0273 if hasattr(sys, 'tracebacklimit'): 0274 limit = sys.tracebacklimit 0275 list = [] 0276 n = 0 0277 while f is not None and (limit is None or n < limit): 0278 lineno = f.f_lineno 0279 co = f.f_code 0280 filename = co.co_filename 0281 name = co.co_name 0282 linecache.checkcache(filename) 0283 line = linecache.getline(filename, lineno) 0284 if line: line = line.strip() 0285 else: line = None 0286 list.append((filename, lineno, name, line)) 0287 f = f.f_back 0288 n = n+1 0289 list.reverse() 0290 return list 0291 0292 def tb_lineno(tb): 0293 """Calculate correct line number of traceback given in tb. 0294 0295 Obsolete in 2.3. 0296 """ 0297 return tb.tb_lineno 0298
Generated by PyXR 0.9.4