how to get the caller's filename, method name in python

后端 未结 6 1524
别那么骄傲
别那么骄傲 2020-12-05 13:46

for example, a.boo method calls b.foo method. In b.foo method, how can I get a\'s file name (I don\'t want to pass __file__

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-05 14:28

    Python 3.5+

    Caller's Filename

    To retrieve just the caller's filename with no path at the beginning or extension at the end, use:

    import inspect
    import os
    
    # First get the full filename (including path and file extension)
    caller_frame = inspect.stack()[1]
    caller_filename = caller_frame.filename
    
    # Now get rid of the directory and extension
    filename = os.path.splitext(os.path.basename(caller_filename))[0]
    
    # Output
    print(f"Caller Filename: {caller_filename}")
    print(f"Filename: {filename}")
    

    Sources:

    • inspect.stack()
    • os.path.basename()
    • os.path.splitext()

提交回复
热议问题