sys.modules.copy

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

40 Examples 7

Example 1

Project: pymo Source File: CallTips.py
Function: get_entity
    def get_entity(self, name):
        "Lookup name in a namespace spanning sys.modules and __main.dict__"
        if name:
            namespace = sys.modules.copy()
            namespace.update(__main__.__dict__)
            try:
                return eval(name, namespace)
            except (NameError, AttributeError):
                return None

Example 2

Project: pymo Source File: test_sax.py
    def test_sf_1511497(self):
        # Bug report: http://www.python.org/sf/1511497
        import sys
        old_modules = sys.modules.copy()
        for modname in sys.modules.keys():
            if modname.startswith("xml."):
                del sys.modules[modname]
        try:
            import xml.sax.expatreader
            module = xml.sax.expatreader
            self.assertEqual(module.__name__, "xml.sax.expatreader")
        finally:
            sys.modules.update(old_modules)

Example 3

Project: pymo Source File: test_support.py
Function: init
    def __init__(self, *module_names):
        self.original_modules = sys.modules.copy()
        for module_name in module_names:
            if module_name in sys.modules:
                module = sys.modules[module_name]
                # It is possible that module_name is just an alias for
                # another module (e.g. stub for modules renamed in 3.x).
                # In that case, we also need delete the real module to clear
                # the import cache.
                if module.__name__ != module_name:
                    del sys.modules[module.__name__]
                del sys.modules[module_name]

Example 4

Project: github-cli Source File: test_base.py
Function: set_up
    def setUp(self):
        self.mods = sys.modules.copy()
        if self.mod in sys.modules:
            del sys.modules[self.mod]

        global commands
        if self.command in commands:
            del commands[self.command]

Example 5

Project: deblaze Source File: test_adapters.py
Function: set_up
    def setUp(self):
        PostLoadHookClearingTestCase.setUp(self)

        self.old_env = os.environ.copy()
        self.mods = sys.modules.copy()

        self.path = os.path.join(os.path.dirname(__file__), 'imports')
        sys.path.append(self.path)

Example 6

Project: deblaze Source File: test_imports.py
Function: set_up
    def setUp(self):
        PostLoadHookClearingTestCase.setUp(self)

        self.path = os.path.join(os.path.dirname(__file__), 'imports')
        self.mods = sys.modules.copy()
        self.executed = False

        sys.path.insert(0, self.path)

Example 7

Project: rpyc Source File: splitbrain.py
@contextmanager
def localbrain():
    """Return to operate on the local machine. You can enter this context only after calling ``enable()``"""
    if not _enabled:
        raise ValueError("Splitbrain not enabled")
    prev_conn = getattr(router, "conn", None)
    prev_modules = sys.modules.copy()
    if hasattr(router, "conn"):
        del router.conn
    try:
        yield
    finally:
        sys.modules.clear()
        sys.modules.update(prev_modules)
        router.conn = prev_conn
        if not router.conn:
            del router.conn

Example 8

Project: WAPT Source File: CallTips.py
    def get_entity(self, expression):
        """Return the object corresponding to expression evaluated
        in a namespace spanning sys.modules and __main.dict__.
        """
        if expression:
            namespace = sys.modules.copy()
            namespace.update(__main__.__dict__)
            try:
                return eval(expression, namespace)
            except BaseException:
                # An uncaught exception closes idle, and eval can raise any
                # exception, especially if user classes are involved.
                return None

Example 9

Project: TrustRouter Source File: CallTips.py
Function: get_entity
    def get_entity(self, name):
        "Lookup name in a namespace spanning sys.modules and __main.dict__."
        if name:
            namespace = sys.modules.copy()
            namespace.update(__main__.__dict__)
            try:
                return eval(name, namespace)
            except (NameError, AttributeError):
                return None

Example 10

Project: TrustRouter Source File: test_datetime.py
Function: set_up
            def setUp(self, module=module, setup=cls.setUp):
                self._save_sys_modules = sys.modules.copy()
                sys.modules[TESTS] = module
                sys.modules['datetime'] = module.datetime_module
                sys.modules['_strptime'] = module._strptime
                setup(self)

Example 11

