How do I get the path of the current executed file in Python?

前端 未结 13 2361
天命终不由人
天命终不由人 2020-11-22 17:06

This may seem like a newbie question, but it is not. Some common approaches don\'t work in all cases:

sys.argv[0]

This means using path = os.path.abs

13条回答
  •  情深已故
    2020-11-22 17:38

    I was running into a similar problem, and I think this might solve the problem:

    def module_path(local_function):
       ''' returns the module path without the use of __file__.  Requires a function defined
       locally in the module.
       from http://stackoverflow.com/questions/729583/getting-file-path-of-imported-module'''
       return os.path.abspath(inspect.getsourcefile(local_function))
    

    It works for regular scripts and in idle. All I can say is try it out for others!

    My typical usage:

    from toolbox import module_path
    def main():
       pass # Do stuff
    
    global __modpath__
    __modpath__ = module_path(main)
    

    Now I use __modpath__ instead of __file__.

提交回复
热议问题