Python interceptor package
Dominic
nomail at nospam.no
Thu Jun 17 06:09:36 EDT 2004
I've attached two source fragments which
I had used to wrap/intercept objects.
"weave" can be used to plug between an
object (like a proxy).
It temporarily modifies "self" so that even
method calls inside an object can
be trapped from the outside.
(Sorry could not find a use
case and I'm too lazy to write one
right now.)
The "trace_all" just wraps functions
inside a module.
Well, it probably won't help you much.
But who knows. Maybe you come up with an
idea :-)
Ciao,
Dominic
=============================================
=============================================
def weave(delegate, into, for_):
class X(object):
def __getattribute__(self, key):
def wrapper(*args,**kargs):
class XX(object):
def __getattribute__(self, key):
if getattr(delegate, key, None):
return getattr(delegate, key)
else:
return getattr(into, key)
def __setattr__(self, key, value):
if getattr(delegate, key, None):
setattr(delegate, key, value)
else:
setattr(into, key, value)
return getattr(into.__class__,key).im_func(XX(), *args, **kargs)
if key in for_: # catch attribute
if getattr(into, key, None): #
return getattr(into, key) #
else:
return wrapper # catch method
elif getattr(delegate, key, None):
return getattr(delegate, key)
else:
return getattr(into, key)
def __setattr__(self, key, value):
print key, value
setattr(into, key, value)
return X()
=============================================
=============================================
# wrap stuff here
from trace import trace_all
trace_all('fork', locals())
---------------------------------
@file ../prototype/trace.py
indent = 0
hash = {}
def trace(name, f):
def wrapper(*args,**kargs):
"""wrapped"""
global indent, hash
print " "*indent + "%s:%s(%s,%s)" % (name, f.func_name, args, kargs)
indent = indent + 1
result = f(*args,**kargs)
indent = indent - 1
hash[name] = hash.get(name,{})
hash[name][f.func_name] = hash[name].get(f.func_name,0) + 1
return result
return wrapper
from types import FunctionType
def trace_all(name, d):
for k,v in d.items():
if type(v) == FunctionType and k != 'trace_all' and v.func_doc !=
'wrapped':
#print "Wrap %s" % k
d[k] = trace(name, v)
More information about the Python-list
mailing list