为什么 python __file__ 变量在 DJango 中使用时返回错误路径?
我试图使用 django 下的 python __file__
变量检索文件路径,尽管我得到了正确的路径。它的行为有点奇怪。这是我附加的示例代码,请让我知道为什么会出现这种情况。
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')
我已将此代码存储在给定位置:C:\Django_example\MySample。理想情况下,它应该返回类似 C:\Django_example\MySample\webserver.py 的内容,但我得到的是 C:\Django_example\MySample\..\MySample\webserver.py 。有人可以指出我正确的方向吗?
预先感谢,
鲁佩什
I was trying to retrieve the file path using python __file__
variable under django though i am getting correct path. 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,
Rupesh
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,
C:\Django_example\MySample\webserver.py
和C:\Django_example\MySample\..\MySample\webserver.py
指向相同的文件,所以不会出错。如果您想要更简洁的路径表示,请尝试:
update (尝试理解 __file__ 的输出)
我可以重现该行为的唯一方法是更新 sys.path< /代码>。示例:
由于绝对路径是通过将相对路径附加到基本路径而形成的,因此我怀疑您的 python 路径中的某处可能有
/../
。当您从视图中打印
sys.path
时,您会得到什么?As far as I can see,
C:\Django_example\MySample\webserver.py
andC:\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:
update (an attempt to understand the output of
__file__
)The only way I can reproduce that behaviour is if I update
sys.path
. Example: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?要获取当前目录路径,您可以执行类似的操作。
这将返回路径名(绝对路径)的规范化绝对版本,并将规范化路径。例如,在 Unix 和 Mac OS X 系统上,路径 /var/www/project 可以正常工作,但在 Windows 系统上,这不是一个好的路径。规范化路径会将正斜杠转换为反斜杠。规范化还会折叠冗余分隔符,例如路径 A/foo/../B 将被规范化为 A/B。
鲁佩什
To get a current directory path you can do something like this.
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