我正在寻找一种方法来同时打印和执行一个函数/方法,就像我可以通过包装一个函数来做的那样。问题是我不能直接装饰函数,因为我调用的函数是 jython 模块的一部分。所以我有一些类似的东西
from jythonModule import fun, obj
fun(a,b,c)
o = obj
o.method(e,f)
我正在寻找运行和打印代码所以它会显示
fun(a,b,c) o.method(e,f)
并执行这些命令。如果无法访问 jython 模块,我怎么能做到这一点?干杯
您可以使用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>}