python笔记_查看函数调用栈的一个小技巧

一、背景

最近在看一个开源框架的源码,涉及到的内容非常杂乱,有的函数不知道是在什么时候被谁给调用了?调用的时候传入了什么参数?为了解决这个问题,写了一个小的装饰器。

二、实现

这个装饰器函数主要参考了logging模块中的findCaller,源码如下:

 1 def findcaller(func):
 2     def wrapper(*args,**kwargs):
 3         import sys
 4         f=sys._getframe()
 5         filename=f.f_back.f_code.co_filename
 6         lineno=f.f_back.f_lineno
 7         print '######################################'
 8         print 'caller filename is ',filename
 9         print 'caller lineno is',lineno
10         print 'the passed args is',args,kwargs
11         print '######################################'
12         func(*args,**kwargs)
13     return wrapper

只要加上这个装饰器,就能在调用函数前看到这个函数被哪个文件中的第几行调用,并且传入的参数是什么。例子如下:

 1 #caller.py
 2 from class_A import A
 3 a1=A()
 4 a2=A(1)
 5 a3=A(2)
 6 a2.func(3)
 7 
 8 #class_A.py
 9 class A(object):
10     def __init__(self,num=0):
11         print num
12     @findcaller
13     def func(self,num=None):
14         print num
15 
16 #执行caller,得到结果如下:
17 ######################################
18 caller filename is  caller.py
19 caller lineno is 5
20 the passed args is (<class_A.A object at 0xb7200a4c>, 3) {}
21 ######################################

可以看到是caller.py中的第5行a2.func(3)调用到了func函数,传入参数是3.

posted on 2017-06-14 10:46  我的MrFiona博客  阅读(1725)  评论(0编辑  收藏  举报

导航