When writing some underlying modules, especially the Log Module and underlying services, You need to record Caller information, such as module name, file name, function name, line number, etc, instead of recording the information of the underlying modules we have written. At this time, you need to use the python inspect module to complete the corresponding functions.
BelowCodeFor example only:
# -*-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 ...... '
Note: caller_frame_record = inspect. Stack () [1]To get caller_frame_record, you need to adjust the subscript of inspect. Stack () based on the actual call situation (such as the nested function) to get the expected frame_record.