Python
Load Module by Path

Load Python Module by Path

import sys
from importlib.util import module_from_spec
from importlib.util import spec_from_file_location
from os.path import basename
from os.path import splitext
from types import ModuleType
 
 
def load_module_from_file(path: str) -> ModuleType:
    """
    ref: https://blog.csdn.net/Likianta/article/details/126660058
    """
    name = splitext(basename(path))[0]
    spec = spec_from_file_location(name, path)
    # print(spec.name, spec.origin)
    module = module_from_spec(spec)
    sys.modules[spec.name] = module
    spec.loader.exec_module(module)
    return module