Python importlib 模块,find_loader() 实例源码

我们从Python开源项目中,提取了以下22个代码示例,用于说明如何使用importlib.find_loader()

项目:Worksets    作者:DozyDolphin    | 项目源码 | 文件源码
def test_dependencies():
    dependencies = {'*nix': ['wmctrl', 'xdotool'],
                    'python': ['tinydb']}
    missing_dependencies = False
    dep_err_msgs = []

    for dependency in dependencies['*nix']:
        DEVNULL = open(os.devnull, 'w')
        result = subprocess.call(['which', dependency], stdout=DEVNULL)
        if not result == 0:
            dep_err_msgs.append('Linux application: ' + dependency)
            missing_dependencies = True

    for dependency in dependencies['python']:
        loader = importlib.find_loader(dependency)
        result = loader is not None
        if not result:
            dep_err_msgs.append('Python package: ' + dependency)
            missing_dependencies = True

    if missing_dependencies:
        print('Worksets will not work - dependencies missing:')
        for each in dep_err_msgs:
            print(each)
        sys.exit()
项目:pythonVSCode    作者:DonJayamanne    | 项目源码 | 文件源码
def find_module_py33(string, path=None):
    loader = importlib.machinery.PathFinder.find_module(string, path)

    if loader is None and path is None:  # Fallback to find builtins
        try:
            loader = importlib.find_loader(string)
        except ValueError as e:
            # See #491. Importlib might raise a ValueError, to avoid this, we
            # just raise an ImportError to fix the issue.
            raise ImportError("Originally ValueError: " + e.message)

    if loader is None:
        raise ImportError("Couldn't find a loader for {0}".format(string))

    try:
        is_package = loader.is_package(string)
        if is_package:
            module_path = os.path.dirname(loader.path)
            module_file = None
        else:
            module_path = loader.get_filename(string)
            module_file = open(module_path, 'rb')
    except AttributeError:
        # ExtensionLoader has not attribute get_filename, instead it has a
        # path attribute that we can use to retrieve the module path
        try:
            module_path = loader.path
            module_file = open(loader.path, 'rb')
        except AttributeError:
            module_path = string
            module_file = None
        finally:
            is_package = False

    return module_file, module_path, is_package
项目:radar    作者:amoose136    | 项目源码 | 文件源码
def has_module(module_name):
    """Check to see if a python module is available.
    """
    if sys.version_info > (3, ):
        import importlib
        return importlib.find_loader(module_name) is not None
    else:  # pragma: no cover
        import imp
        try:
            imp.find_module(module_name)
        except ImportError:
            return False
        return True
项目:coquery    作者:gkunter    | 项目源码 | 文件源码
def has_module(name):
    """
    Check if the Python module 'name' is available.

    Parameters
    ----------
    name : str
        The name of the Python module, as used in an import instruction.

    This function uses ideas from this Stack Overflow question:
    http://stackoverflow.com/questions/14050281/

    Returns
    -------
    b : bool
        True if the module exists, or False otherwise.
    """

    if sys.version_info > (3, 3):
        import importlib.util
        return importlib.util.find_spec(name) is not None
    elif sys.version_info > (2, 7, 99):
        import importlib
        return importlib.find_loader(name) is not None
    else:
        import pkgutil
        return pkgutil.find_loader(name) is not None
项目:stephanie-va    作者:SlapBot    | 项目源码 | 文件源码
def check_if_installed(module_name):
        try:
            module_status = importlib.find_loader(module_name)
        except Exception:
            module_status = importlib.util.find_spec(module_name)
        return module_status
项目:LIE    作者:EmbraceLife    | 项目源码 | 文件源码
def can_import(name, package=None):
    """ Returns True if the given module can be imported.

        # Arguments

        name: str. The name of the module.
        package: str. The name of the package, if `name` is a relative import.
            This is ignored for Python versions < 3.4.

        # Return value

        If importing the specified module should succeed, returns True;
        otherwise, returns False.
    """
    try:
        importlib.util.find_spec
    except AttributeError:
        # Python < 3.4
        return importlib.find_loader(       # pylint: disable=deprecated-method
            name
        ) is not None
    else:
        # Python >= 3.4
        return importlib.util.find_spec(name, package=package) is not None

### EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF
项目:of    作者:OptimalBPM    | 项目源码 | 文件源码
def install_package(_package_name, _arguments=None):
    """
    Install the packages listed if not present
    :param _package_name: The package to install
    :param _argument: An optional argument
    :return:
    """
    _installed = []

    import pip

    _exists = None
    if minor < 3:
        import pkgutil
        _exists = pkgutil.find_loader(_package_name)

    elif minor == 3:
        import importlib
        _exists = importlib.find_loader(_package_name)
    else:
        import importlib
        _exists = importlib.util.find_spec(_package_name)

    if _exists is None:
        print(_package_name + " not installed, installing...")
        if _arguments is None:
            pip.main(['install', _package_name])
        else:
            pip.main(['install', _package_name] + _arguments)
        print(_package_name + " installed...")
        return True
    else:
        print(_package_name + " already installed, skipping...")
        return False
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_sys_modules(self):
        # If a module with __loader__ is in sys.modules, then return it.
        name = 'some_mod'
        with util.uncache(name):
            module = imp.new_module(name)
            loader = 'a loader!'
            module.__loader__ = loader
            sys.modules[name] = module
            found = importlib.find_loader(name)
            self.assertEqual(loader, found)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_sys_modules_loader_is_None(self):
        # If sys.modules[name].__loader__ is None, raise ValueError.
        name = 'some_mod'
        with util.uncache(name):
            module = imp.new_module(name)
            module.__loader__ = None
            sys.modules[name] = module
            with self.assertRaises(ValueError):
                importlib.find_loader(name)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_success(self):
        # Return the loader found on sys.meta_path.
        name = 'some_mod'
        with util.uncache(name):
            with util.import_state(meta_path=[self.FakeMetaFinder]):
                self.assertEqual((name, None), importlib.find_loader(name))
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_success_path(self):
        # Searching on a path should work.
        name = 'some_mod'
        path = 'path to some place'
        with util.uncache(name):
            with util.import_state(meta_path=[self.FakeMetaFinder]):
                self.assertEqual((name, path),
                                 importlib.find_loader(name, path))
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_nothing(self):
        # None is returned upon failure to find a loader.
        self.assertIsNone(importlib.find_loader('nevergoingtofindthismodule'))
项目:CNCGToolKit    作者:cineuse    | 项目源码 | 文件源码
def find_module_py33(string, path=None):
    loader = importlib.machinery.PathFinder.find_module(string, path)

    if loader is None and path is None:  # Fallback to find builtins
        loader = importlib.find_loader(string)

    if loader is None:
        raise ImportError("Couldn't find a loader for {0}".format(string))

    try:
        is_package = loader.is_package(string)
        if is_package:
            module_path = os.path.dirname(loader.path)
            module_file = None
        else:
            module_path = loader.get_filename(string)
            module_file = open(module_path, 'rb')
    except AttributeError:
        # ExtensionLoader has not attribute get_filename, instead it has a
        # path attribute that we can use to retrieve the module path
        try:
            module_path = loader.path
            module_file = open(loader.path, 'rb')
        except AttributeError:
            module_path = string
            module_file = None
        finally:
            is_package = False

    return module_file, module_path, is_package
项目:kur    作者:deepgram    | 项目源码 | 文件源码
def can_import(name, package=None):
    """ Returns True if the given module can be imported.

        # Arguments

        name: str. The name of the module.
        package: str. The name of the package, if `name` is a relative import.
            This is ignored for Python versions < 3.4.

        # Return value

        If importing the specified module should succeed, returns True;
        otherwise, returns False.
    """
    try:
        importlib.util.find_spec
    except AttributeError:
        # Python < 3.4
        return importlib.find_loader(       # pylint: disable=deprecated-method
            name
        ) is not None
    else:
        # Python >= 3.4
        return importlib.util.find_spec(name, package=package) is not None

### EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def find_module_py33(string, path=None, loader=None, fullname=None):
    loader = loader or importlib.machinery.PathFinder.find_module(string, path)

    if loader is None and path is None:  # Fallback to find builtins
        try:
            with warnings.catch_warnings(record=True):
                # Mute "DeprecationWarning: Use importlib.util.find_spec()
                # instead." While we should replace that in the future, it's
                # probably good to wait until we deprecate Python 3.3, since
                # it was added in Python 3.4 and find_loader hasn't been
                # removed in 3.6.
                loader = importlib.find_loader(string)
        except ValueError as e:
            # See #491. Importlib might raise a ValueError, to avoid this, we
            # just raise an ImportError to fix the issue.
            raise ImportError("Originally  " + repr(e))

    if loader is None:
        raise ImportError("Couldn't find a loader for {0}".format(string))

    try:
        is_package = loader.is_package(string)
        if is_package:
            if hasattr(loader, 'path'):
                module_path = os.path.dirname(loader.path)
            else:
                # At least zipimporter does not have path attribute
                module_path = os.path.dirname(loader.get_filename(string))
            if hasattr(loader, 'archive'):
                module_file = DummyFile(loader, string)
            else:
                module_file = None
        else:
            module_path = loader.get_filename(string)
            module_file = DummyFile(loader, string)
    except AttributeError:
        # ExtensionLoader has not attribute get_filename, instead it has a
        # path attribute that we can use to retrieve the module path
        try:
            module_path = loader.path
            module_file = DummyFile(loader, string)
        except AttributeError:
            module_path = string
            module_file = None
        finally:
            is_package = False

    if hasattr(loader, 'archive'):
        module_path = loader.archive

    return module_file, module_path, is_package
项目:pythonVSCode    作者:DonJayamanne    | 项目源码 | 文件源码
def find_module_py33(string, path=None):
    loader = importlib.machinery.PathFinder.find_module(string, path)

    if loader is None and path is None:  # Fallback to find builtins
        try:
            loader = importlib.find_loader(string)
        except ValueError as e:
            # See #491. Importlib might raise a ValueError, to avoid this, we
            # just raise an ImportError to fix the issue.
            raise ImportError("Originally  " + repr(e))

    if loader is None:
        raise ImportError("Couldn't find a loader for {0}".format(string))

    try:
        is_package = loader.is_package(string)
        if is_package:
            if hasattr(loader, 'path'):
                module_path = os.path.dirname(loader.path)
            else:
                # At least zipimporter does not have path attribute
                module_path = os.path.dirname(loader.get_filename(string))
            if hasattr(loader, 'archive'):
                module_file = DummyFile(loader, string)
            else:
                module_file = None
        else:
            module_path = loader.get_filename(string)
            module_file = DummyFile(loader, string)
    except AttributeError:
        # ExtensionLoader has not attribute get_filename, instead it has a
        # path attribute that we can use to retrieve the module path
        try:
            module_path = loader.path
            module_file = DummyFile(loader, string)
        except AttributeError:
            module_path = string
            module_file = None
        finally:
            is_package = False

    if hasattr(loader, 'archive'):
        module_path = loader.archive

    return module_file, module_path, is_package
项目:apm-agent-python    作者:elastic    | 项目源码 | 文件源码
def find_module(self, fullname, path=None):
        # If the module being imported is not one we have registered
        # post import hooks for, we can return immediately. We will
        # take no further part in the importing of this module.

        if not fullname in _post_import_hooks:
            return None

        # When we are interested in a specific module, we will call back
        # into the import system a second time to defer to the import
        # finder that is supposed to handle the importing of the module.
        # We set an in progress flag for the target module so that on
        # the second time through we don't trigger another call back
        # into the import system and cause a infinite loop.

        if fullname in self.in_progress:
            return None

        self.in_progress[fullname] = True

        # Now call back into the import system again.

        try:
            if PY3:
                # For Python 3 we need to use find_loader() from
                # the importlib module. It doesn't actually
                # import the target module and only finds the
                # loader. If a loader is found, we need to return
                # our own loader which will then in turn call the
                # real loader to import the module and invoke the
                # post import hooks.

                loader = importlib.find_loader(fullname, path)

                if loader:
                    return _ImportHookChainedLoader(loader)

            else:
                # For Python 2 we don't have much choice but to
                # call back in to __import__(). This will
                # actually cause the module to be imported. If no
                # module could be found then ImportError will be
                # raised. Otherwise we return a loader which
                # returns the already loaded module and invokes
                # the post import hooks.

                __import__(fullname)

                return _ImportHookLoader()

        finally:
            del self.in_progress[fullname]

