【问题标题】:How can I get the file name of the function that is passed to my decorator in python?如何在 python 中获取传递给我的装饰器的函数的文件名?
【发布时间】:2012-08-22 14:04:14
【问题描述】:

我想获取正在修饰的函数的原始文件/脚本名等。我怎样才能做到这一点?

   def decorate(fn):
        def wrapped():
            return "scriptname: " + fn.scriptname?  
        return wrapped

我尝试使用fn.__code__,但这给了我更多我需要的东西。我可以解析该字符串以获取函数名称,但想知道是否有更优雅的方法来做到这一点

【问题讨论】:

  • 在旁注中依赖生产代码中的这种东西通常是个坏主意

标签: python metaclass python-datamodel


【解决方案1】:

试试这个:

return "filename: " + fn.func_code.co_filename

【讨论】:

  • 请务必注意,这依赖于实现细节,并且可能无法在 CPython 之外运行。使用inspect 是实际正确的答案,但是当单行更容易时,为什么要正确,对吧? :|
  • @Matthew Trevor 正确,inspect 更好,我不知道这一点,并从 gnibbler 的回答中了解到。
【解决方案2】:
import inspect
inspect.getfile(fn)

这不适用于builtin functions,但您必须退回到inspect.getmodule。

【讨论】:

    猜你喜欢
    • 2019-11-20
    • 2018-08-01
    • 2016-01-30
    • 2010-12-30
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    相关资源
    最近更新 更多