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

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.