how to get the caller's module name, file name , function name and line number?
2012-12-21 10:06
411 查看
在写一些底层模块的时候,特别是日志模块、底层服务等,需要记录调用者的一些信息,比如module name, file name, function name, line number 等,而不是记录我们所写的底层模块的相关信息。这个时候就需要用到python的inspect模块来完成相应的功能
以下代码仅作为示例:
需要注意的是:caller_frame_record = inspect.stack()[1],要得到caller_frame_record,需要根据实际的调用情况(比如函数嵌套情况等等)调整inspect.stack()的下标才能得到我们想要的frame_record
以下代码仅作为示例:
# -*- coding: utf-8 -*- ''' @summary: get caller's module name, file name, function name, line number .etc @author: JerryKwan ''' import inspect def report_error(error_msg = ''): # get caller stack frome # caller_frame = inspect.currentframe() caller_frame_record = inspect.stack()[1] # parse module name module = module = inspect.getmodule(caller_frame_record[0]) module_name = module.__name__ # print 'caller_frame_record is : ', caller_frame_record # parse file name, line number, function name .etc file_name = caller_frame_record[1] file_number = caller_frame_record[2] function_name = caller_frame_record[3] # resove caller_frame, parse who called the function? # parse frame info frame_info = inspect.getframeinfo(caller_frame_record[0]) print 'file name is: ', file_name print 'line number is : ', file_number print 'function name is : ', function_name print 'module_name = ', module_name print ' do other process......'
需要注意的是:caller_frame_record = inspect.stack()[1],要得到caller_frame_record,需要根据实际的调用情况(比如函数嵌套情况等等)调整inspect.stack()的下标才能得到我们想要的frame_record
相关文章推荐
- python+sikuli get file name and number
- C# 5.0 CallerMemberName CallerFilePath CallerLineNumber 在.NET4中的使用
- C# 5.0 CallerMemberName CallerFilePath CallerLineNumber获取调用方法名称,路径,行号
- unable to install breakpoint in ...(file name) due to miss line number attributes.
- 在 .NET 4.0 中使用 .NET 4.5 中新增的特性(CallerMemberNameAttribute/CallerFilePathAttribute/CallerLineNumberAttribute)
- 关于C# 5.0 CallerMemberName CallerFilePath CallerLineNumber 在.NET4中的使用介绍方法
- C# 5.0 CallerMemberName CallerFilePath CallerLineNumber 在.NET4中的使用
- FUNCTION line.count does not exist. Check the 'Function Name Parsing and Resolution' section in the
- linux driver: __FILE__, __FUNCTION__, __LINE__
- __FILE__,__LINE__,FUNCTION__实现代码跟踪调试(linux下c语言编程)
- 34.Linux-printk分析、使用__FILE__, __FUNCTION__, __LINE__ 调试
- 利用__FILE__, __LINE__, __FUNCTION__跟踪调试程序
- C语言中预定义符 __FILE__, __LINE__, __FUNCTION__, __DATE__, __TIME__ 的使用
- __FILE__,__LINE__,FUNCTION__实现代码跟踪调试
- GetCurrentDirectory and GetModuleFileName
- __FILE__,__LINE__,FUNCTION__实现代码跟踪调试(linux下c语言编程 )
- Get the file name and extension in Shell
- [PLSQL]Two small function utilities that could be used in dynamic SQL (sqlchar and correct_sql_name)
- FILE__,__LINE__,FUNCTION__实现代码跟踪调试(linux下c语言编程 )
- Removing the trailing file name and backslash from a path