如何在pythondecorator函数中确定被调用者的详细信息?

时间:2013-07-24 16:06:35

标签: python import filenames decorator instrumentation

我的目标是在方法执行期间找到文件的名称。主要问题是我使用python decorator来转换函数。此装饰器位于单独的文件中,并导入到当前文件中。我已经使用下面的一个小方案解释了这个问题:

代码情景

#Normal.py

import decorator

 class A:
    @entryExit
    def move(self):
        print "hello"    

a=A()
a.move()

#decorator.py
import sys
import inspect
def entryExit(f):
    def new_f(self,*args, **kwargs):
        File_Name=inspect.getfile(inspect.currentframe()).split("\\")
        print 'Entry',f.__name__,self.__class__.__name__,File_Name[-1]
        f(self,*args)        
        print 'Exit',f.__name__,self.__class__.__name__,File_Name[-1]        
    return new_f 

Actual Output:
Entry move A decorator.py
hello
Exit move A decorator.py

Needed Output:
Entry move A Normal.py
hello
Exit move A Normal.py

我可以从“实际输出”中了解装饰器是否已导入,每次调用方法时,它都会转到“decorator.py”文件并执行,因此我们得到“实际输出”中显示的输出。

无论如何,我可以获得所需的输出但仍然在导入Decorator.py文件的同时?

1 个答案:

答案 0 :(得分:2)

File_Name作业更改为:

File_Name = inspect.getfile(f)

做你想做的事 inspect.getfile()以对象作为参数,f表示包装函数。

来源:http://docs.python.org/2/library/inspect.html#inspect.getfile

相关问题