This article describes how to obtain the name of the currently running function using python, for more information about how to use php1.cn/wiki/1514.html "target =" _ blank "> python to obtain the instance code of the method using the name of the currently running function, refer to php1.cn/wiki/1514.html" target = "_ blank">
Python method for obtaining the name of the currently running function instance code
Abstract: In c/c ++, the source code name of the FUNCTION is obtained. the method of FUNCTION name and row number is very simple FILE. FUNCTION and LINE python do not have this syntax, but they can also be obtained through some method, here is an example. The exception information is used 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
The above describes how to use python to obtain the name of the currently running function. For more information, see other related articles in the first PHP community!