How to get the file path of a module from a function executed but not declared in it?

后端 未结 3 1876
夕颜
夕颜 2020-12-18 16:29

If I want the path of the current module, I\'ll use __file__.

Now let\'s say I want a function to return that. I can\'t do:

def get_path         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-18 17:08

    I found a way to do it with the inspect module. I'm ok with this solution, but if somebody find a way to do it without dumping the whole stacktrace, it would be cleaner and I would accept his answer gratefully:

    def get_path():
        frame, filename, line_number, function_name, lines, index =\
            inspect.getouterframes(inspect.currentframe())[1]
        return filename
    

提交回复
热议问题