Current directory (os.getcwd) from within Django determined how?
Not sure exactly what you are trying to do, but as you are finding, os.getcwd()
does not have anything to do with locations of files or scripts, it has to do with the location where you are executing the script. This wouldn't be reliable for a number of reasons -- maybe on the host machine your web processes are running as an entirely different user than the owner of the scripts, for example. If you want to get something related to your files, you probably want to use os.path.abspath(os.path.dirname(__file__))
or os.path.realpath(path)
https://docs.python.org/3.3/library/os.path.html#os.path.realpath
![RossGK](https://i.stack.imgur.com/tD1jG.jpg?s=256&g=1)
RossGK
Updated on August 17, 2022Comments
-
RossGK almost 2 years
I'm using Django 1.7 over Python 2.7 and noticed a strange behaviour on my production host (Webfaction) versus development machine (mac os x).
On my dev machine, when I get current working directory via the cmds
import os dirspot = os.getcwd() print dirspot
I get the location of the manage.py executable. When I do it on the host (webfaction) machine I get diff response depending if the Django site is running, vs using the Django shell.
So with my project (and manage.py) located at:
/home/ross/webapps/djangoarea/myproj
Running
python manage.py shell
then the above os.getcwd() I get
/home/ross/webapps/djangoarea/myproj
But if I put the same command into a views.py and run my project, I get
/home/ross/
I'm guessing maybe it's related to apache2 and wsgi running django rather than the manage.py invoking it. Anybody know how to get this to be consistent?
Thanks in advance, Ross.
-
RossGK over 9 yearsThx for the suggestion. In Django the 'script' is the manage.py executable, so I thought there should be a consistent result there indicating its location. However, no prob - read up on abspath and realpath, and that looks good, so used that, which works well. Interestingly, within the manage.py shell, one needs to quote the underscore file reference or it won't work. (can't type that here, I see, as the underscores get removed) :)