编辑: __init__.py
文件已包含在内,但我使用的是Python 3 - 我认为不重要。
另一个修改: config.py
中的任何内容都会导入,没有任何问题。如果我只是省略from cache import Cache
那么没有错误。有趣的是,在Config
config.py
时没有发生错误
我无法弄清楚这里有什么问题。每当我尝试导入特定的类时,我都会收到错误消息。这是我的项目布局:
app/
dir1/
config.py
cache.py
manager.py
__init__.py
test/
test.py
__init__.py
cache.py:
import sys
import os
sys.path.append(os.path.dirname(__file__))
from manager import Manager, AnotherClass
from config import Config
manager.py
import sys
import os
sys.path.append(os.path.dirname(__file__))
from config import Config
from cache import Cache
test.py
cwd = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.abspath(os.path.join(cwd, os.pardir)) + '/dir1')
from cache import Cache, AnotherClass
from manager import Manager
test = Cache()
...
所以,当我运行test.py时,我得到了这个:
File "/path/to/project/app/dir1/<module>
from cache import Cache
ImportError: cannot import name 'Cache'
from manager import Manager line 5,
即使config.Config
加载得很好,也没有错误,但是当我尝试导入cache.Cache
时,它突然无法在cache.py
中找到或导入任何类。所有文件都具有相同的权限。有人能告诉我这里有什么问题吗?
答案 0 :(得分:3)
您缺少模块中的__init__.py
文件
app/
__init__.py
dir1/
__init__.py
config.py
cache.py
manager.py
test/
test.py
而不是弄乱sys.path
应该做一个相对导入,如
from .config import Config
from .cache import Cache
Python 2可能还需要一行
from __future__ import absolute_import
在进口之前。