我认为这是愚蠢的问题,但我无法弄清楚为什么我会得到以下内容
AttributeError: 'module' object has no attribute 'test'
运行我的 test3.py 时。
这是我的项目树:
.
├── __init__.py
├── test3.py
└── testdir
├── __init__.py
└── test.py
我的 test3.py :
#!/usr/bin/python
import testdir
if __name__ == "__main__":
print(testdir.test.VAR)
我的 test.py :
#!/usr/bin/python
import os
VAR=os.path.abspath(__file__)
我也尝试以这种方式导入我的 VAR:
from testdir.test import VAR
编辑:现在这个工作 - 感谢@user2357112 - 但我仍然想知道如果可能的话,如何在没有from ... import ...
的情况下导入整个 test.py 文件。 :)
我尝试了一个import ..testdir
来进行相对导入,但我得到了一个SyntaxError
.
如果我尝试import testdir.test
我会得到NameError: name'test' is not defined
.
如何导入此文件?我有点困惑。
编辑之二 :
很抱歉,当我尝试import testdir.test
时,我也修改了print(testdir.test.VAR)
print(test.VAR)
。
这就是问题所在,我的错。
跟:
#!/usr/bin/python
import testdir.test
if __name__ == "__main__":
print(testdir.test.VAR)
它工作得很好,我认为导入testdir.test
使test
单独存在(而不是testdir.test
)在范围内。
很抱歉给您带来不便。 :S
尝试将from .test import VAR
添加到testdir/init.py。然后import testdir
print testdir.VAR
test3.py 可能会起作用。我同意这更像是一种解决方法而不是解决方案。
要使用import语句添加整个文件,可以使用execfile
我终于成功地让它以这种方式工作:
#!/usr/bin/python
import testdir.test
if __name__ == "__main__":
print(testdir.test.VAR)
当我尝试使用print(testdir.test.VAR)
时,我错误地将修改为print(test.VAR)
import testdir.test
。所以我有这个名称错误。
我的坏。