Consider the following Python code:
import os
print os.getcwd()
I use 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?
UPDATE:
Summing up the answers thus far - os.getcwd()
and 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.__file__
Isn't there any way in Python to (always) be able to receive the path in which the script resides?
getcwd
will tell you your script's location. It suggestsargv[0]
,dirname
, andabspath
. – Phobeos.chdir
, which sets the current working directory; it does not move your script file to a new location on the hard drive. The initial working directory might be the same as the directory your script lives in, but not always; the article even demonstrates that. – Phobe__file__
will return the filename of the scripts context. Caveat emptor if you're calling out to an external script from your__main__
- you might get a different response than you expected. – Keenankeene