sys.modules.get

Here are the examples of the python api sys.modules.get taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: pluginbase
Source File: test_basics.py
View license
def test_persist(base):
    new_source = base.make_plugin_source(searchpath=['./plugins'],
                                         persist=True)
    mod_name = new_source.mod.__name__
    assert sys.modules.get(mod_name) is new_source.mod

    with new_source:
        from dummy.plugins import hello

    new_source = None
    assert sys.modules.get(mod_name) is not None
    assert hello.import_self is not None
    sys.modules[mod_name].__pluginbase_state__.source.cleanup()
    assert sys.modules.get(mod_name) is None
    assert hello.import_self is None

Example 2

View license
    def set_current_module(self, module):
        mod = sys.modules.get(module)
        if mod is not None:
            _debug_write('Setting module to ' + module)
            if sys.platform == 'cli':
                self.exec_mod = clr.GetClrType(type(sys)).GetProperty('Scope', System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(sys, ())
            else:
                self.exec_mod = mod
        else:
            _debug_write('Unknown module ' + module)

Example 3

View license
    def add_info_extractor(self, ie):
        if ie.IE_NAME in _BLACKLIST:
            return
        # Fix ##################################################################
        module = sys.modules.get(ie.__module__)
        if module:
            if hasattr(module, 'unified_strdate'):
                module.unified_strdate = _unified_strdate_wrap
            if hasattr(module, 'date_from_str'):
                module.date_from_str = _date_from_str_wrap
        ########################################################################
        youtube_dl.YoutubeDL.add_info_extractor(self, ie)

Example 4

Project: powerline
Source File: __init__.py
View license
	def __enter__(self):
		self.old = sys.modules.get(self.name)
		if not self.old:
			try:
				self.old = __import__(self.name)
			except ImportError:
				pass
		sys.modules[self.name] = self.new

Example 5

Project: imagrium
Source File: pycimport.py
View license
def __makeModule(name, code, path):
    module = sys.modules.get(name)
    if not module:
        module = sys.modules[name] = imp.new_module(name)
    module.__file__ = path
    exec code in module.__dict__
    return module

Example 6

Project: QMarkdowner
Source File: ImportManager.py
View license
    def setThreaded(self):
        thread = sys.modules.get('thread', None)
        if thread and not self.threaded:
            self.threaded = 1
            self.rlock = thread.allocate_lock()
            self._get_ident = thread.get_ident

Example 7

Project: hl7apy
Source File: __init__.py
View license
def load_library(version):
    """
    Load the correct module according to the version

    :type version: ``str``
    :param version: the version of the library to be loaded (e.g. '2.6')
    :rtype: module object
    """
    check_version(version)
    module_name = SUPPORTED_LIBRARIES[version]
    lib = sys.modules.get(module_name)
    if lib is None:
        lib = importlib.import_module(module_name)
    return lib

Example 8

Project: exabgp
Source File: objgraph.py
View license
def is_proper_module(obj):
    """
    Returns ``True`` if ``obj`` can be treated like a garbage collector root.

    That is, if ``obj`` is a module that is in ``sys.modules``.

    >>> import types
    >>> is_proper_module([])
    False
    >>> is_proper_module(types)
    True
    >>> is_proper_module(types.ModuleType('foo'))
    False

    .. versionadded:: 1.8
    """
    return (inspect.ismodule(obj) and
            obj is sys.modules.get(getattr(obj, '__name__', None)))

Example 9

Project: volatility
Source File: obj.py
View license
    def load_vtypes(self):
        """ Identifies the module from which to load the vtypes 
        
            Eventually this could do the importing directly, and avoid having
            the profiles loaded in memory all at once.
        """
        ntvar = self.metadata.get('memory_model', '32bit')
        self.native_types = copy.deepcopy(self.native_mapping.get(ntvar))

        vtype_module = self.metadata.get('vtype_module', None)
        if not vtype_module:
            debug.warning("No vtypes specified for this profile")
        else:
            module = sys.modules.get(vtype_module, None)

            # Try to locate the _types dictionary
            for i in dir(module):
                if i.endswith('_types'):
                    self.vtypes.update(getattr(module, i))

Example 10

Project: pyp2rpm
Source File: nose.py
View license
def pytest_runtest_makereport(__multicall__, item, call):
    SkipTest = getattr(sys.modules.get('nose', None), 'SkipTest', None)
    if SkipTest:
        if call.excinfo and call.excinfo.errisinstance(SkipTest):
            # let's substitute the excinfo with a py.test.skip one
            call2 = call.__class__(lambda: py.test.skip(str(call.excinfo.value)), call.when)
            call.excinfo = call2.excinfo

Example 11

Project: bashlint
Source File: bashlint.py
View license
    def _load_checkers(self):
        """Load checkers from the current module."""
        checkers = []
        current_module = sys.modules.get(__name__)
        if current_module is not None:
            for name, func in inspect.getmembers(current_module,
                                                 inspect.isfunction):
                if name.startswith('checker'):
                    checkers.append(func)

        if self._options.verbose > 1:
            print("Loaded %s checker(s)." % len(checkers))

        return checkers

Example 12

Project: WAPT
Source File: utils.py
View license
def _get_hasher(algorithm):
    """wrapper to call django.contrib.auth.hashers:get_hasher()"""
    import sys
    module = sys.modules.get("passlib.ext.django.models")
    if module is None:
        # we haven't patched django, so just import directly
        from django.contrib.auth.hashers import get_hasher
    else:
        # we've patched django, so have to use patch manager to retrieve
        # original get_hasher() function...
        get_hasher = module._manager.getorig("django.contrib.auth.hashers:get_hasher")
    return get_hasher(algorithm)

Example 13

Project: ntfy
Source File: test_integration.py
View license
    @patch(builtin_module + '.open', mock_open())
    @patch('ntfy.config.yaml.load')
    def test_linux(self, mock_yamlload):
        old_dbus = modules.get('dbus')
        modules['dbus'] = MagicMock()
        try:
            mock_yamlload.return_value = {'backends': ['linux'], }
            self.assertEqual(0, ntfy_main(['send', 'foobar']))
        finally:
            if old_dbus is not None:
                modules['dbus'] = old_dbus

Example 14

Project: PFramer
Source File: pluginbase.py
View license
def _discover_space(name, globals):
    try:
        return _local.space_stack[-1]
    except (AttributeError, IndexError):
        pass

    if '__pluginbase_state__' in globals:
        return globals['__pluginbase_state__'].source

    mod_name = globals.get('__name__')
    if mod_name is not None and \
       mod_name.startswith(_internalspace.__name__ + '.'):
        end = mod_name.find('.', len(_internalspace.__name__) + 1)
        space = sys.modules.get(mod_name[:end])
        if space is not None:
            return space.__pluginbase_state__.source

Example 15

Project: nightmare
Source File: dcode.py
View license
    def load_module(self, fullname):
        mod = sys.modules.get(fullname)
        if mod == None:
            mod = imp.new_module(fullname)
            sys.modules[fullname] = mod
            mod.__file__ = self.filename
            mod.__loader__ = self
            if self.path != None:
                mod.__path__ = [self.path]

            exec self.fbytes in mod.__dict__

        return mod

Example 16

Project: cylc
Source File: test_core.py
View license
    def skip_if_bad_cookies(self):
        """
        cookies module fails to reject invalid cookies
        https://github.com/cherrypy/cherrypy/issues/1405
        """
        cookies = sys.modules.get('http.cookies')
        _is_legal_key = getattr(cookies, '_is_legal_key', lambda x: False)
        if not _is_legal_key(','):
            return
        issue = 'http://bugs.python.org/issue26302'
        tmpl = "Broken cookies module ({issue})"
        self.skip(tmpl.format(**locals()))

Example 17

Project: logbook
Source File: base.py
View license
    @cached_property
    def process_name(self):
        """The name of the process in which the record has been created."""
        # Errors may occur if multiprocessing has not finished loading
        # yet - e.g. if a custom import hook causes third-party code
        # to run when multiprocessing calls import. See issue 8200
        # for an example
        mp = sys.modules.get('multiprocessing')
        if mp is not None:  # pragma: no cover
            try:
                return mp.current_process().name
            except Exception:
                pass

Example 18

Project: authomatic
Source File: __init__.py
View license
    @property
    def type_id(self):
        """
        A short string representing the provider implementation id used for
        serialization of :class:`.Credentials` and to identify the type of provider in JavaScript.
        The part before hyphen denotes the type of the provider, the part after hyphen denotes the class id
        e.g. ``oauth2.Facebook.type_id = '2-5'``, ``oauth1.Twitter.type_id = '1-5'``.
        """
        
        cls = self.__class__
        mod = sys.modules.get(cls.__module__)
        
        return str(self.PROVIDER_TYPE_ID) + '-' + str(mod.PROVIDER_ID_MAP.index(cls))

Example 19

Project: python-ubersmith
Source File: test_calls.py
View license
def setup_module(module):
    """Import all call modules."""
    bases = set(method.split('.', 1)[0] for method in METHODS)
    for base in bases:
        mod_name = '.'.join(['ubersmith', base])
        if not sys.modules.get(mod_name):
            __import__(mod_name)

Example 20

Project: sublime-robot-plugin
Source File: importer.py
View license
    def _wrong_module_imported(self, name, importing_from, importing_package):
        module = sys.modules.get(name)
        if not module:
            return False
        source = getattr(module, '__file__', None)
        if not source:  # play safe (occurs at least with java based modules)
            return True
        imported_from, imported_package = self._get_import_information(source)
        return ((normpath(importing_from), importing_package) !=
                (normpath(imported_from), imported_package))

Example 21

Project: batpod
Source File: batpod.py
View license
    def get_root(self):
        mod = sys.modules.get(self.import_name)
        if mod is not None and self.import_name != '__main__':
            return os.path.dirname(os.path.abspath(mod.__file__))
        else:
            return os.getcwd()

Example 22

Project: pytest
Source File: nose.py
View license
def get_skip_exceptions():
    skip_classes = set()
    for module_name in ('unittest', 'unittest2', 'nose'):
        mod = sys.modules.get(module_name)
        if hasattr(mod, 'SkipTest'):
            skip_classes.add(mod.SkipTest)
    return tuple(skip_classes)

Example 23

Project: Piped
Source File: log.py
View license
    def format(self, record):
        if not self.repl_provider:
            self.__class__.repl_provider = sys.modules.get(self.repl_provider_module, None)

        formatted = super(REPLAwareUTCFormatter, self).format(record)
        if self.repl_provider and getattr(self.repl_provider, self.repl_provider_class).running:
            formatted = formatted.replace('\n', '\n\r\r') + '\r\r'
        return formatted

Example 24

Project: vivisect
Source File: dcode.py
View license
    def load_module(self, fullname):
        mod = sys.modules.get(fullname)
        if mod == None:
            mod = imp.new_module(fullname)
            sys.modules[fullname] = mod
            mod.__file__ = self.filename
            mod.__loader__ = self
            if self.path != None:
                mod.__path__ = [self.path]

            exec toutf8(self.fbytes) in mod.__dict__

        return mod

Example 25

Project: pytest
Source File: compat.py
View license
def num_mock_patch_args(function):
    """ return number of arguments used up by mock arguments (if any) """
    patchings = getattr(function, "patchings", None)
    if not patchings:
        return 0
    mock = sys.modules.get("mock", sys.modules.get("unittest.mock", None))
    if mock is not None:
        return len([p for p in patchings
                        if not p.attribute_name and p.new is mock.DEFAULT])
    return len(patchings)

Example 26

Project: fe
Source File: command.py
View license
	def __call__(self, *args, **kw):
		storage = (
			sys.modules.get('__context__'),
			sys.modules.get('__main__'),
			sys.argv,
			os.environ.copy(),
		)
		try:
			return self._call(*args, **kw)
		finally:
			sys.modules['__context__'], \
			sys.modules['__main__'], \
			sys.argv, os.environ = storage

Example 27

Project: backdoorme
Source File: splitbrain.py
View license
def _importer(modname, *args, **kwargs):
    if not hasattr(router, "conn"):
        return _orig_import(modname, *args, **kwargs)
    existing = sys.modules.get(modname, None)
    if type(existing) is RoutedModule:
        return existing
    
    mod = router.conn.modules[modname]
    if existing and type(existing) is RemoteModule:
        return existing
    rmod = RemoteModule(mod)
    sys.modules[modname] = rmod
    return rmod

Example 28

Project: backdoorme
Source File: splitbrain.py
View license
def _importer(modname, *args, **kwargs):
    if not hasattr(router, "conn"):
        return _orig_import(modname, *args, **kwargs)
    existing = sys.modules.get(modname, None)
    if type(existing) is RoutedModule:
        return existing
    
    mod = router.conn.modules[modname]
    if existing and type(existing) is RemoteModule:
        return existing
    rmod = RemoteModule(mod)
    sys.modules[modname] = rmod
    return rmod

Example 29

Project: ntfy
Source File: test_integration.py
View license
    @patch(builtin_module + '.open', mock_open())
    @patch('ntfy.backends.default.platform', 'linux')
    @patch('ntfy.config.yaml.load')
    def test_default(self, mock_yamlload):
        old_dbus = modules.get('dbus')
        modules['dbus'] = MagicMock()
        try:
            mock_yamlload.return_value = {'backends': ['default'], }
            self.assertEqual(0, ntfy_main(['send', 'foobar']))
        finally:
            if old_dbus is not None:
                modules['dbus'] = old_dbus

Example 30

Project: confab
Source File: files.py
View license
def _import_string(module_name, content):
    """
    Load python module from an in-memory string without reloading.
    """

    # assign module a name that's not likely to conflict
    safe_name = _safe_name(module_name, content)

    # check if module is already loaded
    existing = sys.modules.get(safe_name)
    if existing:
        return existing

    # try to load module
    module = imp.new_module(safe_name)
    exec content in module.__dict__
    return module

Example 31

Project: apptools
Source File: naming_traits.py
View license
    def find_class ( self ):
        module = self.module
        aClass = self.aClass
        col    = aClass.rfind( '.' )
        if col >= 0:
            module = aClass[ : col ]
            aClass = aClass[ col + 1: ]
        theClass = getattr( sys.modules.get( module ), aClass, None )
        if (theClass is None) and (col >= 0):
            try:
                theClass = getattr( __import__( module ), aClass, None )
            except:
                pass
        return theClass

Example 32

Project: Camelot
Source File: entity.py
View license
    def set_entity( self, entity ):
        self.entity = entity
        self.module = sys.modules.get( entity.__module__ )
        self.tablename = entity.__tablename__
        #
        # verify if a primary key was set manually
        #
        for key, value in entity.__dict__.items():
            if isinstance( value, schema.Column ):
                if value.primary_key:
                    self.has_pk = True
            if isinstance( value, EntityBuilder ):
                self.builders.append( value )
            if isinstance( value, Property ):
                value.entity = entity
                value.name = key
        # execute the builders in the order they were created
        self.builders.sort( key = lambda b:b.counter )

Example 33

Project: QSTK
Source File: docintrospecter.py
View license
def verify_name(value, dotted_name):
    """
    Verify the name.  E.g., if it's a nested class, then we won't be
    able to find it with the name we constructed.
    """
    if dotted_name is UNKNOWN: return UNKNOWN
    if len(dotted_name) == 1 and hasattr(__builtin__, dotted_name[0]):
        return dotted_name
    named_value = sys.modules.get(dotted_name[0])
    if named_value is None: return UNKNOWN
    for identifier in dotted_name[1:]:
        try: named_value = getattr(named_value, identifier)
        except: return UNKNOWN
    if value is named_value:
        return dotted_name
    else:
        return UNKNOWN

Example 34

Project: chronology
Source File: cloudpickle.py
View license
    def save_ufunc(self, obj):
        """Hack function for saving numpy ufunc objects"""
        name = obj.__name__
        for tst_mod_name in self.numpy_tst_mods:
            tst_mod = sys.modules.get(tst_mod_name, None)
            if tst_mod:
                if name in tst_mod.__dict__:
                    self.save_reduce(_getobject, (tst_mod_name, name))
                    return
        raise pickle.PicklingError('cannot save %s. Cannot resolve what module it is defined in' % str(obj))

Example 35

Project: python-gflags
Source File: _helpers.py
View license
def GetModuleObjectAndName(globals_dict):
  """Returns the module that defines a global environment, and its name.

  Args:
    globals_dict: A dictionary that should correspond to an environment
      providing the values of the globals.

  Returns:
    _ModuleObjectAndName - pair of module object & module name.
    Returns (None, None) if the module could not be identified.
  """
  name = globals_dict.get('__name__', None)
  module = sys.modules.get(name, None)
  # Pick a more informative name for the main module.
  return _ModuleObjectAndName(module,
                              (sys.argv[0] if name == '__main__' else name))

Example 36

Project: DAMM
Source File: obj.py
View license
    def load_vtypes(self):
        """ Identifies the module from which to load the vtypes 
        
            Eventually this could do the importing directly, and avoid having
            the profiles loaded in memory all at once.
        """
        ntvar = self.metadata.get('memory_model', '32bit')
        self.native_types = copy.deepcopy(self.native_mapping.get(ntvar))

        vtype_module = self.metadata.get('vtype_module', None)
        if not vtype_module:
            debug.warning("No vtypes specified for this profile")
        else:
            module = sys.modules.get(vtype_module, None)

            # Try to locate the _types dictionary
            for i in dir(module):
                if i.endswith('_types'):
                    self.vtypes.update(getattr(module, i))

Example 37

Project: signedimp
Source File: bootstrap.py
View license
    def _create_module(self,fullname,code,filename,is_package):
        """Create a new module by executing the given code object."""
        created = False
        mod = sys.modules.get(fullname)
        if not mod:
            mod = imp.new_module(fullname)
            sys.modules[fullname] = mod
            created = True
        try:
            mod.__file__ = filename
            mod.__loader__ = self
            if is_package:
                mod.__path__ = [os.path.dirname(filename)]
            exec code in mod.__dict__
        except Exception:
            if created:
                sys.modules.pop(fullname,None)
            raise
        return mod

Example 38

Project: vsm
Source File: zipfile.py
View license
def _inject(module, new_module):
    if imp.lock_held() is True:
        if sys.modules.get(module):
            del sys.modules[module]
        sys.modules[new_module] = __import__(new_module)
        sys.modules[module] = __import__(new_module)

Example 39

Project: chipsec
Source File: test_site.py
View license
    def cleanup(self, prep=False):
        """Make sure that the .pth file is deleted, self.imported is not in
        sys.modules, and that both self.good_dirname and self.bad_dirname are
        not existing directories."""
        if os.path.exists(self.file_path):
            os.remove(self.file_path)
        if prep:
            self.imported_module = sys.modules.get(self.imported)
            if self.imported_module:
                del sys.modules[self.imported]
        else:
            if self.imported_module:
                sys.modules[self.imported] = self.imported_module
        if os.path.exists(self.good_dir_path):
            os.rmdir(self.good_dir_path)
        if os.path.exists(self.bad_dir_path):
            os.rmdir(self.bad_dir_path)

Example 40

Project: nvda
Source File: logHandler.py
View license
	def handle(self,record):
		# versionInfo must be imported after the language is set. Otherwise, strings won't be in the correct language.
		# Therefore, don't import versionInfo if it hasn't already been imported.
		versionInfo = sys.modules.get("versionInfo")
		# Only play the error sound if this is a test version.
		shouldPlayErrorSound = versionInfo and versionInfo.isTestVersion
		if record.levelno>=logging.CRITICAL:
			try:
				winsound.PlaySound("SystemHand",winsound.SND_ALIAS)
			except:
				pass
		elif record.levelno>=logging.ERROR and shouldPlayErrorSound:
			import nvwave
			try:
				nvwave.playWaveFile("waves\\error.wav")
			except:
				pass
		return logging.StreamHandler.handle(self,record)

Example 41

Project: ibis
Source File: cloudpickle.py
View license
    def save_ufunc(self, obj):
        """Hack function for saving numpy ufunc objects"""
        name = obj.__name__
        for tst_mod_name in self.numpy_tst_mods:
            tst_mod = sys.modules.get(tst_mod_name, None)
            if tst_mod:
                if name in tst_mod.__dict__:
                    self.save_reduce(_getobject, (tst_mod_name, name))
                    return
        raise pickle.PicklingError('cannot save %s. Cannot resolve what module it is defined in' % str(obj))

Example 42

Project: luci-py
Source File: subcommand.py
View license
def _get_color_module():
  """Returns the colorama module if available.

  If so, assumes colors are supported and return the module handle.
  """
  return sys.modules.get('colorama') or sys.modules.get('third_party.colorama')

Example 43

Project: brython
Source File: test_site.py
View license
    def cleanup(self, prep=False):
        """Make sure that the .pth file is deleted, self.imported is not in
        sys.modules, and that both self.good_dirname and self.bad_dirname are
        not existing directories."""
        if os.path.exists(self.file_path):
            os.remove(self.file_path)
        if prep:
            self.imported_module = sys.modules.get(self.imported)
            if self.imported_module:
                del sys.modules[self.imported]
        else:
            if self.imported_module:
                sys.modules[self.imported] = self.imported_module
        if os.path.exists(self.good_dir_path):
            os.rmdir(self.good_dir_path)
        if os.path.exists(self.bad_dir_path):
            os.rmdir(self.bad_dir_path)

Example 44

Project: cgstudiomap
Source File: utils.py
View license
def _get_hasher(algorithm):
    """wrapper to call django.contrib.auth.hashers:get_hasher()"""
    import sys
    module = sys.modules.get("passlib.ext.django.models")
    if module is None:
        # we haven't patched django, so just import directly
        from django.contrib.auth.hashers import get_hasher
    else:
        # we've patched django, so have to use patch manager to retrieve
        # original get_hasher() function...
        get_hasher = module._manager.getorig("django.contrib.auth.hashers:get_hasher")
    return get_hasher(algorithm)

Example 45

View license
def mock(mod_path):
    name_list = mod_path.split('.')
    child_name = name_list.pop()
    child_mod = sys.modules.get(mod_path, types.ModuleType(child_name))
    if len(name_list) == 0:  # child_name is left-most basic module
        if child_name not in sys.modules:
            sys.modules[child_name] = child_mod
        return sys.modules[child_name]
    else:
        # New or existing child becomes parent
        recurse_path = ".".join(name_list)
        parent_mod = mock(recurse_path)
        if not hasattr(sys.modules[recurse_path], child_name):
            setattr(parent_mod, child_name, child_mod)
            # full-name also points at child module
            sys.modules[mod_path] = child_mod
        return sys.modules[mod_path]

Example 46

Project: sublimelint
Source File: persist.py
View license
    def update_settings(self):
        settings = merge_user_settings(self.sub_settings)
        self.settings.clear()
        self.settings.update(settings)

        # reattach settings objects to linters
        import sys
        linter = sys.modules.get('lint.linter')
        if linter and hasattr(linter, 'persist'):
            linter.Linter.reload()

Example 47

Project: luci-py
Source File: subcommand.py
View license
def _get_color_module():
  """Returns the colorama module if available.

  If so, assumes colors are supported and return the module handle.
  """
  return sys.modules.get('colorama') or sys.modules.get('third_party.colorama')

Example 48

Project: datafari
Source File: test_ensurepip.py
View license
@contextlib.contextmanager
def fake_pip(version=ensurepip._PIP_VERSION):
    if version is None:
        pip = None
    else:
        class FakePip():
            __version__ = version
        pip = FakePip()
    sentinel = object()
    orig_pip = sys.modules.get("pip", sentinel)
    sys.modules["pip"] = pip
    try:
        yield pip
    finally:
        if orig_pip is sentinel:
            del sys.modules["pip"]
        else:
            sys.modules["pip"] = orig_pip

Example 49

Project: unrpyc
Source File: magic.py
View license
    def __getattr__(self, name):
        modname = self.__name__ + "." + name
        mod = sys.modules.get(modname, None)
        if mod is None:
            try:
                __import__(modname)
            except:
                mod = FakePackage(modname)
            else:
                mod = sys.modules[modname]
        return mod

Example 50

Project: vivisect
Source File: __init__.py
View license
def getParserModule(fmt):
    mname = "vivisect.parsers.%s" % fmt
    mod = sys.modules.get(mname)
    if mod == None:
        __import__(mname)
        mod = sys.modules[mname]
    return mod