Python 从另一个包导入lib import_模块
我的目录结构如下所示:Python 从另一个包导入lib import_模块,python,python-2.7,python-import,import-module,python-importlib,Python,Python 2.7,Python Import,Import Module,Python Importlib,我的目录结构如下所示: . ├── superclass │ ├── __init__.py │ └── superclass.py ├── tests │ ├── __init__.py │ └── test_subclass.pyc └── subclass ├── __init__.py ├── a.py ├── b.py └── subclass.py 在subclass.py中,我有一个类子类,它继承自超类。在子类中,我调用self.r
.
├── superclass
│ ├── __init__.py
│ └── superclass.py
├── tests
│ ├── __init__.py
│ └── test_subclass.pyc
└── subclass
├── __init__.py
├── a.py
├── b.py
└── subclass.py
在subclass.py
中,我有一个类子类
,它继承自超类
。在子类中,我调用self.register(“Subclass”,“a”,“b”)
,它在超类中定义为:
def register(self, package, module_names):
for name in module_names:
module = importlib.import_module(name, package)
functions = inspect.getmembers(module, inspect.isfunction)
for register in functions:
if register[0].startswith("register"):
register[1](self)
subclass.py
还包含:
if __name__ == "__main__":
Subclass().do_something()
当我运行python subclass/subclass.py
时,一切都按照我的预期运行;导入模块a
和b
,并且每个模块中的所有寄存器
功能都正确运行
在test\u子类
中,我从subclass.subclass导入subclass
,调用子类
构造函数。但是,当我运行py.test
时,我得到错误ImportError:没有名为b的模块。a
模块导入正常,但b
模块失败
我尝试颠倒导入的顺序(self.register(“subclass”,“b”,“a”)
),但在b
上仍然失败
模块a
比模块b
有更多的导入语句(我有其他文件没有显示在目录图中),当我将a
的所有导入添加到b
时,它仍然以同样的方式失败
这是动态导入模块的正确方法吗?如果是,我是否遗漏了什么?如果不是,我是否将错误的参数传递给了import\u module
注意,我正在使用python 2.7。将子类的父路径添加到PYTHONPATH中,这有帮助吗?这是一个很好的想法,但我已经确保了它的存在。谢谢