Project: pyff Source File: test_rollbackimporter.py
    def testSysModulesEqualBeforeAndAfter(self):
        """Modules before and after usage of RBI should be equal."""
        before = sys.modules.copy()
        rbi = RollbackImporter()
        import mod_w_imports
        rbi.uninstall()
        self.assertEqual(before, sys.modules)

Example 12

Project: brython Source File: test_datetime.py
Function: setup_class
        @classmethod
        def setUpClass(cls_, module=module):
            cls_._save_sys_modules = sys.modules.copy()
            sys.modules[TESTS] = module
            sys.modules['datetime'] = module.datetime_module
            sys.modules['_strptime'] = module._strptime

Example 13

Project: circuits Source File: utils.py
def safeimport(name):
    modules = sys.modules.copy()
    try:
        if name in sys.modules:
            return reload(sys.modules[name])
        else:
            return __import__(name, globals(), locals(), [""])
    except:
        for name in sys.modules.copy():
            if not name in modules:
                del sys.modules[name]

Example 14

Project: crossbar Source File: reloader.py
Function: snapshot
    def snapshot(self):
        """
        Establish a snapshot - that is, remember which modules are currently
        loaded. Later, when reload() is called, only modules imported later
        will be (forcefully) reloaded.
        """
        self._modules = sys.modules.copy()

        # do mtime tracking ..
        if self._use_mtimes:
            self._module_mtimes = {}
            for mod_name, mod in self._modules.items():
                self._module_mtimes[mod_name] = get_module_path_and_mtime(mod)

Example 15

Project: distarray Source File: ipython_cleanup.py
Function: clear
def clear(view):
    """ Removes all distarray-related modules from engines' sys.modules."""

    def clear_engine():
        from sys import modules
        orig_mods = set(modules)
        for m in modules.copy():
            if m.startswith('distarray'):
                del modules[m]
        return sorted(orig_mods - set(modules))

    return view.apply_async(clear_engine).get_dict()

Example 16

Project: ocf Source File: commands.py
    def switch_to(self):
        from django.core.management import setup_environ
        import sys
        
        self.curr_mods = sys.modules.copy()

        self.backup_path = sys.path[0]
        sys.path[0] = self.project_path
        
        import settings
        setup_environ(settings)
        
        from django.db.models.loading import get_models
        loaded_models = get_models()

Example 17

Project: pyamf Source File: test_adapters.py
Function: set_up
    def setUp(self):
        ImportsTestCase.setUp(self)

        self.old_env = os.environ.copy()
        self.mods = sys.modules.copy()

        self.path = os.path.join(os.path.dirname(__file__), 'imports')
        sys.path.append(self.path)

Example 18

Project: ironpython3 Source File: CallTips.py
def get_entity(expression):
    """Return the object corresponding to expression evaluated
    in a namespace spanning sys.modules and __main.dict__.
    """
    if expression:
        namespace = sys.modules.copy()
        namespace.update(__main__.__dict__)
        try:
            return eval(expression, namespace)
        except BaseException:
            # An uncaught exception closes idle, and eval can raise any
            # exception, especially if user classes are involved.
            return None

Example 19

Project: mythbox Source File: test_gtkreactor.py
Function: set_up
    def setUp(self):
        """
        Create a stub for the module 'gtk' if it does not exist, so that it can
        be imported without errors or warnings.
        """
        self.mods = sys.modules.copy()
        sys.modules['gtk'] = self.StubGTK()
        sys.modules['pygtk'] = self.StubPyGTK()

Example 20

Project: mythbox Source File: test_versions.py
    def setUp(self):
        """
        Create a temporary directory with a package structure in it.
        """
        self.entry = FilePath(self.mktemp())
        self.preTestModules = sys.modules.copy()
        sys.path.append(self.entry.path)
        pkg = self.entry.child("twisted_python_versions_package")
        pkg.makedirs()
        pkg.child("__init__.py").setContent(
            "from twisted.python.versions import Version\n"
            "version = Version('twisted_python_versions_package', 1, 0, 0)\n")
        self.svnEntries = pkg.child(".svn")
        self.svnEntries.makedirs()

Example 21

Project: mythbox Source File: test_modules.py
    def replaceSysModules(self, sysModules):
        """
        Replace sys.modules, for the duration of the test, with the given value.
        """
        originalSysModules = sys.modules.copy()
        def cleanUpSysModules():
            sys.modules.clear()
            sys.modules.update(originalSysModules)
        self.addCleanup(cleanUpSysModules)
        sys.modules.clear()
        sys.modules.update(sysModules)

