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
exec('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 is really doesn't work if you execute the script from another one with exec()
.