# Decorator for marking that a function should be called as a post
# import hook when the target module is imported.
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def find_module_py33(string, path=None, loader=None, fullname=None):
    loader = loader or importlib.machinery.PathFinder.find_module(string, path)

    if loader is None and path is None:  # Fallback to find builtins
        try:
            loader = importlib.find_loader(string)
        except ValueError as e:
            # See #491. Importlib might raise a ValueError, to avoid this, we
            # just raise an ImportError to fix the issue.
            raise ImportError("Originally  " + repr(e))

    if loader is None:
        raise ImportError("Couldn't find a loader for {0}".format(string))

    try:
        is_package = loader.is_package(string)
        if is_package:
            if hasattr(loader, 'path'):
                module_path = os.path.dirname(loader.path)
            else:
                # At least zipimporter does not have path attribute
                module_path = os.path.dirname(loader.get_filename(string))
            if hasattr(loader, 'archive'):
                module_file = DummyFile(loader, string)
            else:
                module_file = None
        else:
            module_path = loader.get_filename(string)
            module_file = DummyFile(loader, string)
    except AttributeError:
        # ExtensionLoader has not attribute get_filename, instead it has a
        # path attribute that we can use to retrieve the module path
        try:
            module_path = loader.path
            module_file = DummyFile(loader, string)
        except AttributeError:
            module_path = string
            module_file = None
        finally:
            is_package = False

    if hasattr(loader, 'archive'):
        module_path = loader.archive

    return module_file, module_path, is_package
项目:deb-python-wrapt    作者:openstack    | 项目源码 | 文件源码
def find_module(self, fullname, path=None):
        # If the module being imported is not one we have registered
        # post import hooks for, we can return immediately. We will
        # take no further part in the importing of this module.

        if not fullname in _post_import_hooks:
            return None

        # When we are interested in a specific module, we will call back
        # into the import system a second time to defer to the import
        # finder that is supposed to handle the importing of the module.
        # We set an in progress flag for the target module so that on
        # the second time through we don't trigger another call back
        # into the import system and cause a infinite loop.

        if fullname in self.in_progress:
            return None

        self.in_progress[fullname] = True

        # Now call back into the import system again.

        try:
            if PY3:
                # For Python 3 we need to use find_loader() from
                # the importlib module. It doesn't actually
                # import the target module and only finds the
                # loader. If a loader is found, we need to return
                # our own loader which will then in turn call the
                # real loader to import the module and invoke the
                # post import hooks.

                loader = importlib.find_loader(fullname, path)

                if loader:
                    return _ImportHookChainedLoader(loader)

            else:
                # For Python 2 we don't have much choice but to
                # call back in to __import__(). This will
                # actually cause the module to be imported. If no
                # module could be found then ImportError will be
                # raised. Otherwise we return a loader which
                # returns the already loaded module and invokes
                # the post import hooks.

                __import__(fullname)

                return _ImportHookLoader()

        finally:
            del self.in_progress[fullname]

