使用できますsys.settrace
:
# trace.py
import sys
def trace_function(frame, event, arg):
if event == "call": # Only report function calls
code_name = frame.f_code.co_name
code = frame.f_code
print "Function call: {0} @ {1}:{2}".format(code.co_name, code.co_filename, code.co_firstlineno)
print "Locals:", frame.f_locals
print
return trace_function # Continue tracing the new scope
def f0(arg):
print "In f0: ", arg
print "Done"
def f1(arg):
print "In f1: ", arg
f0(arg)
def f2(arg):
print "In f2: ", arg
f1(arg)
sys.settrace(trace_function)
f2("The arg string")
次の出力が得られます。
$ python trace.py:
Function call: f2 @ trace.py:23
Locals: {'arg': 'The arg string'}
In f2: The arg string
Function call: f1 @ trace.py:19
Locals: {'arg': 'The arg string'}
In f1: The arg string
Function call: f0 @ trace.py:15
Locals: {'arg': 'The arg string'}
In f0: The arg string
Done
Function call: _remove @ /Users/thomas/.virtualenvs/ec2vpn/lib/python2.7/_weakrefset.py:38
Locals: {'item': <weakref at 0x106743158; dead>, 'selfref': <weakref at 0x1067956d8; to 'WeakSet' at 0x1067949d0>}
Function call: _remove @ /Users/thomas/.virtualenvs/ec2vpn/lib/python2.7/_weakrefset.py:38
Locals: {'item': <weakref at 0x1067430a8; dead>, 'selfref': <weakref at 0x106743050; to 'WeakSet' at 0x106744e90>}