Example 22

Project: mythbox Source File: test_twistd.py
Function: test_without_profile
    def test_withoutProfile(self):
        """
        When the C{profile} module is not present, L{app.ProfilerRunner.run}
        should raise a C{SystemExit} exception.
        """
        savedModules = sys.modules.copy()

        config = twistd.ServerOptions()
        config["profiler"] = "profile"
        profiler = app.AppProfiler(config)

        sys.modules["profile"] = None
        try:
            self.assertRaises(SystemExit, profiler.run, None)
        finally:
            sys.modules.clear()
            sys.modules.update(savedModules)

Example 23

Project: mythbox Source File: test_twistd.py
    def test_withoutHotshot(self):
        """
        When the C{hotshot} module is not present, L{app.HotshotRunner.run}
        should raise a C{SystemExit} exception and log the C{ImportError}.
        """
        savedModules = sys.modules.copy()
        sys.modules["hotshot"] = None

        config = twistd.ServerOptions()
        config["profiler"] = "hotshot"
        profiler = app.AppProfiler(config)
        try:
            self.assertRaises(SystemExit, profiler.run, None)
        finally:
            sys.modules.clear()
            sys.modules.update(savedModules)

Example 24

Project: mythbox Source File: test_twistd.py
    def test_withoutCProfile(self):
        """
        When the C{cProfile} module is not present,
        L{app.CProfileRunner.run} should raise a C{SystemExit}
        exception and log the C{ImportError}.
        """
        savedModules = sys.modules.copy()
        sys.modules["cProfile"] = None

        config = twistd.ServerOptions()
        config["profiler"] = "cProfile"
        profiler = app.AppProfiler(config)
        try:
            self.assertRaises(SystemExit, profiler.run, None)
        finally:
            sys.modules.clear()
            sys.modules.update(savedModules)

Example 25

Project: supernova Source File: test_imports.py
        def test_import_supernova_exception(self):
            def import_mock(name, *args, **kwargs):
                if name == 'gi.require_version':
                    return MockGi
                return orig_import(name, *args, **kwargs)
            mods = sys.modules.copy()
            loading = []
            tmpmod = {}
            for mod in mods:
                if mod.startswith('supernova'):
                    loading.append(mod.split('.')[-1])
                    tmpmod[mod] = sys.modules[mod]
                    del sys.modules[mod]
            __builtin__.__import__ = import_mock
            __import__('supernova', fromlist=loading)
            sys.modules.update(tmpmod)
            assert MockGi.called == 1
            __builtin__.__import__ = orig_import

Example 26

Project: bloodhound Source File: __init__.py
Function: safe_import
def safe__import__(module_name):
    """
    Safe imports: rollback after a failed import.
    
    Initially inspired from the RollbackImporter in PyUnit,
    but it's now much simpler and works better for our needs.
    
    See http://pyunit.sourceforge.net/notes/reloading.html
    """
    already_imported = sys.modules.copy()
    try:
        return __import__(module_name, globals(), locals(), [])
    except Exception, e:
        for modname in sys.modules.copy():
            if not already_imported.has_key(modname):
                del(sys.modules[modname])
        raise e

Example 27

Project: pymo Source File: AutoComplete.py
Function: get_entity
    def get_entity(self, name):
        """Lookup name in a namespace spanning sys.modules and __main.dict__"""
        namespace = sys.modules.copy()
        namespace.update(__main__.__dict__)
        return eval(name, namespace)

Example 28

Project: setuptools Source File: sandbox.py
Function: save_modules
@contextlib.contextmanager
def save_modules():
    """
    Context in which imported modules are saved.

    Translates exceptions internal to the context into the equivalent exception
    outside the context.
    """
    saved = sys.modules.copy()
    with ExceptionSaver() as saved_exc:
        yield saved

    sys.modules.update(saved)
    # remove any modules imported since
    del_modules = (
        mod_name for mod_name in sys.modules
        if mod_name not in saved
        # exclude any encodings modules. See #285
        and not mod_name.startswith('encodings.')
    )
    _clear_modules(del_modules)

    saved_exc.resume()

