This article mainly introduces pythonRelevant information about the method instance code for obtaining the current running function name, required Friends can refer to the example code of
python method to get the name of the currently running function
Abstract: How to get the source code name, function name and line number of the function in c/c++ It is very simple. FILE, FUNCTION and LINE python do not have this syntax, but it can also be obtained through a certain method. Here is an example, using exception information to obtain [possible loss of performance]
Directly paste the code [please refer to python Core Programming 4.4]
#Get the function name where the function is called (called)
#author:peterguo@vip.qq.com def get_func_name(): import sys try: raise Exception except: exc_info = sys.exc_info() #返回 异常类型,异常,traceback对象 traceObj = exc_info[2] #traceback对象 frameObj = traceObj.tb_frame #获取frame对象,即本函数的frame信息 #print frameObj.f_code.co_name,frameObj.f_lineno #请在使用的时候将其注释 Upframe = frameObj.f_back #获取该代码段的frame信息,即调用该函数的函数frame #print Upframe.f_code.co_name, Upframe.f_lineno #请在使用的时候将其注释 return (Upframe.f_code.co_name, Upframe.f_lineno)[0] #获取名称 调用方法
Get the file name path, function name, line 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)
#测试代码 def test1(): print getCurRunPosInfo() def test2(): print get_func_name() 输出: >>('demo.py', 'test1', 44) >>test2
The above is the detailed content of How to use python to get the name of the currently running function. For more information, please follow other related articles on the PHP Chinese website!