Get parent function

后端 未结 4 443
不思量自难忘°
不思量自难忘° 2021-01-02 00:39

Is there a way to find what function called the current function? So for example:

def first():
    second()

def second():
    # print out here what function         


        
4条回答
  •  情话喂你
    2021-01-02 01:03

    These work well for quickly adding minimal where-am-I debugging aids when you don't want to import yet another module. (CPython only, for debugging only.)

    def LINE( back = 0 ):
        return sys._getframe( back + 1 ).f_lineno
    def FILE( back = 0 ):
        return sys._getframe( back + 1 ).f_code.co_filename
    def FUNC( back = 0):
        return sys._getframe( back + 1 ).f_code.co_name
    def WHERE( back = 0 ):
        frame = sys._getframe( back + 1 )
        return "%s/%s %s()" % ( os.path.basename( frame.f_code.co_filename ),
                                frame.f_lineno, frame.f_code.co_name )
    

    Example:

    import sys, os # these you almost always have...
    
    def WHERE( back = 0 ):
        frame = sys._getframe( back + 1 )
        return "%s/%s %s()" % ( os.path.basename( frame.f_code.co_filename ),
                            frame.f_lineno, frame.f_code.co_name )
    
    def first():
        second()
    
    def second():
        print WHERE()
        print WHERE(1)
    
    first()
    

    Output:

    $ python fs.py
    fs.py/12 second()
    fs.py/9 first()
    

提交回复
热议问题