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

前端 未结 13 2451
天命终不由人
天命终不由人 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条回答
  •  猫巷女王i
    2020-11-22 17:32

    See my answer to the question Importing modules from parent folder for related information, including why my answer doesn't use the unreliable __file__ variable. This simple solution should be cross-compatible with different operating systems as the modules os and inspect come as part of Python.

    First, you need to import parts of the inspect and os modules.

    from inspect import getsourcefile
    from os.path import abspath
    

    Next, use the following line anywhere else it's needed in your Python code:

    abspath(getsourcefile(lambda:0))
    

    How it works:

    From the built-in module os (description below), the abspath tool is imported.

    OS routines for Mac, NT, or Posix depending on what system we're on.

    Then getsourcefile (description below) is imported from the built-in module inspect.

    Get useful information from live Python objects.

    • abspath(path) returns the absolute/full version of a file path
    • getsourcefile(lambda:0) somehow gets the internal source file of the lambda function object, so returns '' in the Python shell or returns the file path of the Python code currently being executed.

    Using abspath on the result of getsourcefile(lambda:0) should make sure that the file path generated is the full file path of the Python file.
    This explained solution was originally based on code from the answer at How do I get the path of the current executed file in Python?.

提交回复
热议问题