程序中打印日志,或者消息上传,比如kafka消息等。经常上传的消息需要上传文件名,行号,上层-levelcaller和其他用于在堆栈信息中定位的特定消息。Python提供了以下两个方法:sys._getframe,基本方法inspect.currentframe,推荐方法,除了sys._getframe方法外,还提供了更多frame相关的方法。具体用法如下_getframe私有方法的具体使用如下:importosimportsysdefget_cur_info():"""调用时获取上层调用者的文件名、行号、名称:return:文件名、行号、以及上层调用者的名称“””try:current_frame=sys._getframe(2)returnos.path.basename(current_frame.f_code.co_filename),current_frame.f_lineno,current_frame.f_code.co_nameexceptValueError:return'unknown',0,'unknown'具体函数输出结果演示请参考下面inspect模块的结果。使用inspect模块(推荐)相比sys自带的私有方法,更推荐使用inspect模块。inspect模块的具体用法如下importosimportinspectdefget_cur_info():try:current_frame=inspect.currentframe(2)returnos.path.basename(current_frame.f_code.co_filename),current_frame.f_lineno,current_frame.f_code.co_name除了:ValueErrorreturn'unknown',0,'unknown'defproduce():returnget_cur_info()defbusiness():returnproduce()if__name__=='__main__':print(get_cur_info())#output('unknown',0,'unknown')print(produce())#output('a.py',22,'
