python gets the method instance code that currently runs the function name

  • 2020-05-30 20:26:29
  • OfStack

python gets the method instance code for the currently running function name

Abstract: in c/c++ to get the source name of the function, the method of getting the function name and the line number is very simple, s 6en__, s 7en__ and s 8en__ python has no such syntax, but can be obtained by some method. Here is an example.

Direct coding [see python core programming 4.4]

Gets the name of the function where the function is called


#author:peterguo@vip.qq.com 
def get_func_name():
  import sys
  try:
    raise Exception
  except:
    exc_info = sys.exc_info()                             # return   Exception type, exception, traceback object 
    traceObj = exc_info[2]                               #traceback object 
    frameObj = traceObj.tb_frame                         # To obtain frame Object of this function frame information 
    #print frameObj.f_code.co_name,frameObj.f_lineno         # Please comment it out when you use it 
    Upframe = frameObj.f_back                           # Gets the code snippet frame Information, the function that calls the function frame
    #print Upframe.f_code.co_name, Upframe.f_lineno          # Please comment it out when you use it 
    return (Upframe.f_code.co_name, Upframe.f_lineno)[0]      # Get the name 
 A method is called 

Get 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)

# The test code 
def test1():
  print getCurRunPosInfo()

def test2():
  print get_func_name()
  
 Output: 
>>('demo.py', 'test1', 44)
>>test2

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: