简体   繁体   English

python importlib没有命名的模块

[英]python importlib no module named

I am using flask and have the following structure 我正在使用烧瓶并具有以下结构

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

In routes.py, I'm trying to create an instance of the Interview class in the Interview module, like so 在routes.py中,我正在尝试在Interview模块中创建Interview类的实例,就像这样

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

I get an error here that says 我在这里得到一个错误

ImportError: No module named formmodules.Interview

Some info about the init files: 有关init文件的一些信息:

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

Let me know if it is helpful to know the contents of any of these files. 如果知道任何这些文件的内容是否有帮助,请告诉我。

This is one of the classical relative vs absolute import problems. 这是经典的相对与绝对导入问题之一。

formmodules only exists relative to cas , but import_module does an absolute import (as with from __future__ import absolute_imports ). formmodules仅相对于cas存在,但import_module执行绝对导入(与from __future__ import absolute_imports )。 Since formmodules cannot be found via sys.path , the import fails. 由于无法通过sys.path找到formmodules ,导入失败。

One way to fix this is to use a 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. 如果以相对术语指定名称,则必须将package参数指定给包,该包用作解析包名称的锚点。

You might want to try with: 您可能想尝试:

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

Note the . 请注意. .

The other option is to muck about with sys.path , which really isn't necessary, here. 另一种选择是使用sys.path这个问题,这里没有必要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM