7

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
  • 515
  • 2
  • 7
  • 19

2 Answers2

10

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

Spencer
  • 709
  • 5
  • 12
  • 1
    Thx 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) :) – RossGK Jan 29 '15 at 17:08
0

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

Nomi
  • 185
  • 2
  • 13