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

如何在pythondecorator函数中确定被调用方的详细信息?,python,import,filenames,decorator,instrumentation,Python,Import,Filenames,Decorator,Instrumentation,我的目标是在方法执行期间查找文件名。主要问题是我使用python装饰器来转换函数。此装饰器位于单独的文件中,正在导入到当前文件中。我已经用下面的一个小场景解释了这个问题: 代码场景 #Normal.py import decorator class A: @entryExit def move(self): print "hello" a=A() a.move() #decorator.py import sys import inspect d

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

代码场景

#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是导入的,每次调用一个方法时,它都会进入“decorator.py”文件并执行,因此我们得到的输出显示在“实际输出”中


是否仍然可以在导入Decorator.py文件的同时获得所需的输出?

将您的
文件名更改为:

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

资料来源: