Python imp.find_module() Examples

The following are 30 code examples for showing how to use imp.find_module(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module imp , or try the search function .

Example 1
Project: ALF   Author: blackberry   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def import_helper():
    from os.path import dirname
    import imp
    possible_libs = ["_alf_grammar.win32",
                     "_alf_grammar.ntoarm",
                     "_alf_grammar.ntox86",
                     "_alf_grammar.linux"]
    found_lib = False
    for i in possible_libs:
        fp = None
        try:
            fp, pathname, description = imp.find_module(i, [dirname(__file__)])
            _mod = imp.load_module("_alf_grammar", fp, pathname, description)
            found_lib = True
            break
        except ImportError:
            pass
        finally:
            if fp:
                fp.close()
    if not found_lib:
        raise ImportError("Failed to load _alf_grammar module")
    return _mod 
Example 2
Project: pywren-ibm-cloud   Author: pywren   File: module_dependency.py    License: Apache License 2.0 6 votes vote down vote up
def _is_relative_import(module_name, path):
        """Checks if import is relative. Returns True if relative, False if
        absolute, and None if import could not be found."""
        try:
            # Check within the restricted path of a (sub-)package
            imp.find_module(module_name, [path])
        except ImportError:
            pass
        else:
            return True

        try:
            # Check across all of sys.path
            imp.find_module(module_name)
        except ImportError:
            pass
        else:
            return False

        # Module could not be found on system due to:
        # 1. Import that doesn't exist. "Bad import".
        # 2. Since we're only scanning the AST, there's a good chance the
        #    import's inclusion is conditional, and would never be triggered.
        #    For example, an import specific to an OS.
        return None 
Example 3
Project: oscrypto   Author: wbond   File: coverage.py    License: MIT License 6 votes vote down vote up
def _load_package_tests(name):
    """
    Load the test classes from another modularcrypto package

    :param name:
        A unicode string of the other package name

    :return:
        A list of unittest.TestCase classes of the tests for the package
    """

    package_dir = os.path.join('..', name)
    if not os.path.exists(package_dir):
        return []

    tests_module_info = imp.find_module('tests', [package_dir])
    tests_module = imp.load_module('%s.tests' % name, *tests_module_info)
    return tests_module.test_classes() 
Example 4
Project: verge3d-blender-addon   Author: Soft8Soft   File: __init__.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _find_and_load_module(self, name, path=None):
        """
        Finds and loads it. But if there's a . in the name, handles it
        properly.
        """
        bits = name.split('.')
        while len(bits) > 1:
            # Treat the first bit as a package
            packagename = bits.pop(0)
            package = self._find_and_load_module(packagename, path)
            try:
                path = package.__path__
            except AttributeError:
                # This could be e.g. moves.
                flog.debug('Package {0} has no __path__.'.format(package))
                if name in sys.modules:
                    return sys.modules[name]
                flog.debug('What to do here?')

        name = bits[0]
        module_info = imp.find_module(name, path)
        return imp.load_module(name, *module_info) 
Example 5
Project: misp42splunk   Author: remg427   File: __init__.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def find_module(self, fullname, path=None):
        logger.debug('Running find_module: {0}...'.format(fullname))
        if '.' in fullname:
            parent, child = fullname.rsplit('.', 1)
            if path is None:
                loader = self.find_module(parent, path)
                mod = loader.load_module(parent)
                path = mod.__path__
            fullname = child

        # Perhaps we should try using the new importlib functionality in Python
        # 3.3: something like this?
        # thing = importlib.machinery.PathFinder.find_module(fullname, path)
        try:
            self.found = imp.find_module(fullname, path)
        except Exception as e:
            logger.debug('Py2Fixer could not find {0}')
            logger.debug('Exception was: {0})'.format(fullname, e))
            return None
        self.kind = self.found[-1][-1]
        if self.kind == imp.PKG_DIRECTORY:
            self.pathname = os.path.join(self.found[1], '__init__.py')
        elif self.kind == imp.PY_SOURCE:
            self.pathname = self.found[1]
        return self 
Example 6
Project: misp42splunk   Author: remg427   File: __init__.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def _find_and_load_module(self, name, path=None):
        """
        Finds and loads it. But if there's a . in the name, handles it
        properly.
        """
        bits = name.split('.')
        while len(bits) > 1:
            # Treat the first bit as a package
            packagename = bits.pop(0)
            package = self._find_and_load_module(packagename, path)
            try:
                path = package.__path__
            except AttributeError:
                # This could be e.g. moves.
                flog.debug('Package {0} has no __path__.'.format(package))
                if name in sys.modules:
                    return sys.modules[name]
                flog.debug('What to do here?')

        name = bits[0]
        module_info = imp.find_module(name, path)
        return imp.load_module(name, *module_info) 
Example 7
Project: misp42splunk   Author: remg427   File: __init__.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def find_module(self, fullname, path=None):
        logger.debug('Running find_module: {0}...'.format(fullname))
        if '.' in fullname:
            parent, child = fullname.rsplit('.', 1)
            if path is None:
                loader = self.find_module(parent, path)
                mod = loader.load_module(parent)
                path = mod.__path__
            fullname = child

        # Perhaps we should try using the new importlib functionality in Python
        # 3.3: something like this?
        # thing = importlib.machinery.PathFinder.find_module(fullname, path)
        try:
            self.found = imp.find_module(fullname, path)
        except Exception as e:
            logger.debug('Py2Fixer could not find {0}')
            logger.debug('Exception was: {0})'.format(fullname, e))
            return None
        self.kind = self.found[-1][-1]
        if self.kind == imp.PKG_DIRECTORY:
            self.pathname = os.path.join(self.found[1], '__init__.py')
        elif self.kind == imp.PY_SOURCE:
            self.pathname = self.found[1]
        return self 
Example 8
Project: linter-pylama   Author: AtomLinter   File: spec.py    License: MIT License 6 votes vote down vote up
def find_module(self, modname, module_parts, processed, submodule_path):
        """Find the given module

        Each finder is responsible for each protocol of finding, as long as
        they all return a ModuleSpec.

        :param str modname: The module which needs to be searched.
        :param list module_parts: It should be a list of strings,
                                  where each part contributes to the module's
                                  namespace.
        :param list processed: What parts from the module parts were processed
                               so far.
        :param list submodule_path: A list of paths where the module
                                    can be looked into.
        :returns: A ModuleSpec, describing how and where the module was found,
                  None, otherwise.
        """ 
Example 9
Project: autopython   Author: wing324   File: check_MySQLdb_module.py    License: GNU General Public License v3.0 6 votes vote down vote up
def check_mysqldb_modules():
# 检查MySQLdb模块是否存在
# check MySQLdb module exists
	try:
		imp.find_module('MySQLdb')
		found = 1
	except ImportError:
		found = 0 
	if found == 0:
		os.system('yum install -y MySQL-python')
		# 如果MySQLdb不存在,则使用yum安装MySQL-python
		# If MySQLdb doesn`t exist, then use Yum to install MySQL-python
	else:
		pass
		# 如果MySLQdb存在,则什么都不用做
		# If MySLQdb exists, there's nothing to do 
Example 10
Project: browserscope   Author: elsigh   File: sandbox.py    License: Apache License 2.0 6 votes vote down vote up
def find_module(self, fullname, path=None):
    if fullname in _WHITE_LIST_C_MODULES:
      return None
    if any(regex.match(fullname) for regex in self._enabled_regexes):
      return None
    _, _, submodule_name = fullname.rpartition('.')
    try:
      result = imp.find_module(submodule_name, path)
    except ImportError:
      return None
    f, _, description = result
    _, _, file_type = description
    if isinstance(f, file):
      f.close()
    if file_type == imp.C_EXTENSION:
      return self
    return None 
Example 11
Project: browserscope   Author: elsigh   File: sandbox.py    License: Apache License 2.0 6 votes vote down vote up
def find_module(self, fullname, path=None):
    if any(regex.match(fullname) for regex in self._enabled_regexes):
      return None
    _, _, submodule_name = fullname.rpartition('.')
    try:
      f, filename, description = imp.find_module(submodule_name, path)
    except ImportError:
      return None
    if f:
      f.close()
    _, _, file_type = description
    if (file_type in self._EXCLUDED_TYPES or
        stubs.FakeFile.is_file_accessible(filename) or
        (filename.endswith('.pyc') and
         os.path.exists(filename.replace('.pyc', '.py')))):
      return None
    return self 
Example 12
Project: browserscope   Author: elsigh   File: sandbox_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_load_with_path_hook(self):

    class DummyPathHook(object):

      def __init__(self, path):
        if path != 'dummy/path':
          raise ImportError

      def find_module(self, unused_fullname):
        return self

      def load_module(self, fullname):
        return imp.new_module('fake name: %s' % fullname)

    self.test_policies['distutils.util'] = sandbox.ModuleOverridePolicy(
        None, [], {}, default_pass_through=True)
    sys.path_hooks = [DummyPathHook]
    util = self.hook.load_module('distutils.util')
    self.assertEqual('fake name: distutils.util', util.__name__) 
Example 13
Project: browserscope   Author: elsigh   File: sandbox_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_load_with_path_hook_cant_find(self):

    class DummyPathHook(object):

      def __init__(self, path):
        if path != 'dummy/path':
          raise ImportError

      def find_module(self, unused_fullname):
        return None

      def load_module(self, fullname):
        raise ImportError

    self.test_policies['distutils.util'] = sandbox.ModuleOverridePolicy(
        None, [], {}, default_pass_through=True)
    sys.path_hooks = [DummyPathHook]
    util = self.hook.load_module('distutils.util')
    self.assertEqual('distutils.util', util.__name__) 
Example 14
Project: browserscope   Author: elsigh   File: dev_appserver_import_hook.py    License: Apache License 2.0 6 votes vote down vote up
def SetAllowedModule(name):
    """Allow the use of a module based on where it is located.

    Meant to be used by use_library() so that it has a link back into the
    trusted part of the interpreter.

    Args:
      name: Name of the module to allow.
    """
    stream, pathname, description = imp.find_module(name)
    pathname = os.path.normcase(os.path.abspath(pathname))
    if stream:
      stream.close()
      FakeFile.ALLOWED_FILES.add(pathname)
      FakeFile.ALLOWED_FILES.add(os.path.realpath(pathname))
    else:
      assert description[2] == imp.PKG_DIRECTORY
      if pathname.startswith(SITE_PACKAGES):
        FakeFile.ALLOWED_SITE_PACKAGE_DIRS.add(pathname)
        FakeFile.ALLOWED_SITE_PACKAGE_DIRS.add(os.path.realpath(pathname))
      else:
        FakeFile.ALLOWED_DIRS.add(pathname)
        FakeFile.ALLOWED_DIRS.add(os.path.realpath(pathname)) 
Example 15
Project: jbox   Author: jpush   File: depends.py    License: MIT License 6 votes vote down vote up
def find_module(module, paths=None):
    """Just like 'imp.find_module()', but with package support"""

    parts = module.split('.')

    while parts:
        part = parts.pop(0)
        f, path, (suffix,mode,kind) = info = imp.find_module(part, paths)

        if kind==PKG_DIRECTORY:
            parts = parts or ['__init__']
            paths = [path]

        elif parts:
            raise ImportError("Can't find %r in %s" % (parts,module))

    return info 
Example 16
Project: jbox   Author: jpush   File: _compat.py    License: MIT License 6 votes vote down vote up
def _check_if_pyc(fname):
    """Return True if the extension is .pyc, False if .py
    and None if otherwise"""
    from imp import find_module
    from os.path import realpath, dirname, basename, splitext

    # Normalize the file-path for the find_module()
    filepath = realpath(fname)
    dirpath = dirname(filepath)
    module_name = splitext(basename(filepath))[0]

    # Validate and fetch
    try:
        fileobj, fullpath, (_, _, pytype) = find_module(module_name, [dirpath])
    except ImportError:
        raise IOError("Cannot find config file. "
                      "Path maybe incorrect! : {0}".format(filepath))
    return pytype, fileobj, fullpath 
Example 17
Project: CapTipper   Author: omriher   File: CTPlugin.py    License: GNU General Public License v3.0 6 votes vote down vote up
def init_plugins():
    p_files = glob.glob(CTCore.plugins_folder + "*.py")
    for p in p_files:
        p_full = os.path.join(os.path.dirname(os.path.realpath(__file__)),p)
        (path, name) = os.path.split(p_full)
        (name, ext) = os.path.splitext(name)

        (p_file, filename, data) = imp.find_module(name, [path])
        mod = imp.load_module(name, p_file, filename, data)

        for name, value in inspect.getmembers(mod):
            if inspect.isclass(value):
                if issubclass(value, ConsolePlugin) and value is not ConsolePlugin:
                    p_num = len(CTCore.plugins)
                    CTCore.plugins.append(namedtuple('Plugin', ['id', 'name','module', 'description']))
                    CTCore.plugins[p_num].id = p_num
                    CTCore.plugins[p_num].name = name
                    CTCore.plugins[p_num].module = value
                    CTCore.plugins[p_num].description = value.description 
Example 18
Project: google-assistant-hotword-raspi   Author: warchildmd   File: snowboydetect.py    License: MIT License 5 votes vote down vote up
def swig_import_helper():
        from os.path import dirname
        import imp
        fp = None
        try:
            fp, pathname, description = imp.find_module('_snowboydetect', [dirname(__file__)])
        except ImportError:
            import _snowboydetect
            return _snowboydetect
        if fp is not None:
            try:
                _mod = imp.load_module('_snowboydetect', fp, pathname, description)
            finally:
                fp.close()
            return _mod 
Example 19
Project: oscrypto   Author: wbond   File: __init__.py    License: MIT License 5 votes vote down vote up
def _import_from(mod, path, mod_dir=None):
    """
    Imports a module from a specific path

    :param mod:
        A unicode string of the module name

    :param path:
        A unicode string to the directory containing the module

    :param mod_dir:
        If the sub directory of "path" is different than the "mod" name,
        pass the sub directory as a unicode string

    :return:
        None if not loaded, otherwise the module
    """

    if mod_dir is None:
        mod_dir = mod

    if not os.path.exists(path):
        return None

    if not os.path.exists(os.path.join(path, mod_dir)):
        return None

    try:
        mod_info = imp.find_module(mod_dir, [path])
        return imp.load_module(mod, *mod_info)
    except ImportError:
        return None 
Example 20
Project: verge3d-blender-addon   Author: Soft8Soft   File: __init__.py    License: GNU General Public License v3.0 5 votes vote down vote up
def find_module(self, fullname, path=None):
        # Handles hierarchical importing: package.module.module2
        new_base_names = set([s.split('.')[0] for s in self.new_to_old])
        # Before v0.12: Was: if fullname in set(self.old_to_new) | new_base_names:
        if fullname in new_base_names:
            return self
        return None 
Example 21
Project: misp42splunk   Author: remg427   File: __init__.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def find_module(self, fullname, path=None):
        # Handles hierarchical importing: package.module.module2
        new_base_names = set([s.split('.')[0] for s in self.new_to_old])
        # Before v0.12: Was: if fullname in set(self.old_to_new) | new_base_names:
        if fullname in new_base_names:
            return self
        return None 
Example 22
Project: misp42splunk   Author: remg427   File: __init__.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def find_module(self, fullname, path=None):
        # Handles hierarchical importing: package.module.module2
        new_base_names = set([s.split('.')[0] for s in self.new_to_old])
        # Before v0.12: Was: if fullname in set(self.old_to_new) | new_base_names:
        if fullname in new_base_names:
            return self
        return None 
Example 23
Project: mdentropy   Author: msmbuilder   File: basesetup.py    License: MIT License 5 votes vote down vote up
def check_dependencies(dependencies):
    def module_exists(dep):
        try:
            imp.find_module(dep)
            return True
        except ImportError:
            return False

    for dep in dependencies:
        if len(dep) == 1:
            import_name, pkg_name = dep[0], dep[0]
        elif len(dep) == 2:
            import_name, pkg_name = dep
        else:
            raise ValueError(dep)

        if not module_exists(import_name):
            lines = [
                '-' * 50,
                'Warning: This package requires %r. Try' % import_name,
                '',
                '  $ conda install %s' % pkg_name,
                '',
                'or:',
                '',
                '  $ pip install %s' % pkg_name,
                '-' * 50,
            ]
            print(os.linesep.join(lines), file=sys.stderr) 
Example 24
Project: recipes-py   Author: luci   File: recipe_module_importer.py    License: Apache License 2.0 5 votes vote down vote up
def find_module(self, fullname, path=None):  # pylint: disable=unused-argument
    if fullname == self.PREFIX or fullname.startswith(self.PREFIX + '.'):
      toks = fullname.split('.')
      if 1 <= len(toks) <= 3:
        # We should definitely handle all of these.
        # RECIPE_MODULES
        # RECIPE_MODULES.<repo_name>
        # RECIPE_MODULES.<repo_name>.<module_name>
        return self
      if len(toks) > 3:
        # We can only be guaranteed to handle this if such a file exists.
        #
        # For example, if api.py in a module does `import base64`, python will
        # first try:
        #
        #   RECIPE_MODULES.<repo_name>.<module_name>.base64
        #
        # So we should only return ourselves as a loader if we can ACTUALLY
        # import the requested module.
        repo_name = toks[1]
        module_name = toks[2]
        mod_dir = self._recipe_deps.repos[repo_name].modules[module_name].path
        target = os.path.join(mod_dir, *toks[3:])
        if (os.path.isdir(target) and
            os.path.isfile(os.path.join(target, '__init__.py'))):
          # This is a module in the recipe package.
          return self
        elif os.path.isfile(target + '.py'):
          # This is a python file in the recipe package.
          return self

      # Otherwise, we'll have to let python resolve this along e.g. sys.path
      # and builtins.
      return None 
Example 25
Project: AerialDetection   Author: dingjiansw101   File: polyiou.py    License: Apache License 2.0 5 votes vote down vote up
def swig_import_helper():
        from os.path import dirname
        import imp
        fp = None
        try:
            fp, pathname, description = imp.find_module('_polyiou', [dirname(__file__)])
        except ImportError:
            import _polyiou
            return _polyiou
        if fp is not None:
            try:
                _mod = imp.load_module('_polyiou', fp, pathname, description)
            finally:
                fp.close()
            return _mod 
Example 26
Project: pyspelling   Author: facelessuser   File: setup.py    License: MIT License 5 votes vote down vote up
def get_version():
    """Get version and version_info without importing the entire module."""

    path = os.path.join(os.path.dirname(__file__), 'pyspelling')
    fp, pathname, desc = imp.find_module('__meta__', [path])
    try:
        meta = imp.load_module('__meta__', fp, pathname, desc)
        return meta.__version__, meta.__version_info__._get_dev_status()
    finally:
        fp.close() 
Example 27
Project: linter-pylama   Author: AtomLinter   File: modutils.py    License: MIT License 5 votes vote down vote up
def is_relative(modname, from_file):
    """return true if the given module name is relative to the given
    file name

    :type modname: str
    :param modname: name of the module we are interested in

    :type from_file: str
    :param from_file:
      path of the module from which modname has been imported

    :rtype: bool
    :return:
      true if the module has been imported relatively to `from_file`
    """
    if not os.path.isdir(from_file):
        from_file = os.path.dirname(from_file)
    if from_file in sys.path:
        return False
    try:
        stream, _, _ = imp.find_module(modname.split('.')[0], [from_file])

        # Close the stream to avoid ResourceWarnings.
        if stream:
            stream.close()
        return True
    except ImportError:
        return False


# internal only functions ##################################################### 
Example 28
Project: linter-pylama   Author: AtomLinter   File: spec.py    License: MIT License 5 votes vote down vote up
def find_module(self, modname, module_parts, processed, submodule_path):
        if submodule_path is not None:
            submodule_path = list(submodule_path)
        try:
            stream, mp_filename, mp_desc = imp.find_module(modname, submodule_path)
        except ImportError:
            return None

        # Close resources.
        if stream:
            stream.close()

        return ModuleSpec(name=modname, location=mp_filename,
                          module_type=_imp_type_to_module_type(mp_desc[2])) 
Example 29
Project: linter-pylama   Author: AtomLinter   File: spec.py    License: MIT License 5 votes vote down vote up
def find_module(self, modname, module_parts, processed, submodule_path):
        if processed:
            modname = '.'.join(processed + [modname])
        if util.is_namespace(modname) and modname in sys.modules:
            submodule_path = sys.modules[modname].__path__
            return ModuleSpec(name=modname, location='',
                              origin='namespace',
                              module_type=ModuleType.PY_NAMESPACE,
                              submodule_search_locations=submodule_path)
        return None 
Example 30
Project: linter-pylama   Author: AtomLinter   File: spec.py    License: MIT License 5 votes vote down vote up
def find_module(self, modname, module_parts, processed, submodule_path):
        spec = importlib.machinery.PathFinder.find_spec(modname, path=submodule_path)
        if spec:
            location = spec.origin if spec.origin != 'namespace' else None
            module_type = ModuleType.PY_NAMESPACE if spec.origin == 'namespace' else None
            spec = ModuleSpec(name=spec.name, location=location,
                              origin=spec.origin, module_type=module_type,
                              submodule_search_locations=list(spec.submodule_search_locations
                                                              or []))
        return spec