我有这个项目结构:
脚本
-- A == AA ++ __init__.py ++ AAA.py ++ AAB.py ++ AAC.py == AB ++ __init__.py ++ ABA.py ++ ABB.py ++ ABC.py -- B == BA ++ __init__.py ++ BAA.py ++ BAB.py ++ BAC.py == BB ++ __init__.py ++ BBA.py ++ BBB.py ++ BBC.py
我想将里面的类Scripts/A/AA/AAA.py
导入Scripts/B/BB/BBC.py
. 我使用了一些解决方案:
from AAA import *
给我ImportError: No module named AAA
。from Scripts.A.AA.AAA import *
给我ImportError: No module named Scripts.A.AA.AAA
。from ..A.AA.AAA import *
给我ValueError: Attempted relative import beyond toplevel package
。from ....A.AA.AAA import *
给我ValueError: Attempted relative import in non-package
。
我该怎么办 ?
编辑1:
我改变了项目的结构,现在是这样的:
脚本
-- elements == A ++ __init__.py ++ AAA.py ++ AAB.py ++ AAC.py == B ++ __init__.py ++ BAA.py ++ BAB.py ++ BAC.py -- general == imports.py == __init__.py -- main.py
我编写了这段代码来导入所有类:
elementDict = []
dirList = os.walk('elements')
for dname in dirList:
fileList = dname[2]
for fname in fileList:
if fname != '__init__.py' and fname.endswith('.py') and (not fname.endswith('_ut.py')) and (not fname.endswith('~')):
path = dname[0].split(os.sep)
path = filter(None, path[path.index('elements'):])
dir = '.'.join(path)
mod = importlib.import_module(dir + '.' + fname[:-3])
for cname, obj in inspect.getmembers(mod, inspect.isclass):
if cname not in elementDict:
elementDict[cname] = obj
这导致:
Traceback (most recent call last):
File "C:\Users\test\Scripts\general\imports.py", line 29, in __init__
mod = importlib.import_module(dir + '.' + fname[:-3])
File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named elements.A.AAA
任何的想法?
编辑2:
我已经解决了这个问题;我没有任何__init__.py
.elements