Python method to obtain the name of the currently running function instance code, python Function
Python method for obtaining the name of the currently running function instance code
Abstract: To obtain the source code name of a FUNCTION in c/c ++, the FUNCTION name and row number method is very simple: _ FILE __,__ FUNCTION _ and _ LINE _ python do not have this syntax, however, you can also obtain it in some way. Here we provide an example to use the exception information to obtain [performance may be compromised]
Directly paste code [Refer to python core programming 4.4]
# Obtain the name of the function that calls the function (called)
# Author: peterguo@vip.qq.com def get_func_name (): import sys try: raise Exception failed T: exc_info = sys. exc_info () # Return exception type, exception, traceback object traceObj = exc_info [2] # traceback object frameObj = traceObj. tb_frame # Get the frame object, that is, the frame information of this function # print frameObj. f_code.co_name, frameObj. f_lineno # Note Upframe = frameObj when using it. f_back # Get the frame information of the code segment, that is, the function frame that calls the function # print Upframe. f_code.co_name, Upframe. f_lineno # comment return (Upframe. f_code.co_name, Upframe. f_lineno) [0] # obtain the name call Method
Obtain the file name path, function name, and row number.
------------------------------------------------------------------------------
def getCurRunPosInfo(): import sys try: raise Exception except: exc_info = sys.exc_info() traceObj = exc_info[2] frameObj = traceObj.tb_frame #print frameObj.f_code.co_name,frameObj.f_lineno Upframe = frameObj.f_back #print Upframe.f_code.co_name, Upframe.f_lineno return (Upframe.f_code.co_filename, Upframe.f_code.co_name, Upframe.f_lineno)
# Test code def test1 (): print getCurRunPosInfo () def test2 (): print get_func_name () Output: >>( 'demo. py', 'test1', 44)> test2
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!