2009-05-22 120 views
74

如果你有2种功能,如:在Python的另一个函数中获取调用者函数名称?

def A 
def B 

和A调用B,你可以得到谁在呼叫B B内,如:

def A() : 
    B() 

def B() : 
    this.caller.name 
+1

您有可用的来源。你为什么需要这样的事情? – 2009-05-23 01:36:50

+12

因为我正在调试第三方应用程序的python解释器中没有真正的调试器的代码。 – 2009-05-25 17:31:32

+3

[Python:如何获得被调用方法中的调用者方法名称?]的可能重复(http://stackoverflow.com/questions/2654113/python-how-to-get-the-callers-method-name-in - 所谓的方法) – bernie 2012-03-28 15:05:10

回答

103

可以使用inspect模块获取调用叠加。它返回一个帧记录列表。每条记录中的第三个元素是来电者姓名。你想要的是:

>>> import inspect 
>>> def f(): 
...  print inspect.stack()[1][3] 
... 
>>> def g(): 
...  f() 
... 
>>> g() 
g 

当然,在尝试访问特定索引之前检查是否存在足够的帧记录是一个好主意。

+6

python 3.4至少这不起作用,他们已经改变了元组的顺序。现在正在使用一个命名的元组,因此最好使用inspect.stack()[1] .filename – timeyyy 2016-03-23 18:53:45

8

就像下面的例子:

>>> def foo(): 
... global x 
... x = sys._getframe(1) 
... 
>>> def y(): foo() 
... 
>>> y() 
>>> x.f_code.co_name 
'y' 
>>> 

重要提示:因为它是从_getframe方法名(嘿,它以下划线开头)明显的,它不是一个API方法之一应该是不假思索地依靠。

2

您可以将用户的日志模块,并指定%(文件名)■在BaseConfig()选项

import logging 
logging.basicConfig(filename='/tmp/test.log', level=logging.DEBUG, format='%(asctime)s | %(levelname)s | %(funcName)s |%(message)s') 

def A(): 
    logging.info('info') 
10

有两种方法,使用sysinspect模块:

  • inspect.stack()[1][3]

stack()形式的可读性和依赖于实现,因为它要求sys._getframe(),看到inspect.py提取物:

def stack(context=1): 
    """Return a list of records for the stack above the caller's frame.""" 
    return getouterframes(sys._getframe(1), context) 
4

这对我的作品! :D

>>> def a(): 
...  import sys 
...  print sys._getframe(1).f_code.co_name 
... 
>>> def b(): 
...  a() 
... 
... 
>>> b() 
b 
>>> 
相关问题