2013-08-23 97 views
0

我正在尋找一種方法來同時打印和執行一個類似的功能/方法我可以通過包裝一個功能。問題是我不能直接裝飾函數,因爲我調用的函數是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

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

非常感謝托馬斯,將會給一個嘗試 – chrise