(py-outdent-p): new function
[python/dscho.git] / Lib / traceback.py
blob5ab3ec6b347890663288ade3a0ca8c3cf1182e16
1 # Format and print Python stack traces
3 import linecache
4 import string
5 import sys
6 import types
8 def print_tb(tb, limit = None):
9 if limit is None:
10 if hasattr(sys, 'tracebacklimit'):
11 limit = sys.tracebacklimit
12 n = 0
13 while tb is not None and (limit is None or n < limit):
14 f = tb.tb_frame
15 lineno = tb.tb_lineno
16 co = f.f_code
17 filename = co.co_filename
18 name = co.co_name
19 print ' File "%s", line %d, in %s' % (filename, lineno, name)
20 line = linecache.getline(filename, lineno)
21 if line: print ' ' + string.strip(line)
22 tb = tb.tb_next
23 n = n+1
25 def extract_tb(tb, limit = None):
26 if limit is None:
27 if hasattr(sys, 'tracebacklimit'):
28 limit = sys.tracebacklimit
29 list = []
30 n = 0
31 while tb is not None and (limit is None or n < limit):
32 f = tb.tb_frame
33 lineno = tb.tb_lineno
34 co = f.f_code
35 filename = co.co_filename
36 name = co.co_name
37 line = linecache.getline(filename, lineno)
38 if line: line = string.strip(line)
39 else: line = None
40 list.append(filename, lineno, name, line)
41 tb = tb.tb_next
42 n = n+1
43 return list
45 def print_exception(etype, value, tb, limit = None):
46 if tb:
47 print 'Traceback (innermost last):'
48 print_tb(tb, limit)
49 if type(etype) == types.ClassType:
50 stype = etype.__name__
51 else:
52 stype = etype
53 if value is None:
54 print stype
55 else:
56 if etype is SyntaxError:
57 try:
58 msg, (filename, lineno, offset, line) = value
59 except:
60 pass
61 else:
62 if not filename: filename = "<string>"
63 print ' File "%s", line %d' % \
64 (filename, lineno)
65 i = 0
66 while i < len(line) and \
67 line[i] in string.whitespace:
68 i = i+1
69 s = ' '
70 print s + string.strip(line)
71 for c in line[i:offset-1]:
72 if c in string.whitespace:
73 s = s + c
74 else:
75 s = s + ' '
76 print s + '^'
77 value = msg
78 print '%s: %s' % (stype, value)
80 def print_exc(limit = None):
81 print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback,
82 limit)
84 def print_last(limit = None):
85 print_exception(sys.last_type, sys.last_value, sys.last_traceback,
86 limit)