, sys.settrace:
import sys
class SetTrace(object):
def __init__(self, func):
self.func = func
def __enter__(self):
sys.settrace(self.func)
return self
def __exit__(self, ext_type, exc_value, traceback):
sys.settrace(None)
def monitor(frame, event, arg):
if event == "line":
print('hello')
return monitor
def foo():
print 'bar'
print 'barbar'
print 'barbarbar'
with SetTrace(monitor):
foo()
hello
bar
hello
barbar
hello
barbarbar
hello
monitor foo, frame.f_locals frame.f_globals.
post , sys.settrace .
foo monitor:
- foo, foo , . monitor , foo .
, foo, monitor. , . SetTrace.__exit__, , foo .
import sys
class Sentinel(Exception): pass
class SetTrace(object):
"""
with SetTrace(monitor):
...
"""
def __init__(self, func):
self.func = func
def __enter__(self):
sys.settrace(self.func)
return self
def __exit__(self, ext_type, exc_value, traceback):
sys.settrace(None)
return isinstance(exc_value, Sentinel)
def monitor(frame, event, arg):
if event == "line":
l = frame.f_locals
x = l.get('x', 0)
print('x = {}'.format(x))
if x > 3:
raise Sentinel()
return monitor
def foo():
x = 0
while True:
print 'bar'
x += 1
with SetTrace(monitor):
foo()