1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 """
21 Debugging helper code
22 """
23
24
25 import sys
26 import re
27 import linecache
28
29 from twisted.python.reflect import filenameToModuleName
30
31
32 _tracing = 0
33 _indent = ''
34
35 -def trace_start(func_filter=None, ignore_files_re=None, print_returns=False,
36 write=None):
37 global _tracing, _indent
38
39 if func_filter:
40 func_filter = re.compile(func_filter)
41
42 if ignore_files_re:
43 ignore_files_re = re.compile(ignore_files_re)
44
45 if not write:
46 def write(indent, str, *args):
47 print (indent + str) % args
48
49 def do_trace(frame, event, arg):
50 global _tracing, _indent
51
52 if not _tracing:
53 print '[tracing stopped]'
54 return None
55
56 co = frame.f_code
57
58 if event == 'line':
59 return do_trace
60 if func_filter and not func_filter.search(co.co_name):
61 return None
62 if ignore_files_re and ignore_files_re.search(co.co_filename):
63 return None
64 elif event == 'call' or event == 'c_call':
65 if co.co_name == '?':
66 return None
67 module = filenameToModuleName(co.co_filename)
68 write(_indent, '%s:%d:%s():', module, frame.f_lineno, co.co_name)
69 _indent += ' '
70 return do_trace
71 elif event == 'return' or event == 'c_return':
72 if print_returns:
73 write(_indent, 'return %r', arg)
74 _indent = _indent[:-2]
75 return None
76 elif event == 'exception' or event == 'c_exception':
77 if arg:
78 write(_indent, 'Exception: %s:%d: %s (%s)', co.co_filename,
79 frame.f_lineno, arg[0].__name__, arg[1])
80 else:
81 write(_indent, 'Exception: (from C)')
82 return do_trace
83 else:
84 write(_indent, 'unknown event: %s', event)
85 return None
86
87 _tracing += 1
88 if _tracing == 1:
89 assert _indent == ''
90 sys.settrace(do_trace)
91
99
101 f = sys._getframe(1)
102 output = []
103 while f:
104 co = f.f_code
105 filename = co.co_filename
106 lineno = f.f_lineno
107 name = co.co_name
108 linecache.checkcache(filename)
109 line = linecache.getline(filename, lineno)
110
111 if f.f_locals:
112 for k, v in f.f_locals.items():
113 output.append(' %s = %r' % (k, v))
114 output.append(' Locals:')
115 if line:
116 output.append(' %s' % line.strip())
117 output.append(' File "%s", line %d, in %s' % (filename,lineno,name))
118 f = f.f_back
119 output.reverse()
120 for line in output:
121 print line
122