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

來源:互聯網
上載者:User

在寫一些底層模組的時候,特別是日誌模組、底層服務等,需要記錄調用者的一些資訊,比如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 inspectdef 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.