how to get the caller's module name, file name , function name and line number?

在写一些底层模块的时候,特别是日志模块、底层服务等,需要记录调用者的一些信息,比如module name, file name, function name, line number 等,而不是记录我们所写的底层模块的相关信息。这个时候就需要用到python的inspect模块来完成相应的功能
以下代码仅作为示例:

# -*- 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

原文地址:https://www.cnblogs.com/Jerryshome/p/2827492.html