# Decorator for marking that a function should be called as a post
# import hook when the target module is imported.
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
def find_module_py33(string, path=None):
    loader = importlib.machinery.PathFinder.find_module(string, path)

    if loader is None and path is None:  # Fallback to find builtins
        try:
            loader = importlib.find_loader(string)
        except ValueError as e:
            # See #491. Importlib might raise a ValueError, to avoid this, we
            # just raise an ImportError to fix the issue.
            raise ImportError("Originally  " + repr(e))

    if loader is None:
        raise ImportError("Couldn't find a loader for {0}".format(string))

    try:
        is_package = loader.is_package(string)
        if is_package:
            if hasattr(loader, 'path'):
                module_path = os.path.dirname(loader.path)
            else:
                # At least zipimporter does not have path attribute
                module_path = os.path.dirname(loader.get_filename(string))
            if hasattr(loader, 'archive'):
                module_file = DummyFile(loader, string)
            else:
                module_file = None
        else:
            module_path = loader.get_filename(string)
            module_file = DummyFile(loader, string)
    except AttributeError:
        # ExtensionLoader has not attribute get_filename, instead it has a
        # path attribute that we can use to retrieve the module path
        try:
            module_path = loader.path
            module_file = DummyFile(loader, string)
        except AttributeError:
            module_path = string
            module_file = None
        finally:
            is_package = False

    if hasattr(loader, 'archive'):
        module_path = loader.archive

    return module_file, module_path, is_package
项目:.emacs.d    作者:christabella    | 项目源码 | 文件源码
def find_module_py33(string, path=None, loader=None, fullname=None):
    loader = loader or importlib.machinery.PathFinder.find_module(string, path)

    if loader is None and path is None:  # Fallback to find builtins
        try:
            loader = importlib.find_loader(string)
        except ValueError as e:
            # See #491. Importlib might raise a ValueError, to avoid this, we
            # just raise an ImportError to fix the issue.
            raise ImportError("Originally  " + repr(e))

    if loader is None:
        raise ImportError("Couldn't find a loader for {0}".format(string))

    try:
        is_package = loader.is_package(string)
        if is_package:
            if hasattr(loader, 'path'):
                module_path = os.path.dirname(loader.path)
            else:
                # At least zipimporter does not have path attribute
                module_path = os.path.dirname(loader.get_filename(string))
            if hasattr(loader, 'archive'):
                module_file = DummyFile(loader, string)
            else:
                module_file = None
        else:
            module_path = loader.get_filename(string)
            module_file = DummyFile(loader, string)
    except AttributeError:
        # ExtensionLoader has not attribute get_filename, instead it has a
        # path attribute that we can use to retrieve the module path
        try:
            module_path = loader.path
            module_file = DummyFile(loader, string)
        except AttributeError:
            module_path = string
            module_file = None
        finally:
            is_package = False

    if hasattr(loader, 'archive'):
        module_path = loader.archive

    return module_file, module_path, is_package
项目:wuye.vim    作者:zhaoyingnan911    | 项目源码 | 文件源码
def find_module_py33(string, path=None, loader=None, fullname=None):
    loader = loader or importlib.machinery.PathFinder.find_module(string, path)

    if loader is None and path is None:  # Fallback to find builtins
        try:
            loader = importlib.find_loader(string)
        except ValueError as e:
            # See #491. Importlib might raise a ValueError, to avoid this, we
            # just raise an ImportError to fix the issue.
            raise ImportError("Originally  " + repr(e))

    if loader is None:
        raise ImportError("Couldn't find a loader for {0}".format(string))

    try:
        is_package = loader.is_package(string)
        if is_package:
            if hasattr(loader, 'path'):
                module_path = os.path.dirname(loader.path)
            else:
                # At least zipimporter does not have path attribute
                module_path = os.path.dirname(loader.get_filename(string))
            if hasattr(loader, 'archive'):
                module_file = DummyFile(loader, string)
            else:
                module_file = None
        else:
            module_path = loader.get_filename(string)
            module_file = DummyFile(loader, string)
    except AttributeError:
        # ExtensionLoader has not attribute get_filename, instead it has a
        # path attribute that we can use to retrieve the module path
        try:
            module_path = loader.path
            module_file = DummyFile(loader, string)
        except AttributeError:
            module_path = string
            module_file = None
        finally:
            is_package = False

    if hasattr(loader, 'archive'):
        module_path = loader.archive

    return module_file, module_path, is_package