Why does python __file__ variable returns errorneous path when used in DJango?
__file__
variable under django though i am getting correct pa开发者_JAVA技巧th. It's behavior is little weird. Here is my attached sample code please let me know why is the behavior so.
from django.shortcuts import render_to_response
import datetime
class WebServer():
def __init__(self):
pass
def display_first_page(self, request):
print "File Path: ", __file__
return render_to_response('Hello')
I have stored this code at the given location : C:\Django_example\MySample. Ideally it should have returned something like C:\Django_example\MySample\webserver.py, but instead i am getting C:\Django_example\MySample\..\MySample\webserver.py . Can someone please point me to the right direction.
Thanks in advance,
RupeshAs far as I can see, C:\Django_example\MySample\webserver.py
and C:\Django_example\MySample\..\MySample\webserver.py
points to the same file, so it isn't errorneous.
If you want a more succinct representation of the path, try:
import os
print "File Path: ", os.path.realpath(__file__)
update (an attempt to understand the output of __file__
)
The only way I can reproduce that behaviour is if I update sys.path
. Example:
[me@home]$ cd /project/django/xyz
[me@home]$ ./manage.py shell
(InteractiveConsole)
>>> from app import models as M
>>> M.__file__
'/project/django/xyz/app/models.pyc'
>>> import sys
>>> sys.path.append('../')
>>> from xyz.app import models as N
>>> N.__file__
'/project/django/xyz/../xyz/app/models.pyc'
Since the absolute path is formed by appending the relative path to the base path, I suspect you might have a /../
somewhere in your python path.
What do you get when you print sys.path
from your view?
To get a current directory path you can do something like this.
import os
os.path.abspath(os.path.dirname(__file__))
This will return a normalized absolutized version of the pathname(absolute path) as well as it will normalizes the path. For example, on Unix and Mac OS X systems the path /var/www/project will work fine, but on Windows systems that is not a good path. Normalizing the path will convert forward slashes to backward slashes. Normalization also collapses redundant separators, for example the path A/foo/../B will be normalized to A/B.
Rupesh
精彩评论