如何动态加载文件夹中的所有模块?

时间:2018-03-23 18:17:24

标签: python python-3.x python-import

程序结构是这样的:

   ├── loader.py
    └── plugins
        ├── first.py
        └── __init__.py

loader.py包含加载模块的代码,如下所示:

import importlib.util
import os

search_dir = "./plugins"
plugins_module = []

def loader():
    path = os.path.realpath(search_dir)
    for module in os.listdir(path):
        spec = importlib.util.spec_from_file_location(module.split(".")[0], os.path.join(path,module))
        plugin_module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(plugin_module)
        plugins_module.append(plugin_module)

loader()

__init__.py的内容是:

from first import hello
def main():
    print("hello from __init__.py")
    hello()

first.py看起来像这样:

def hello():
    print("hello from first.py")

但是装载机给了我这个错误

Traceback (most recent call last):
  File "loader.py", line 15, in <module>
    loader()
  File "loader.py", line 12, in loader
    spec.loader.exec_module(plugin_module)
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/vishal/Programs/stack/plugins/__init__.py", line 1, in <module>
    from first import hello
ModuleNotFoundError: No module named 'first'

0 个答案:

没有答案