【问题标题】:How to determine the callee details in a pythondecorator function?如何确定 pythondecorator 函数中的被调用者详细信息?
【发布时间】:2013-07-24 16:06:35
【问题描述】:

我的目标是在方法执行期间找到文件的名称。主要问题是我使用 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.py”文件并执行,因此我们得到的输出显示在“实际输出”中。

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

【问题讨论】:

    标签: python import filenames decorator instrumentation


    【解决方案1】:

    将您的 File_Name 分配更改为:

    File_Name = inspect.getfile(f)
    

    做你想做的事。
    inspect.getfile() 接受一个对象作为它的参数,f 代表被包装的函数。

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

    【讨论】:

      猜你喜欢
      • 2015-02-19
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      • 2012-05-21
      • 2019-01-06
      • 2018-11-04
      • 1970-01-01
      • 2020-11-04
      相关资源
      最近更新 更多