Example 29

Project: qiime2 Source File: test_artifact_api.py
    def setUp(self):
        self._sys_modules = sys.modules.copy()
        # Ignore the returned dummy plugin object, just run this to verify the
        # plugin exists as the tests rely on it being loaded.
        get_dummy_plugin()

Example 30

Project: smisk Source File: python.py
def load_modules(path, deep=False, skip_first_init=True, libdir=None, parent_name=None):
  '''Import all modules in a directory.
  
  .. deprecated:: 1.1.1
    This function will be removed in future versions.
  
  :param path: Path of a directory
  :type  path: string
  
  :param deep: Search subdirectories
  :type  deep: bool
  
  :param skip_first_init: Do not load any __init__ directly under `path`.
                          Note that if `deep` is ``True``, 
                          subdirectory/__init__ will still be loaded, 
                          even if `skip_first_init` is ``True``.
  :type  skip_first_init: bool
  
  :returns: A dictionary of modules imported, keyed by name.
  :rtype:   dict'''
  # DEPRECATED 1.1.1
  loaded = sys.modules.copy()
  path = os.path.abspath(path)
  if libdir and parent_name:
    top_path = os.path.abspath(libdir)
    parent_name = parent_name
  else:
    parent_name, top_path = find_closest_syspath(path, [])
  sys.path[0:0] = [top_path]
  loaded_paths = {}
  for name,mod in sys.modules.items():
    if mod:
      try:
        loaded_paths[strip_filename_extension(mod.__file__)] = mod
      except AttributeError:
        pass
  try:
    _load_modules(path, deep, skip_first_init, parent_name, loaded, loaded_paths)
  finally:
    if sys.path[0] == top_path:
      sys.path = sys.path[1:]
  return loaded

Example 31

Project: locality-sensitive-hashing Source File: isolate.py
    def beforeContext(self):
        """Copy sys.modules onto my mod stack
        """
        mods = sys.modules.copy()
        self._mod_stack.append(mods)

Example 32

Project: deblaze Source File: test_django.py
    def setUp(self):
        self.old_env = os.environ.copy()
        self.mods = sys.modules.copy()

        if 'DJANGO_SETTINGS_MODULE' in os.environ.keys():
            from django import conf
            import copy

            self.mod = copy.deepcopy(conf.settings)
            mod = conf.settings
            self.existing = True
        else:
            os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
            mod = new.module('settings')
            sys.modules['settings'] = mod

            self.existing = False

        setattr(mod, 'DATABASE_ENGINE', 'sqlite3')
        setattr(mod, 'DATABASE_NAME', ':memory:')

Example 33

Project: Contexts Source File: assertion_rewriting_tests.py
    def establish(self):
        self.module_name = "assertion_rewriting_test_data"
        self.old_sys_dot_modules = sys.modules.copy()
        self.importer = AssertionRewritingImporter()

Example 34

Project: rpyc Source File: splitbrain.py
@contextmanager
def splitbrain(conn):
    """Enter a splitbrain context in which imports take place over the given RPyC connection (expected to 
    be a SlaveService). You can enter this context only after calling ``enable()``"""
    if not _enabled:
        enable_splitbrain()
        #raise ValueError("Splitbrain not enabled")
    prev_conn = getattr(router, "conn", None)
    prev_modules = sys.modules.copy()
    router.conn = conn
    prev_stdin = conn.modules.sys.stdin
    prev_stdout = conn.modules.sys.stdout
    prev_stderr = conn.modules.sys.stderr
    conn.modules["sys"].stdin = sys.stdin
    conn.modules["sys"].stdout = sys.stdout
    conn.modules["sys"].stderr = sys.stderr
    try:
        yield
    finally:
        conn.modules["sys"].stdin = prev_stdin
        conn.modules["sys"].stdout = prev_stdout
        conn.modules["sys"].stderr = prev_stderr
        sys.modules.clear()
        sys.modules.update(prev_modules)
        router.conn = prev_conn
        if not router.conn:
            del router.conn

Example 35

