在Python的另一个函数里获取调用者函数的名字?
如果你有2个function,如:
def A def B 
和A打电话B,你可以得到谁打电话B在B内,如:
 def A () : B () def B () : this.caller.name 
	
您可以使用inspect模块来获取调用堆栈。 它返回一个帧logging列表。 每个logging中的第三个元素是来电者姓名。 你想要的是这样的:
 >>> import inspect >>> def f(): ... print inspect.stack()[1][3] ... >>> def g(): ... f() ... >>> g() g 
当然,在尝试访问特定索引之前检查是否存在足够的帧logging是一个好主意。
 有两种方法,使用sys和inspect模块: 
-  
sys._getframe(1).f_code.co_name -  
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) 
  sys._getframe(1).f_code.co_name就像下面的例子: 
>>> def foo(): ...全球x ... x = sys._getframe(1) ... >>> def y():foo() ... >>> y() >>> x.f_code.co_name 'Y' >>>
这对我有用! :d
 >>> def a(): ... import sys ... print sys._getframe(1).f_code.co_name ... >>> def b(): ... a() ... ... >>> b() b >>> 
您可以使用日志logging模块并在BaseConfig()中指定%(filename)s选项
 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')