我正在使用 flask 并具有以下结构
<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 中,我试图在面试模块中创建面试类的实例,就像这样
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
,这里确实没有必要。
关于python importlib 没有命名的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46205467/