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 hard to find a good solution.
Here are some problems:
__file__
is not defined if the script is executed with exec
, execfile
__module__
is defined only in modulesUse 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, but I'm looking for the best approach that solves 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()
.
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.
pwd can be used to find the current working directory, and dirname to find the directory of a particular file (command that was run, is $0 , so dirname $0 should give you the directory of the current script).
getcwd() method is used for getting the Current Working Directory in Python. The absolute path to the current working directory is returned in a string by this function of the Python OS module.
PowerShell Get Current Directory of Script File To get current directory of script file or running script, use $PSScriptRoot automatic variable.
Note: The current working directory is the folder in which the Python script is operating. Parameters: path: A complete path of the directory to be changed to the new directory path.
os.path.dirname(os.path.abspath(__file__))
is indeed the best you're going to get.
It's unusual to be executing a script with exec
/execfile
; normally you should be using the module infrastructure to load scripts. If you must use these methods, I suggest setting __file__
in the globals
you pass to the script so it can read that filename.
There's no other way to get the filename in execed code: as you note, the CWD may be in a completely different place.
If you really want to cover the case that a script is called via execfile(...)
, you can use the inspect
module to deduce the filename (including the path). As far as I am aware, this will work for all cases you listed:
filename = inspect.getframeinfo(inspect.currentframe()).filename path = os.path.dirname(os.path.abspath(filename))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With