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

前端 未结 13 2431
天命终不由人
天命终不由人 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

    You can't directly determine the location of the main script being executed. After all, sometimes the script didn't come from a file at all. For example, it could come from the interactive interpreter or dynamically generated code stored only in memory.

    However, you can reliably determine the location of a module, since modules are always loaded from a file. If you create a module with the following code and put it in the same directory as your main script, then the main script can import the module and use that to locate itself.

    some_path/module_locator.py:

    def we_are_frozen():
        # All of the modules are built-in to the interpreter, e.g., by py2exe
        return hasattr(sys, "frozen")
    
    def module_path():
        encoding = sys.getfilesystemencoding()
        if we_are_frozen():
            return os.path.dirname(unicode(sys.executable, encoding))
        return os.path.dirname(unicode(__file__, encoding))
    

    some_path/main.py:

    import module_locator
    my_path = module_locator.module_path()
    

    If you have several main scripts in different directories, you may need more than one copy of module_locator.

    Of course, if your main script is loaded by some other tool that doesn't let you import modules that are co-located with your script, then you're out of luck. In cases like that, the information you're after simply doesn't exist anywhere in your program. Your best bet would be to file a bug with the authors of the tool.

提交回复
热议问题