I would like to see what is best way to determine current script directory in python?
I discovered that two to the many ways of calling python code, it is hard to find a good solution.
Here are some problems:
__file__
is not defined if the script is executed withexec
,execfile
__module__
is defined only in modules
Use cases:
./myfile.py
python myfile.py
./somedir/myfile.py
python somedir/myfile.py
execfile('myfile.py')
(from another script, that can be located in another directory and that can have another current directory.
I know that there is no perfect solution, because in some cases but I'm looking for the best approach that solved most of the cases.
The most used approach is os.path.dirname(os.path.abspath(__file__))
but this really doesn't work if you execute the script from another one with exec()
.
Warning
Any solution that uses current directory will fail, this can be different based on the way the script is called or it can be changed inside the running script.
This gives you the directory of the script at the top of the stack (i.e. the one being executed - not Python's, which is usually the first executed, returning
C:/
)