File size: 703 Bytes
f5cf708
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import importlib.util

def load_module(module_filename, class_name):
    # 使用 spec_from_file_location 获取模块规范
    spec = importlib.util.spec_from_file_location("db_module", module_filename)
    # 如果 spec 是 None,说明无法加载模块
    if spec is None:
        raise ImportError(f"Cannot find module at {module_filename}")
    # 使用 module_from_spec 创建一个新的模块对象
    module = importlib.util.module_from_spec(spec)
    # 执行模块
    spec.loader.exec_module(module)
    MyClass = getattr(module, class_name, None)
    if MyClass is None:
        raise ImportError(f"Cannot find class '{class_name}' in module '{module_filename}'")
    return MyClass()