Python pkgutil.find_loader() Examples

The following are 30 code examples of pkgutil.find_loader(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pkgutil , or try the search function .
Example #1
Source File: utils.py    From mars with Apache License 2.0 6 votes vote down vote up
def lazy_import(name, package=None, globals=None, locals=None, rename=None):
    rename = rename or name
    prefix_name = name.split('.', 1)[0]

    class LazyModule(object):
        def __getattr__(self, item):
            real_mod = importlib.import_module(name, package=package)
            if globals is not None and rename in globals:
                globals[rename] = real_mod
            elif locals is not None:
                locals[rename] = real_mod
            return getattr(real_mod, item)

    if pkgutil.find_loader(prefix_name) is not None:
        return LazyModule()
    else:
        return None 
Example #2
Source File: utils.py    From megaman with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _check_backend(backend):
    def decorator(func):
        def wrapper(*args,**kwargs):
            import warnings
            warnings.warn(
                'Be careful in using megaman.plotter modules'
                ' API will change in the next release.',
                FutureWarning
            )
            import pkgutil
            package = pkgutil.find_loader(backend)
            if package is not None:
                return func(*args,**kwargs)
            else:
                raise ImportError('plotting backend {} not installed'.format(backend))
        return wrapper
    return decorator 
Example #3
Source File: util_import.py    From ubelt with Apache License 2.0 6 votes vote down vote up
def _pkgutil_modname_to_modpath(modname):  # nocover
    """
    faster version of :func:`_syspath_modname_to_modpath` using builtin python
    mechanisms, but unfortunately it doesn't play nice with pytest.

    Example:
        >>> # xdoctest: +SKIP
        >>> modname = 'xdoctest.static_analysis'
        >>> _pkgutil_modname_to_modpath(modname)
        ...static_analysis.py
        >>> # xdoctest: +REQUIRES(CPython)
        >>> _pkgutil_modname_to_modpath('_ctypes')
        ..._ctypes...

    Ignore:
        >>> _pkgutil_modname_to_modpath('cv2')
    """
    import pkgutil
    loader = pkgutil.find_loader(modname)
    if loader is None:
        raise Exception('No module named {} in the PYTHONPATH'.format(modname))
    modpath = loader.get_filename().replace('.pyc', '.py')
    return modpath 
Example #4
Source File: _testing_utils.py    From OpenFermion with Apache License 2.0 6 votes vote down vote up
def module_importable(module):
    """Without importing it, returns whether python module is importable.

    Args:
        module (string): Name of module.

    Returns:
        bool

    """
    import sys
    if sys.version_info >= (3, 4):
        from importlib import util
        plug_spec = util.find_spec(module)
    else:
        import pkgutil
        plug_spec = pkgutil.find_loader(module)
    if plug_spec is None:
        return False
    else:
        return True 
Example #5
Source File: common.py    From XFLTReaT with MIT License 6 votes vote down vote up
def check_modules_installed():
	reqs = []
	os_type = get_os_type()

	# reqs = [["module_name", "package_name"], [...]]
	if os_type == OS_LINUX:
		reqs = [["cryptography", "cryptography"], ["sctp","pysctp"]]
	if os_type == OS_MACOSX:
		reqs = [["cryptography", "cryptography"]]
	if os_type == OS_WINDOWS:
		reqs = [["cryptography", "cryptography"], ["win32file","pywin32"]]
	if os_type == OS_FREEBSD:
		reqs = [["cryptography", "cryptography"]]

	allinstalled = True
	for m in reqs:
		if not pkgutil.find_loader(m[0]):
			allinstalled = False
			internal_print("The following python modules were not installed: {0}".format(m[1]), -1)

	return allinstalled


# get os type. No need to import 'platform' in every module this way. 
Example #6
Source File: testing.py    From QCFractal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _plugin_import(plug):
    plug_spec = pkgutil.find_loader(plug)
    if plug_spec is None:
        return False
    else:
        return True 
Example #7
Source File: settings_template.py    From evo_slam with GNU General Public License v3.0 5 votes vote down vote up
def get_default_plot_backend():
    backends = {"PyQt5": "Qt5Agg", "PyQt4": "Qt4Agg"}
    for pkg in backends:
        if pkgutil.find_loader(pkg) is not None:
            return backends[pkg]
    return "TkAgg"


# default settings with documentation
# yapf: disable 
Example #8
Source File: cli.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def is_maasserver_available():
    """Ensure that 'maasserver' module is available."""
    return pkgutil.find_loader("maasserver") is not None 
Example #9
Source File: test_reporter_basic_ogr.py    From registrant with MIT License 5 votes vote down vote up
def setUp(self):
        """Set up the test.

        Create a file geodatabase from .xml schema file and
        load .json look-up data.
        """
        ogr_loader = pkgutil.find_loader('ogr')
        if not ogr_loader:
            self.skipTest(NO_OGR_ENV_MESSAGE)

        self.in_gdb, self.out_report_folder, self.json_results = prepare_test(
            'Basic_ogr')

    # ---------------------------------------------------------------------- 
Example #10
Source File: test_reporter_advanced_arcpy.py    From registrant with MIT License 5 votes vote down vote up
def setUp(self):
        """Set up the test context.

        Create a file geodatabase from .xml schema file and
        load .json look-up data.
        """
        arcpy_loader = pkgutil.find_loader('arcpy')
        if not arcpy_loader:
            self.skipTest(NO_ARCPY_ENV_MESSAGE)

        self.in_gdb, self.out_report_folder, self.json_results = prepare_test(
            'Advanced')
        return

    # --------------------------------------------------------------------- 
Example #11
Source File: test_reporter_advanced_ogr.py    From registrant with MIT License 5 votes vote down vote up
def setUp(self):
        """Set up the test context.

        Create a file geodatabase from .xml schema file and
        load .json look-up data.
        """
        ogr_loader = pkgutil.find_loader('ogr')
        if not ogr_loader:
            self.skipTest(NO_OGR_ENV_MESSAGE)

        self.in_gdb, self.out_report_folder, self.json_results = prepare_test(
            'Advanced_ogr')

    # --------------------------------------------------------------------- 
Example #12
Source File: test_reporter_basic_arcpy.py    From registrant with MIT License 5 votes vote down vote up
def setUp(self):
        """Set up the test.

        Create a file geodatabase from .xml schema file and
        load .json look-up data.
        """
        arcpy_loader = pkgutil.find_loader('arcpy')
        if not arcpy_loader:
            self.skipTest(NO_ARCPY_ENV_MESSAGE)

        self.in_gdb, self.out_report_folder, self.json_results = prepare_test(
            'Basic')

    # ---------------------------------------------------------------------- 
Example #13
Source File: context.py    From registrant with MIT License 5 votes vote down vote up
def prepare_test(test_type):
    """Prepare the geodatabase data for running tests on."""
    cfg = TEST_CONFIG[test_type]
    test_type = cfg['name']
    out_report_folder = os.path.join(tempfile.gettempdir(), test_type)
    if not os.path.exists(out_report_folder):
        os.mkdir(out_report_folder)

    arcpy_loader = pkgutil.find_loader('arcpy')
    if arcpy_loader:
        import arcpy
        arcpy.env.overwriteOutput = True
        xml_schema = cfg['xml_schema']
        in_gdb = arcpy.CreateFileGDB_management(
            out_folder_path=out_report_folder,
            out_name=test_type,
        ).getOutput(0)
        arcpy.ImportXMLWorkspaceDocument_management(
            target_geodatabase=in_gdb,
            in_file=xml_schema,
            import_type='SCHEMA_ONLY',
        )
    else:
        in_gdb = cfg['ogr_geodatabase']

    json_results = cfg['json_results']
    return (in_gdb, out_report_folder, json_results) 
Example #14
Source File: plots.py    From neupy with MIT License 5 votes vote down vote up
def load_pandas_module():
    if not pkgutil.find_loader('pandas'):
        raise ImportError(
            "The `pandas` library is not installed. Try to "
            "install it with pip: \n    pip install pandas")

    return importlib.import_module('pandas') 
Example #15
Source File: main.py    From onnxmltools with MIT License 5 votes vote down vote up
def convert_tensorflow(frozen_graph_def,
                       name=None, input_names=None, output_names=None,
                       doc_string='',
                       target_opset=None,
                       channel_first_inputs=None,
                       debug_mode=False, custom_op_conversions=None):
    import pkgutil
    if not pkgutil.find_loader('tf2onnx'):
        raise RuntimeError('tf2onnx is not installed, please install it before calling this function.')

    return _convert_tf_wrapper(frozen_graph_def, name, input_names, output_names, doc_string,
                               target_opset, channel_first_inputs, debug_mode, custom_op_conversions) 
Example #16
Source File: test_auth.py    From pygenie with Apache License 2.0 5 votes vote down vote up
def test_request_call(self, request):
        """Test request call kwargs for auth."""

        patcher = None
        if pkgutil.find_loader('eureq'):
            patcher = patch('eureq.request', check_request_auth_kwargs)
            patcher.start()

        request.side_effect = check_request_auth_kwargs

        pygenie.utils.call('http://localhost',
                           auth_handler=pygenie.auth.AuthHandler(conf=self.conf))

        if patcher:
            patcher.stop() 
Example #17
Source File: test_pkgutil.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_find_loader_avoids_emulation(self):
        with check_warnings() as w:
            self.assertIsNotNone(pkgutil.find_loader("sys"))
            self.assertIsNotNone(pkgutil.find_loader("os"))
            self.assertIsNotNone(pkgutil.find_loader("test.support"))
            self.assertEqual(len(w.warnings), 0) 
Example #18
Source File: test_pkgutil.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_find_loader_missing_module(self):
        name = 'totally bogus'
        loader = pkgutil.find_loader(name)
        self.assertIsNone(loader) 
Example #19
Source File: settings_template.py    From evo with GNU General Public License v3.0 5 votes vote down vote up
def get_default_plot_backend():
    backends = {"PyQt5": "Qt5Agg", "PyQt4": "Qt4Agg"}
    for pkg in backends:
        if pkgutil.find_loader(pkg) is not None:
            return backends[pkg]
    return "TkAgg"


# default settings with documentation
# yapf: disable 
Example #20
Source File: bootstrap.py    From opentelemetry-python with Apache License 2.0 5 votes vote down vote up
def _is_installed(library):
    return library in sys.modules or pkgutil.find_loader(library) is not None 
Example #21
Source File: utils.py    From snn_toolbox with MIT License 5 votes vote down vote up
def is_module_installed(mod):
    if sys.version_info[0] < 3:
        return pkgutil.find_loader(mod) is not None
    else:
        return importlib.util.find_spec(mod) is not None 
Example #22
Source File: test_imports.py    From MultiPlanarUNet with MIT License 5 votes vote down vote up
def test_modules_exist(self):
        """ Check if needed modules exist (are visible to Python) """
        for mod in self.needed_mods:
            self.assertIsNot(pkgutil.find_loader(mod), None,
                             msg="Could not find loader for needed package "
                                 "'{}' - This could indicate that the package "
                                 "is not installed or is not visible to the "
                                 "current Python interpreter "
                                 "session.".format(mod)) 
Example #23
Source File: __init__.py    From dagster with Apache License 2.0 5 votes vote down vote up
def is_module_available(module_name):
    if sys.version_info <= (3, 3):
        # python 3.3 and below
        import pkgutil

        loader = pkgutil.find_loader(module_name)
    elif sys.version_info >= (3, 4):
        # python 3.4 and above
        import importlib

        loader = importlib.util.find_spec(module_name)

    return loader is not None 
Example #24
Source File: S16_available_modules.py    From qkit with GNU General Public License v2.0 5 votes vote down vote up
def module_available(self, module_name):
        if module_name not in self.available_modules:
            self.available_modules[module_name] = bool(find_loader(module_name))
        return self.available_modules[module_name] 
Example #25
Source File: test_pkgutil.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_find_loader_avoids_emulation(self):
        with check_warnings() as w:
            self.assertIsNotNone(pkgutil.find_loader("sys"))
            self.assertIsNotNone(pkgutil.find_loader("os"))
            self.assertIsNotNone(pkgutil.find_loader("test.support"))
            self.assertEqual(len(w.warnings), 0) 
Example #26
Source File: test_pkgutil.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_find_loader_missing_module(self):
        name = 'totally bogus'
        loader = pkgutil.find_loader(name)
        self.assertIsNone(loader) 
Example #27
Source File: test_pkgutil.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_find_loader_avoids_emulation(self):
        with check_warnings() as w:
            self.assertIsNotNone(pkgutil.find_loader("sys"))
            self.assertIsNotNone(pkgutil.find_loader("os"))
            self.assertIsNotNone(pkgutil.find_loader("test.support"))
            self.assertEqual(len(w.warnings), 0) 
Example #28
Source File: test_pkgutil.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_find_loader_missing_module(self):
        name = 'totally bogus'
        loader = pkgutil.find_loader(name)
        self.assertIsNone(loader) 
Example #29
Source File: runnerbase.py    From spyder-unittest with MIT License 5 votes vote down vote up
def is_installed(cls):
        """
        Check whether test framework is installed.

        This function tests whether self.module is installed, but it does not
        import it.

        Returns
        -------
        bool
            True if framework is installed, False otherwise.
        """
        return find_spec_or_loader(cls.module) is not None 
Example #30
Source File: tools.py    From seisflows with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def package_exists(name):
    return find_loader(name)