python importlib 没有命名的模块

标签 python flask python-importlib

我正在使用 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/

相关文章:

python - 根据存储在字典中的条件从 Pandas 数据框中选择数据

python - 如何从这种图像中删除背景?

python - 日期时间对象不适用于 weekday()

javascript - 可过滤的自动完成,在 Flask 中使用 ajax

python - sqlite同时多次写入

python - 在 Flask-SqlAlchemy 中连接表

python - 如何使用 importlib 实现可以动态修改源代码的导入 Hook ?

Python:从名称为变量的文件导入函数

python - 如何从 Python 中的列表列表中删除值

python - 如何在保留调试的同时从字符串加载 Python 模块?