Consider the following Python code:
import os print os.getcwd()
os.getcwd() to get the script file's directory location. When I run the script from the command line it gives me the correct path whereas when I run it from a script run by code in a Django view it prints
How can I get the path to the script from within a script run by a Django view?
Summing up the answers thus far -
os.path.abspath() both give the current working directory which may or may not be the directory where the script resides. In my web host setup
gives only the filename without the path.
Isn't there any way in Python to (always) be able to receive the path in which the script resides?
You need to call
__file__, so that when
__file__ is a filename without the path you still get the dir path:
import os print(os.path.dirname(os.path.realpath(__file__)))
To quote from the Python docs:
As initialized upon program startup, the first item of this list,
path, is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input),
pathis the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of