程序中的日志打印,或者音讯上传,比方kafka音讯等等。常常上传的音讯中须要上传堆栈信息中的文件名、行号、下层调用者等具体用于定位的音讯。Python提供了以下两种办法:
sys._getframe
, 根底办法inspect.currentframe
, 举荐办法,提供除了sys._getframe
办法之外更多的frame相干的办法
<!--more-->
具体应用如下
应用sys._getframe
公有办法
具体应用办法如下:
import osimport sysdef get_cur_info(): """ 获取调用时的文件名,行号,下层调用者的名称 :return: 文件名,行号,下层调用者名称 """ try: current_frame = sys._getframe(2) return os.path.basename(current_frame.f_code.co_filename), current_frame.f_lineno, current_frame.f_code.co_name except ValueError: return 'unknown', 0, 'unknown'
具体的函数输入后果演示能够参见上面的inspect模块后果
应用inspect
模块(举荐)
相比于sys的内置公有办法,更举荐inspect模块。inspect模块的具体应用办法如下
import osimport inspectdef get_cur_info(): try: current_frame = inspect.currentframe(2) return os.path.basename(current_frame.f_code.co_filename), current_frame.f_lineno, current_frame.f_code.co_name except ValueError: return 'unknown', 0, 'unknown'def produce(): return get_cur_info()def business(): return produce()if __name__ == '__main__': print(get_cur_info()) # 输入 ('unknown', 0, 'unknown') print(produce()) # 输入 ('a.py', 22, '<module>') print(business()) # 输入 ('a.py', 16, 'business')
次要依赖inspect.currentframe办法,对于inspect.currentframe办法的应用见帮忙文档
>>> help(inspect.currentframe)Help on built-in function _getframe in module sys:_getframe(...) _getframe([depth]) -> frameobject Return a frame object from the call stack. If optional integer depth is given, return the frame object that many calls below the top of the stack. If that is deeper than the call stack, ValueError is raised. The default for depth is zero, returning the frame at the top of the call stack. This function should be used for internal and specialized purposes only.
从调用堆栈返回一个帧对象。深度为整数,默认为0,返回调用堆栈顶部的帧。如果指定深度比调用堆栈深,会抛出ValueError异样。该性能应该只用于外部和业余目标。
inspect.currentframe办法的实现见内置库inspect.py
if hasattr(sys, '_getframe'): currentframe = sys._getframeelse: currentframe = lambda _=None: None
所以实质上inspect.currentframe办法等同于sys._getframe办法
currentframe = lambda _=None: None 等同于 currentframe = lambda _: None ,即lambda函数接管一个参数,返回None
参考:
- Python frame hack
- StackOverFlow-In Python, how do I obtain the current frame?
记得帮我点赞哦!
精心整顿了计算机各个方向的从入门、进阶、实战的视频课程和电子书,依照目录正当分类,总能找到你须要的学习材料,还在等什么?快去关注下载吧!!!
朝思暮想,必有回响,小伙伴们帮我点个赞吧,非常感谢。
我是职场亮哥,YY高级软件工程师、四年工作教训,回绝咸鱼争当龙头的斜杠程序员。听我说,提高多,程序人生一把梭
如果有幸能帮到你,请帮我点个【赞】,给个关注,如果能顺带评论给个激励,将不胜感激。
职场亮哥文章列表:更多文章
自己所有文章、答复都与版权保护平台有单干,著作权归职场亮哥所有,未经受权,转载必究!