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
#!/usr/bin/env python
import inspect
import os
import sys
def get_script_dir(follow_symlinks=True):
if getattr(sys, 'frozen', False): # py2exe, PyInstaller, cx_Freeze
path = os.path.abspath(sys.executable)
else:
path = inspect.getabsfile(get_script_dir)
if follow_symlinks:
path = os.path.realpath(path)
return os.path.dirname(path)
print(get_script_dir())
It works on CPython, Jython, Pypy. It works if the script is executed using execfile()
(sys.argv[0]
and __file__
-based solutions would fail here). It works if the script is inside an executable zip file (/an egg). It works if the script is "imported" (PYTHONPATH=/path/to/library.zip python -mscript_to_run
) from a zip file; it returns the archive path in this case. It works if the script is compiled into a standalone executable (sys.frozen
). It works for symlinks (realpath
eliminates symbolic links). It works in an interactive interpreter; it returns the current working directory in this case.