我需要从另一个包中动态地将模块导入到我的项目中.
结构如下:
project_folder/
project/
__init__.py
__main__.py
plugins/
__init__.py
plugin1/
__init__.py
...
plugin2/
__init__.py
...
Run Code Online (Sandbox Code Playgroud)
我做了这个函数来加载一个模块:
import os
from importlib.util import spec_from_file_location, module_from_spec
def load_module(path, name=""):
""" loads a module by path """
try:
name = name if name != "" else path.split(os.sep)[-1] # take the module name by default
spec = spec_from_file_location(name, os.path.join(path, "__init__.py"))
plugin_module = module_from_spec(spec)
spec.loader.exec_module(plugin_module)
return plugin_module
except Exception as e:
print("failed to load module", path, "-->", e)
Run Code Online (Sandbox Code Playgroud)
除非模块使用相对导入,否则它可以工作:
无法加载module/path/to/plugins/plugin1 - >父模块'plugin1'未加载,无法执行相对导入
我究竟做错了什么?
我正在尝试将绘图函数映射到列表中的每个元素.函数本身,drawMap似乎没问题但是当我使用它时,我收到以下错误:
Couldn't match type `[]' with `IO'
Expected type: IO (IO Bool)
Actual type: [IO Bool]
In the return type of a call of `drawMap'
In a stmt of a 'do' block: drawMap testMap 32 img screen
In the second argument of `($)', namely
`do { screen <- SDL.setVideoMode 640 480 32 [SDL.SWSurface];
img <- SDL.loadBMP "grass.bmp";
drawMap testMap 32 img screen;
SDL.flip screen;
.... }'
Run Code Online (Sandbox Code Playgroud)
从阅读本文开始,我现在明白它与函数返回的内容有关,但我现在还不知道如何修复它.
我的代码看起来像这样:
testMap = [Tile 0 0 1, Tile 0 1 1, …Run Code Online (Sandbox Code Playgroud)