python importlib 没有命名的模块

python importlib no module named

我正在使用烧瓶并具有以下结构

<root>
manage_server.py
cas <directory>
--- __init__.py
--- routes.py
--- models.py
--- templates <directory>
--- static <directory>
--- formmodules <directory>
------ __init__.py
------ BaseFormModule.py
------ Interview.py

在 routes.py 中,我正在尝试在采访模块中创建采访 class 的实例,就像这样

my_module = "Interview"
module = importlib.import_module('formmodules."+my_module)

我在这里收到一个错误

ImportError: No module named formmodules.Interview

关于初始化文件的一些信息:

/cas/formmodules/__init__.py is empty
/cas/__init__.py is where I initialize my flask app. 

让我知道了解这些文件的内容是否有帮助。

这是经典的相对与绝对导入问题之一。

formmodules 仅相对于 cas 存在,但 import_module 进行绝对导入(与 from __future__ import absolute_imports 一样)。由于无法通过 sys.path 找到 formmodules,因此导入失败。

解决此问题的一种方法是使用 relative import.

If the name is specified in relative terms, then the package argument must be specified to the package which is to act as the anchor for resolving the package name.

您可能想尝试:

module = importlib.import_module('.formmodules.' + my_module, package=__package__)

注意 .

另一种选择是与 sys.path 混为一谈,这里确实没有必要。