How do you properly determine the current script directory in Python?

后端 未结 12 1815
情深已故
情深已故 2020-11-22 02:30

I would like to see what is the best way to determine the current script directory in Python.

I discovered that, due to the many ways of calling Python code, it is ha

12条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 02:49

    For .py scripts as well as interactive usage:

    I frequently use the directory of my scripts (for accessing files stored along side them), but I also frequently run these scripts in an interactive shell for debugging purposes. I define __dirpath__ as:

    • When running or importing a .py file, the file's base directory. This is always the correct path.
    • When running an .ipyn notebook, the current working directory. This is always the correct path, since Jupyter sets the working directory as the .ipynb base directory.
    • When running in a REPL, the current working directory. Hmm, what is the actual "correct path" when the code is detached from a file? Rather, make it your responsibility to change into the "correct path" before invoking the REPL.

    Python 3.4 (and above):

    from pathlib import Path
    __dirpath__ = Path(globals().get("__file__", "./_")).absolute().parent
    

    Python 2 (and above):

    import os
    __dirpath__ = os.path.dirname(os.path.abspath(globals().get("__file__", "./_")))
    

    Explanation:

    • globals() returns all the global variables as a dictionary.
    • .get("__file__", "./_") returns the value from the key "__file__" if it exists in globals(), otherwise it returns the provided default value "./_".
    • The rest of the code just expands __file__ (or "./_") into an absolute filepath, and then returns the filepath's base directory.

提交回复
热议问题