Michal Kwiatkowski
3/15/2010 4:57:00 PM
Hi,
I'm trying to write code that will trace arguments and return values
of all function calls. Using sys.settrace with 'call' and 'return'
events works great for Python functions, but now I want to extend that
to C functions as well. Using sys.setprofile instead in theory gives
me what I need ('c_call' and 'c_return'), but I'm stuck on getting
actual arguments and return values.
A snippet of code is worth a thousand words, so here it is:
import inspect
import sys
def trace(frame, event, arg):
if event == 'call':
print "CALL", frame.f_code.co_name, "arguments:",
inspect.getargvalues(frame)
elif event == 'return':
print "RETURN", frame.f_code.co_name, "return value:", arg
elif event == 'c_call':
print "C_CALL", arg.__name__, "???"
elif event == 'c_return':
print "C_RETURN", arg.__name__, "???"
def func(x):
return x+1
sys.setprofile(trace)
func(1) # Python function
repr(2) # C function
sys.setprofile(None)
For a 'c_call' event the trace function is called *before* the call,
so frame is still in the context of the caller. 'c_return' event is
invoked *after* the function has returned, so I don't get the return
value here either. That's why I can't use inspect.getargvalues in
those cases. Is there any other way I could get arguments and a return
value of a C function call?
Cheers,
mk