When i try:PROJECT_ROOT = os.path.dirname(__file__)
i get error like this:Traceback (most recent call last):
File "< stdin>", line 1, in <module>
NameError: name '__file__' is not defined
当我尝试:PROJECT_ROOT = os.path.dirname(__ file__)时,我得到如下错误:Traceback(最近一次调用最后一次):文件“
Does someone know how to fix this?
有人知道如何解决这个问题吗?
3 个解决方案
#1
4
Run that line of code via an actual module instead of in the Python REPL.
通过实际模块而不是Python REPL运行该行代码。
#2
4
If you are trying to use __file__
from your interpreter, no __file__
is defined. This is the intended behavior. __file__
is an attribute of modules. Here
is a discussion about the subject.
如果您尝试使用解释器中的__file__,则不会定义__file__。这是预期的行为。 __file__是模块的属性。这是关于这个主题的讨论。
You can test by doing this:
你可以这样测试:
~$ echo "print __file__" > test.py
~$ python test.py
test.py
__file__
works in from within modules.
__file__在模块内工作。
Now from the interpreter:
现在来自翻译:
~$ python
Python 2.7.0+ (r27:82500, Sep 15 2010, 18:04:55)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print __file__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
__file__
is not defined
__file__未定义
>>> import test
test.pyc
>>> print __file__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
__file__
is not defined
__file__未定义
>>> print test.__file__
test.pyc
>>>
__file__
is defined for the test module
__file__是为测试模块定义的
#3
3
Please try this in your settings.py :
请在您的settings.py中尝试此操作:
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
#1
4
Run that line of code via an actual module instead of in the Python REPL.
通过实际模块而不是Python REPL运行该行代码。
#2
4
If you are trying to use __file__
from your interpreter, no __file__
is defined. This is the intended behavior. __file__
is an attribute of modules. Here
is a discussion about the subject.
如果您尝试使用解释器中的__file__,则不会定义__file__。这是预期的行为。 __file__是模块的属性。这是关于这个主题的讨论。
You can test by doing this:
你可以这样测试:
~$ echo "print __file__" > test.py
~$ python test.py
test.py
__file__
works in from within modules.
__file__在模块内工作。
Now from the interpreter:
现在来自翻译:
~$ python
Python 2.7.0+ (r27:82500, Sep 15 2010, 18:04:55)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print __file__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
__file__
is not defined
__file__未定义
>>> import test
test.pyc
>>> print __file__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
__file__
is not defined
__file__未定义
>>> print test.__file__
test.pyc
>>>
__file__
is defined for the test module
__file__是为测试模块定义的
#3
3
Please try this in your settings.py :
请在您的settings.py中尝试此操作:
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))