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

后端 未结 6 1508
别那么骄傲
别那么骄傲 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:15

    This can be done with the inspect module, specifically inspect.stack:

    import inspect
    import os.path
    
    def get_caller_filepath():
        # get the caller's stack frame and extract its file path
        frame_info = inspect.stack()[1]
        filepath = frame_info[1]  # in python 3.5+, you can use frame_info.filename
        del frame_info  # drop the reference to the stack frame to avoid reference cycles
    
        # make the path absolute (optional)
        filepath = os.path.abspath(filepath)
        return filepath
    

    Demonstration:

    import b
    
    print(b.get_caller_filepath())
    # output: D:\Users\Aran-Fey\a.py
    

提交回复
热议问题