How do I get the name of a function or method from within a Python function or method?

后端 未结 5 1371
一向
一向 2020-11-29 23:06

I feel like I should know this, but I haven\'t been able to figure it out...

I want to get the name of a method--which happens to be an integration test--from inside

5条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 23:45

    # file "foo.py" 
    import sys
    import os
    
    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 )
    
    def testit():
       print "Here in %s, file %s, line %s" % ( FUNC(), FILE(), LINE() )
       print "WHERE says '%s'" % WHERE()
    
    testit()
    

    Output:

    $ python foo.py
    Here in testit, file foo.py, line 17
    WHERE says 'foo.py/18 testit()'
    

    Use "back = 1" to find info regarding two levels back down the stack, etc.

提交回复
热议问题