Python:如何获取我所在函数的*完整*名称

标签 python traceback inspect

有没有办法让下面的代码:

import traceback

def log(message):
    print "%s: %s" %(traceback.extract_stack()[0:-1][-1][2], message)

def f1():
    log("hello")

class cls(object):
    def f1(self):
        log("hi there")

f1()
mycls = cls()
mycls.f1()

显示:

f1: hello
cls.f1: hi there

代替:

f1: hello
f1: hi there

?

我尝试使用模块“检查”但没有成功...

朱利安

EDIT:

The point here is for 'log' function to be able to retrieve its caller name on its own (using traceback, inspect, or any mean necessary).

I do not want to pass the class name, or anything else than 'message' to the 'log' function.

最佳答案

所以我终于想出了这个方法:

#!/usr/bin/env python3

def log(message):
    import inspect
    import gc
    code = inspect.currentframe().f_back.f_code
    func = [obj for  obj in  gc.get_referrers(code) if inspect.isfunction(obj)][0]
    print(func.__qualname__, message)

它需要 python3 以便可以使用 __qualname__。

关于Python:如何获取我所在函数的*完整*名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45470346/

相关文章:

Python:获取当前行运行时间

python - 在应用程序运行之间将位置保存在列表中的标准方法是什么?

python - Pandas 时间序列重新采样,分箱似乎关闭

python - 尝试使用 Opencv 和 Flask 显示多个流

python - 如何在 Visual Studio Code 中将我的 python 文件导入到另一个文件中

python - 文件 "<string>"回溯和行预览

python - 检查python类属性

python - 查看在 Python 装饰器中从哪一行调用函数

python - 如何通过排除对 Numpy 数组进行子集化

python - 使用 pandas 查找数字列中的数据变化