【发布时间】:2017-03-15 14:27:33
【问题描述】:
编辑: __init__.py 文件已包含在内,但我使用的是 Python 3 - 我认为这并不重要。
另一个编辑: config.py 中的任何内容都将毫无问题地导入。如果我只是省略from cache import Cache,那么就没有错误。有趣的是,在config.py中导入Config时没有出现错误
我无法弄清楚这里出了什么问题。每当我尝试导入特定类时都会出错。这是我的项目布局:
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 中找到或导入任何类。所有文件都具有相同的权限。谁能告诉我这里出了什么问题?
【问题讨论】:
-
模块中没有
__init__.py文件。 -
相关 - What is init.py for?
-
您应该检查该目录是否已经在 sys.path 中。这只是一个简单的列表,如果你继续添加它,它会变得非常大。
-
os.path.abspath(os.path.join(cwd, os.pardir)) + '/dir1'应该是os.path.abspath(os.path.join(cwd, os.pardir, 'dir1'))- os.path.join 可以接受任意数量的参数。 -
@MartinBonner 在这些情况下,您根本不应该修改
sys.path。
标签: python python-import python-module