Exemplo n.º 1
0
def load_source(name, pathname, file=None):
    loader = _LoadSourceCompatibility(name, pathname, file)
    spec = util.spec_from_file_location(name, pathname, loader=loader)
    if name in sys.modules:
        module = _exec(spec, sys.modules[name])
    else:
        module = _load(spec)
    # To allow reloading to potentially work, use a non-hacked loader which
    # won't rely on a now-closed file object.
    module.__loader__ = machinery.SourceFileLoader(name, pathname)
    module.__spec__.loader = module.__loader__
    return module
Exemplo n.º 2
0
def load_compiled(name, pathname, file=None):
    """**DEPRECATED**"""
    loader = _LoadCompiledCompatibility(name, pathname, file)
    spec = util.spec_from_file_location(name, pathname, loader=loader)
    if name in sys.modules:
        module = _exec(spec, sys.modules[name])
    else:
        module = _load(spec)
    # To allow reloading to potentially work, use a non-hacked loader which
    # won't rely on a now-closed file object.
    module.__loader__ = SourcelessFileLoader(name, pathname)
    module.__spec__.loader = module.__loader__
    return module
Exemplo n.º 3
0
    def load_dynamic(name, path, file=None):
        """**DEPRECATED**

        Load an extension module.
        """
        import importlib.machinery
        loader = importlib.machinery.ExtensionFileLoader(name, path)

        # Issue #24748: Skip the sys.modules check in _load_module_shim;
        # always load new extension
        spec = importlib.machinery.ModuleSpec(
            name=name, loader=loader, origin=path)
        return _load(spec)
Exemplo n.º 4
0
def load_dynamic(name, path):
    """Load and initialize a module implemented as a dynamically loadable
    shared library and return its module object. If the module was already
    initialized, it will be initialized again.
    """
    # imp module is deprecated since Python 3.4
    if (sys.version_info >= (3, 4)):
        # the code below is taken from python3.6/imp.py
        from importlib.machinery import ExtensionFileLoader, ModuleSpec
        from importlib._bootstrap import _load
        loader = ExtensionFileLoader(name, path)
        spec = ModuleSpec(name=name, loader=loader, origin=path)
        return _load(spec)
    else:
        import imp
        return imp.load_dynamic(name, path)
Exemplo n.º 5
0
def load_package(name, path):
    """**DEPRECATED**"""
    if os.path.isdir(path):
        extensions = (machinery.SOURCE_SUFFIXES[:] +
                      machinery.BYTECODE_SUFFIXES[:])
        for extension in extensions:
            path = os.path.join(path, '__init__'+extension)
            if os.path.exists(path):
                break
        else:
            raise ValueError('{!r} is not a package'.format(path))
    spec = util.spec_from_file_location(name, path,
                                        submodule_search_locations=[])
    if name in sys.modules:
        return _exec(spec, sys.modules[name])
    else:
        return _load(spec)
Exemplo n.º 6
0
Arquivo: imp.py Projeto: Aktay-0/WP_EJ
def load_package(name, path):
    """**DEPRECATED**"""
    if os.path.isdir(path):
        extensions = (machinery.SOURCE_SUFFIXES[:] +
                      machinery.BYTECODE_SUFFIXES[:])
        for extension in extensions:
            path = os.path.join(path, '__init__' + extension)
            if os.path.exists(path):
                break
        else:
            raise ValueError('{!r} is not a package'.format(path))
    spec = util.spec_from_file_location(name,
                                        path,
                                        submodule_search_locations=[])
    if name in sys.modules:
        return _exec(spec, sys.modules[name])
    else:
        return _load(spec)
Exemplo n.º 7
0
def load_module_override(load_name, file, pathname, description):
    if pathname is not None:
        finder = get_importer(dirname(pathname))
        if hasattr(finder, "prefix"):  # AssetFinder or zipimporter
            entry, base_name = split(pathname)
            real_name = join(finder.prefix,
                             splitext(base_name)[0]).replace("/", ".")
            if hasattr(finder, "find_spec"):
                spec = finder.find_spec(real_name)
                spec.name = load_name
                return _bootstrap._load(spec)
            elif real_name == load_name:
                return finder.find_module(real_name).load_module(real_name)
            else:
                raise ImportError(
                    "{} does not support loading module '{}' under a different name '{}'"
                    .format(type(finder).__name__, real_name, load_name))

    return load_module_original(load_name, file, pathname, description)
Exemplo n.º 8
0
def load_py_package(file_path, module_name=None):
    if os.path.isdir(file_path):
        extensions = (machinery.SOURCE_SUFFIXES[:] +
                      machinery.BYTECODE_SUFFIXES[:])
        for extension in extensions:
            init_path = os.path.join(file_path, '__init__' + extension)
            if os.path.exists(init_path):
                if module_name is None:
                    module_name = os.path.basename(file_path)
                file_path = init_path
                break
        else:
            raise ValueError('{!r} is not a package'.format(file_path))
    else:
        if module_name is None:
            module_name = os.path.basename(os.path.dirname(file_path))
    spec = util.spec_from_file_location(module_name,
                                        file_path,
                                        submodule_search_locations=[])
    if module_name in sys.modules:
        return _exec(spec, sys.modules[module_name])
    else:
        return _load(spec)
Exemplo n.º 9
0
def load_plugins(*plugin_dir: str) -> Set[Plugin]:
    loaded_plugins = set()
    for module_info in pkgutil.iter_modules(plugin_dir):
        _tmp_matchers.clear()
        name = module_info.name
        if name.startswith("_"):
            continue

        spec = module_info.module_finder.find_spec(name)
        if spec.name in sys.modules:
            continue

        try:
            module = _load(spec)

            plugin = Plugin(name, module, _tmp_matchers.copy())
            plugins[name] = plugin
            loaded_plugins.add(plugin)
            logger.info(f"Succeeded to import \"{name}\"")
        except Exception as e:
            logger.error(f"Failed to import \"{name}\", error: {e}")
            logger.exception(e)
    return loaded_plugins
Exemplo n.º 10
0
def load_plugins(*plugin_dir: str) -> Set[Plugin]:
    """
    :说明:
      导入目录下多个插件,以 ``_`` 开头的插件不会被导入!
    :参数:
      - ``*plugin_dir: str``: 插件路径
    :返回:
      - ``Set[Plugin]``
    """
    loaded_plugins = set()
    for module_info in pkgutil.iter_modules(plugin_dir):
        _tmp_matchers.clear()
        name = module_info.name
        if name.startswith("_"):
            continue

        spec = module_info.module_finder.find_spec(name, None)
        if spec.name in plugins:
            continue
        elif spec.name in sys.modules:
            logger.warning(
                f"Module {spec.name} has been loaded by other plugin! Ignored")
            continue

        try:
            module = _load(spec)

            for m in _tmp_matchers:
                m.module = name
            plugin = Plugin(name, module, _tmp_matchers.copy())
            plugins[name] = plugin
            loaded_plugins.add(plugin)
            logger.opt(colors=True).info(f'Succeeded to import "<y>{name}</y>"')
        except Exception as e:
            logger.opt(colors=True, exception=e).error(
                f'<r><bg #f8bbd0>Failed to import "{name}"</bg #f8bbd0></r>')
    return loaded_plugins