调试外部函数的包装器

时间:2013-08-23 14:35:44

标签: python decorator jython

我正在寻找一种方法来同时打印和执行一个函数/方法,就像我可以通过包装函数一样。问题是我无法直接修饰函数,因为我调用的函数是jython模块的一部分。 所以我有一些事情

from jythonModule import fun, obj

fun(a,b,c)
o = obj
o.method(e,f)

我正在寻找运行和打印代码 所以它会显示

乐趣(A,B,C) o.method(E,F)

并执行这些命令。 如果没有访问jython模块,我怎么能这样做? 干杯

1 个答案:

答案 0 :(得分:1)

您可以使用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>}