Project: TrustRouter Source File: CallTips.py
    def get_object_at_cursor(self,
                             wordchars="._" + string.ascii_uppercase + string.ascii_lowercase + string.digits):
        # XXX - This needs to be moved to a better place
        # so the "." attribute lookup code can also use it.
        text = self.text
        chars = text.get("insert linestart", "insert")
        i = len(chars)
        while i and chars[i-1] in wordchars:
            i = i-1
        word = chars[i:]
        if word:
            # How is this for a hack!
            import sys, __main__
            namespace = sys.modules.copy()
            namespace.update(__main__.__dict__)
            try:
                    return eval(word, namespace)
            except:
                    pass
        return None # Can't find an object.

Example 36

Project: TrustRouter Source File: view.py
	def _GetObjectAtPos(self, pos = -1, bAllowCalls = 0):
		left, right = self._GetWordSplit(pos, bAllowCalls)
		if left: # It is an attribute lookup
			# How is this for a hack!
			namespace = sys.modules.copy()
			namespace.update(__main__.__dict__)
			# Get the debugger's context.
			try:
				from pywin.framework import interact
				if interact.edit is not None and interact.edit.currentView is not None:
					globs, locs = interact.edit.currentView.GetContext()[:2]
					if globs: namespace.update(globs)
					if locs: namespace.update(locs)
			except ImportError:
				pass
			try:
				return eval(left, namespace)
			except:
				pass
		return None

Example 37

Project: pyff Source File: RollbackImporter.py
    def __init__(self):
        """Init the RollbackImporter and setup the import proxy."""
        self.oldmodules = sys.modules.copy()
        self.realimport = __builtin__.__import__
        __builtin__.__import__ = self._import

Example 38

Project: xtraceback Source File: support.py
def modules_setup():
    return sys.modules.copy(),

Example 39

Project: supernova Source File: test_imports.py
        def test_import_gi(self):
            def import_mock(name, *args, **kwargs):
                if name == 'gi.require_version':
                    return MockGi
                return orig_import(name, *args, **kwargs)

            mods = sys.modules.copy()
            tmpmod = {}
            loading = []
            for mod in mods:
                if mod.startswith('supernova'):
                    if mod.startswith('supernova'):
                        loading.append(mod.split('.')[-1])
                    tmpmod[mod] = sys.modules[mod]
                    del sys.modules[mod]
            builtins.__import__ = import_mock
            __import__('supernova', fromlist=loading)
            sys.modules.update(tmpmod)
            assert MockGi.called == 1
            builtins.__import__ = orig_import

Example 40

Project: pytest-nodev Source File: plugin.py
def make_candidate_index(config):
    if config.getoption('candidates_from_all') and os.environ.get('PYTEST_NODEV_MODE') != 'FEARLESS':
        raise ValueError("Use of --candidates-from-all may be very dangerous, see the docs.")

    if not hasattr(config, '_candidate_index'):
        # take over collect logging
        collect.logger.propagate = False
        collect.logger.setLevel(logging.DEBUG)  # FIXME: loglevel should be configurable
        collect.logger.addHandler(utils.EmitHandler(config._warn))

        # delegate interrupting hanging tests to pytest-timeout
        os.environ['PYTEST_TIMEOUT'] = os.environ.get('PYTEST_TIMEOUT', '1')

        # build the object index
        distributions = collections.OrderedDict()

        if config.getoption('candidates_from_stdlib') or config.getoption('candidates_from_all'):
            distributions.update(collect.collect_stdlib_distributions())

        if config.getoption('candidates_from_all'):
            distributions.update(collect.collect_installed_distributions())

        distributions.update(collect.collect_distributions(config.getoption('candidates_from_specs')))

        if config.getoption('candidates_from_modules'):
            distributions['unknown distribution'] = config.getoption('candidates_from_modules')

        top_level_modules = collect.import_distributions(distributions.items())

        includes = config.getoption('candidates_includes')
        if not includes:
            includes = ['.'] if config.getoption('candidates_from_all') else sorted(top_level_modules)
        excludes = config.getoption('candidates_excludes')
        predicate = config.getoption('candidates_predicate')

        # NOTE: 'copy' is needed here because indexing may unexpectedly trigger a module load
        modules = sys.modules.copy()
        object_index = dict(
            collect.generate_objects_from_modules(modules, includes, excludes, predicate)
        )

        # store index
        config._candidate_index = list(zip(*sorted(object_index.items()))) or [(), ()]

    return config._candidate_index