简体   繁体   中英

Current directory (os.getcwd) from within Django determined how?

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.

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

Just in case someone find it useful. You can see your working directory, or print working direct in django using request. This behavior seem to work it rest framework's request, although I am not sure whether it works with regular django request or not.

def some_view(self, request, *args, **kwargs):
    request.META.get('pwd')

I hope it is useful for someone

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM