sys.modules.keys

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

169 Examples 7

Example 1

Project: sphinx-gallery
Source File: gen_rst.py
View license
def clean_modules():
    """Remove "unload" seaborn from the name space

    After a script is executed it can load a variety of setting that one
    does not want to influence in other examples in the gallery."""

    # Horrible code to 'unload' seaborn, so that it resets
    # its default when is load
    # Python does not support unloading of modules
    # https://bugs.python.org/issue9072
    for module in list(sys.modules.keys()):
        if 'seaborn' in module:
            del sys.modules[module]

    # Reset Matplotlib to default
    plt.rcdefaults()

Example 2

Project: tensorly
Source File: gen_rst.py
View license
def clean_modules():
    """Remove "unload" seaborn from the name space

    After a script is executed it can load a variety of setting that one
    does not want to influence in other examples in the gallery."""

    # Horrible code to 'unload' seaborn, so that it resets
    # its default when is load
    # Python does not support unloading of modules
    # https://bugs.python.org/issue9072
    for module in list(sys.modules.keys()):
        if 'seaborn' in module:
            del sys.modules[module]

    # Reset Matplotlib to default
    plt.rcdefaults()

Example 3

Project: django-object-tools
Source File: __init__.py
View license
    def test_autodiscover(self):
        autodiscover()
        self.failUnless(
            'object_tools.tests.tools' in sys.modules.keys(),
            'Autodiscover should import tool modules from installed apps.'
        )

Example 4

Project: mirage
Source File: test_match.py
View license
    def tearDown(self): 
        import sys
        test_modules = [x for x in sys.modules.keys() \
                        if x.startswith('localhost_stubotest')]
        for mod in test_modules:
            del sys.modules[mod]
            
        from stubo.ext.module import Module
        Module('localhost').remove('dummy')   
        self.q_patch.stop()         

Example 5

Project: locality-sensitive-hashing
Source File: cover.py
View license
    def begin(self):
        """
        Begin recording coverage information.
        """
        log.debug("Coverage begin")
        self.skipModules = sys.modules.keys()[:]
        if self.coverErase:
            log.debug("Clearing previously collected coverage statistics")
            self.coverInstance.combine()
            self.coverInstance.erase()
        self.coverInstance.exclude('#pragma[: ]+[nN][oO] [cC][oO][vV][eE][rR]')
        self.coverInstance.load()
        self.coverInstance.start()

Example 6

Project: glymur
Source File: test_printing.py
View license
    def test_xmp(self):
        """
        Verify the printing of a UUID/XMP box.

        If no lxml, just verify that we don't error out.
        """
        j = glymur.Jp2k(self.jp2file)
        actual = str(j.box[3])

        if 'lxml' in sys.modules.keys():
            expected = fixtures.nemo_xmp_box
            self.assertEqual(actual, expected)

Example 7

Project: flexx
Source File: testing.py
View license
def _clear_our_modules():
    """ Remove ourselves from sys.modules to force an import.
    """
    for key in list(sys.modules.keys()):
        if key.startswith(PACKAGE_NAME) and 'testing' not in key:
            del sys.modules[key]

Example 8

Project: pyff
Source File: HexoViz.py
View license
    def _reinit_base(self):
        
        for key in sys.modules.keys():
            if key.startswith("direct.") and not(sys.modules[key]==None) and not key.endswith('Messenger'):
                sys.modules.pop(key)
        import direct.showbase
        reload(sys.modules['direct.showbase.Messenger'])
        from direct.directbase import DirectStart        

Example 9

Project: scikit-learn
Source File: gen_rst.py
View license
def clean_modules():
    """Remove "unload" seaborn from the name space

    After a script is executed it can load a variety of setting that one
    does not want to influence in other examples in the gallery."""

    # Horrible code to 'unload' seaborn, so that it resets
    # its default when is load
    # Python does not support unloading of modules
    # https://bugs.python.org/issue9072
    for module in list(sys.modules.keys()):
        if 'seaborn' in module:
            del sys.modules[module]

    # Reset Matplotlib to default
    plt.rcdefaults()

Example 10

Project: python-haystack
Source File: model.py
View license
    def reset(self):
        """Clean the book"""
        log.info('RESET MODEL')
        self.__book = dict()
        # FIXME: that is probably useless now.
        for mod in sys.modules.keys():
            if 'haystack.reverse' in mod:
                del sys.modules[mod]
                log.debug('de-imported %s',mod)

Example 11

Project: mirage
Source File: test_module.py
View license
    def tearDown(self):
        import sys

        test_modules = [x for x in sys.modules.keys() if x.startswith('localhost_stubotest')]
        for mod in test_modules:
            del sys.modules[mod]
        self.q_patch.stop()

Example 12

Project: Voodoo-Mock
Source File: untee.py
View license
def importFromTee( name, fromlist ):
    if name not in sys.modules.keys():
        sys.modules[ name ] = imp.new_module( name );
    module = sys.modules[ name ];
    for each in fromlist:
        setattr( module, each, oldImport( each ) );
    return module;

Example 13

Project: glymur
Source File: test_printing.py
View license
    @unittest.skipIf('lxml' not in sys.modules.keys(), "No lxml")
    def test_jp2_codestream_0(self):
        """Verify dumping with -c 0, supressing all codestream details."""
        actual = self.run_jp2dump(['', '-c', '0', self.jp2file])

        # shave off the codestream details
        lines = fixtures.nemo.split('\n')
        expected = lines[0:105]
        expected = '\n'.join(expected)
        self.assertEqual(actual, expected)

Example 14

Project: mirage
Source File: api.py
View license
def list_module(handler, names):
    module = Module(get_hostname(handler.request))
    info = {}
    if not names:
        names = [x.rpartition(':')[-1] for x in get_keys(
            '{0}:modules:*'.format(module.host()))]
    for name in names:
        loaded_sys_versions = [x for x in sys.modules.keys() if '{0}_v'.format(name) in x]
        lastest_code_version = module.latest_version(name)
        info[name] = {
            'latest_code_version': lastest_code_version,
            'loaded_sys_versions': loaded_sys_versions
        }
    payload = dict(message='list modules', info=info)
    return {
        'version': version,
        'data': payload
    }

Example 15

Project: pybuilder
Source File: coverage_plugin.py
View license
def _delete_non_essential_modules():
    sys_packages, sys_modules = _get_system_assets()
    for module_name in list(sys.modules.keys()):
        module = sys.modules[module_name]
        if module:
            if not _is_module_essential(module.__name__, sys_packages, sys_modules):
                _delete_module(module_name, module)

Example 16

Project: glymur
Source File: test_printing.py
View license
    @unittest.skipIf('lxml' not in sys.modules.keys(), "No lxml")
    def test_suppress_xml(self):
        """Verify dumping with -x, suppress XML."""
        actual = self.run_jp2dump(['', '-x', self.jp2file])

        # shave off the XML and non-main-header segments
        lines = fixtures.nemo.split('\n')
        expected = lines[0:18]
        expected.extend(lines[104:140])
        expected = '\n'.join(expected)
        self.assertEqual(actual, expected)

Example 17

Project: hifive
Source File: test_hic_data.py
View license
    def test_hic_bam_data_creation(self):
        if 'pysam' not in sys.modules.keys():
            print >> sys.stderr, "pysam required for bam import"
            return None
        subprocess.call("./bin/hifive hic-data -q -S %s %s -i 500 %s test/data/test_temp.hcd" %
                        (self.bam_fname1, self.bam_fname2, self.fend_fname), shell=True)
        data = h5py.File('test/data/test_temp.hcd', 'r')
        self.compare_hdf5_dicts(self.bam_data, data, 'data')

Example 18

Project: zorro
Source File: base.py
View license
    def tearDown(self):
        if not self.hub.stopping:
            self.hub.stop()
        self.thread.join(self.test_timeout)
        if self.thread.is_alive():
            try:
                if not getattr(self, 'should_timeout', False):
                    raise AssertionError("test timed out")
            finally:
                self.hub.crash()
                self.thread.join()
        for key in list(sys.modules.keys()):
            if key == 'zorro' or key.startswith('zorro.'):
                del sys.modules[key]

Example 19

Project: riglab
Source File: riglab_plugin.py
View license
def CloseScene_OnEvent(in_ctxt):
    log("CloseScene_OnEvent called", C.siVerbose)
    import sys
    module = "riglab"
    if len(module):
        for k in sys.modules.keys():
            if k.startswith(module):
                del sys.modules[k]
    return True

Example 20

Project: flumotion
Source File: project.py
View license
def list():
    """
    Returns a list of all add-on projects seen by Flumotion.
    """
    projects = [n for n in sys.modules.keys()
                      if n.startswith('flumotion.project')]
    paths = flumotion.project.__path__
    modules = []
    for path in paths:
        modules.extend(package.findEndModuleCandidates(
            os.path.abspath(os.path.join(path, '..', '..')),
            prefix='flumotion.project'))

    modules.remove('flumotion.project.project')

    return [n[len('flumotion.project.'):] for n in modules]

Example 21

Project: python-haystack
Source File: vol.py
View license
    def _unload_volatility(self):
        '''we cannot have volatility already loaded.
        we need to remove it'''
        for mod in sys.modules.keys():
            if 'volatility' in mod:
                del sys.modules[mod]

Example 22

Project: corduroy
Source File: io.py
View license
    def __init__(self):
        self._ready = False
        if any(m for m in sys.modules.keys() if m.startswith('tornado')):
            try:
                from tornado import httpclient, ioloop, gen
                self.blocking = adict(client=httpclient.HTTPClient(), request=httpclient.HTTPRequest, error=httpclient.HTTPError)
                self.async = adict(client=httpclient.AsyncHTTPClient(force_instance=True), request=httpclient.HTTPRequest, 
                                           loop=ioloop.IOLoop.instance(), gen=gen)
                self._ready = True

                # prefer the libcurl-based client because it's fast (even though pycurl's
                # very literal transcription of the c ‘api’ doesn't fill me with confidence
                # about what's happening in ffi-land...)
                log("Using httpclient (tornado)")
                import pycurl
                httpclient.AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")
                log("... with the pycurl backend")
            except ImportError:
                pass

Example 23

Project: pyff
Source File: HexoViz.py
View license
    def shut_down(self):
        # try to remove all Panda3D stuff from working memory so that it has to be completely reloaded
        base.exitfunc()
        for key in sys.modules.keys():
            if key.startswith("direct.") and not(sys.modules[key]==None):# and not key.endswith('Messenger'):
                del sys.modules[key]
                #sys.modules.pop(key)
        pass

Example 24

Project: ShinyMUD
Source File: __init__.py
View license
    def setUp(self):
        import sys
        remove = [m for m in sys.modules.keys() if 'shinymud' in m]
        for r in remove:
            del sys.modules[r]
        from shinymud.lib.world import World
        self.world = World(':memory:')
        from shinymud.lib.setup import initialize_database
        initialize_database()

Example 25

Project: glymur
Source File: test_printing.py
View license
    @unittest.skipIf('lxml' not in sys.modules.keys(), "No lxml")
    def test_suppress_codestream(self):
        """
        Verify printing with codestream suppressed
        """
        jp2 = Jp2k(self.jp2file)
        glymur.set_option('print.codestream', False)

        # Get rid of the file line
        actual = '\n'.join(str(jp2).splitlines()[1:])

        expected = fixtures.nemo_dump_no_codestream
        self.assertEqual(actual, expected)

        opt = glymur.get_option('print.codestream')
        self.assertFalse(opt)

Example 26

View license
    def afterContext(self):
        """Pop my mod stack and restore sys.modules to the state
        it was in when mod stack was pushed.
        """
        mods = self._mod_stack.pop()
        to_del = [ m for m in sys.modules.keys() if m not in mods ]
        if to_del:
            log.debug('removing sys modules entries: %s', to_del)
            for mod in to_del:
                del sys.modules[mod]
        sys.modules.update(mods)

Example 27

Project: glymur
Source File: test_printing.py
View license
    @unittest.skipIf('lxml' not in sys.modules.keys(), "No lxml")
    def test_full_codestream(self):
        """
        Verify printing with the full blown codestream
        """
        jp2 = Jp2k(self.jp2file)
        glymur.set_option('parse.full_codestream', True)

        # Get rid of the file line
        actual = '\n'.join(str(jp2).splitlines()[1:])

        expected = fixtures.nemo
        self.assertEqual(actual, expected)

        opt = glymur.get_option('print.codestream')
        self.assertTrue(opt)

Example 28

Project: glymur
Source File: test_printing.py
View license
    def test_default_nemo(self):
        """by default one should get the main header"""
        actual = self.run_jp2dump(['', self.jp2file])
        if 'lxml' not in sys.modules.keys():
            # No lxml, so don't bother verifying.  We know at least that it
            # runs.
            return

        # shave off the  non-main-header segments
        lines = fixtures.nemo.split('\n')
        expected = lines[0:140]
        expected = '\n'.join(expected)
        self.assertEqual(actual, expected)

Example 29

Project: mirage
Source File: test_module.py
View license
    def test_remove_sys_module(self):
        import sys

        m = self._get_module()
        m.add_sys_module('localhost_stubotest_foo', 'x = "hello"')
        m.remove_sys_module('localhost_stubotest_foo')
        self.assertTrue('localhost_stubotest_foo' not in sys.modules.keys())

Example 30

Project: PSO2Proxy
Source File: commands.py
View license
    def call_from_console(self):
        if len(self.args.split(' ')) < 2:
            return "[Command] Invalid usage. (Usage: reloadplugin <Plugin Name>)"
        modulearg = self.args.split(' ')[1]
        if modulearg not in sys.modules.keys():
            return "That plugin (%s) is not loaded." % modulearg
        output = "[ShipProxy] Reloading plugin: %s..." % modulearg
        rebuild.rebuild(sys.modules[modulearg])
        output += "[ShipProxy] Plugin reloaded!\n"
        return output

Example 31

Project: mirage
Source File: api.py
View license
def delete_module(request, names):
    module = Module(get_hostname(request))
    removed = []
    for name in names:
        loaded_versions = [x for x in sys.modules.keys() if '{0}_v'.format(name) in x]
        for loaded in loaded_versions:
            module.remove_sys_module(loaded)
        if module.remove(name):
            removed.append('{0}:{1}'.format(module.host(), name))
    return {
        'version': version,
        'data': {'message': 'delete modules: {0}'.format(names),
                 'deleted': removed}
    }

Example 32

Project: glymur
Source File: test_printing.py
View license
    @unittest.skipIf('lxml' not in sys.modules.keys(), "No lxml")
    def test_jp2_codestream_1(self):
        """Verify dumping with -c 1, print just the header."""
        actual = self.run_jp2dump(['', '-c', '1', self.jp2file])

        # shave off the  non-main-header segments
        lines = fixtures.nemo.split('\n')
        expected = lines[0:140]
        expected = '\n'.join(expected)
        self.assertEqual(actual, expected)

Example 33

Project: glymur
Source File: test_printing.py
View license
    @unittest.skipIf('lxml' not in sys.modules.keys(), "No lxml")
    def test_jp2_codestream_2(self):
        """Verify dumping with -c 2, print entire jp2 jacket, codestream."""
        actual = self.run_jp2dump(['', '-c', '2', self.jp2file])
        expected = fixtures.nemo
        self.assertEqual(actual, expected)

Example 34

Project: dagbldr
Source File: __diff.py
View license
def _imp(*args, **kwds):
    """
    Replaces the default __import__, to allow a module to be memorised
    before the user can change it
    """
    before = set(sys.modules.keys())
    mod = __import__(*args, **kwds)
    after = set(sys.modules.keys()).difference(before)
    for m in after:
        memorise(sys.modules[m])
    return mod

Example 35

Project: hifive
Source File: test_hic_data.py
View license
    def test_hic_bin_bam_data_creation(self):
        if 'pysam' not in sys.modules.keys():
            print >> sys.stderr, "pysam required for bam import"
            return None
        subprocess.call("./bin/hifive hic-data -q -S %s %s -i 500 %s test/data/test_temp.hcd" %
                        (self.bam_fname1, self.bam_fname2, self.binned_fend_fname), shell=True)
        data = h5py.File('test/data/test_temp.hcd', 'r')
        self.compare_hdf5_dicts(self.bin_bam_data, data, 'data')

Example 36

Project: clustershell
Source File: Defaults.py
View license
def _load_workerclass(workername):
    """
    Return the class pointer matching `workername`.

    The module is loaded if not done yet.
    """
    modname = "ClusterShell.Worker.%s" % workername.capitalize()

    # Do not iterate over sys.modules but use .keys() to avoid RuntimeError
    if modname.lower() not in [mod.lower() for mod in sys.modules.keys()]:
        # Import module if not yet loaded
        __import__(modname)

    # Get the class pointer
    return sys.modules[modname].WORKER_CLASS

Example 37

Project: hifive
Source File: test_fivec_data.py
View license
    def test_fivec_bam_data_creation(self):
        if 'pysam' not in sys.modules.keys():
            print >> sys.stderr, "pysam required for bam import"
            return None
        subprocess.call("./bin/hifive 5c-data -q -B %s %s %s test/data/test_temp.fcd" %
                        (self.bam_fname1, self.bam_fname2, self.frag_fname), shell=True)
        data = h5py.File('test/data/test_temp.fcd', 'r')
        self.compare_hdf5_dicts(self.data, data, 'data')

Example 38

Project: alchemist
Source File: utils.py
View license
def unload_modules(name):
    """Unload all modules where the name begins with the passed name.
    """

    for key in list(sys.modules.keys()):

        if key.startswith(name):

            del sys.modules[key]

Example 39

Project: python-proboscis
Source File: run_tests.py
View license
    def restore_modules(self):
        """Necessary to get the decorators to register tests again."""
        current_module_names = sys.modules.keys()
        delete_list = []
        for name in current_module_names:
            if name not in self.module_names:
                delete_list.append(name)
        for name in delete_list:
            del sys.modules[name]

Example 40

Project: pyff
Source File: RollbackImporter.py
View license
    def uninstall(self):
        """Unload all modules since __init__ and restore the original import."""
        for module in sys.modules.keys():
            if not self.oldmodules.has_key(module):
                del sys.modules[module]
        __builtin__.__import__ = self.realimport

Example 41

Project: jaikuenginepatch
Source File: settings_post.py
View license
def check_app_imports(app):
    before = sys.modules.keys()
    __import__(app, {}, {}, [''])
    after = sys.modules.keys()
    added = [key[len(app)+1:] for key in after if key not in before and
             key.startswith(app + '.') and key[len(app)+1:]]
    if added:
        import logging
        logging.warn('The app "%(app)s" contains imports in '
                     'its __init__.py (at least %(added)s). This can cause '
                     'strange bugs due to recursive imports! You should '
                     'either do the import lazily (within functions) or '
                     'ignore the app settings/urlsauto with '
                     'IGNORE_APP_SETTINGS and IGNORE_APP_URLSAUTO in '
                     'your settings.py.'
                     % {'app': app, 'added': ', '.join(added)})

Example 42

Project: dagbldr
Source File: __diff.py
View license
def _imp(*args, **kwds):
    """
    Replaces the default __import__, to allow a module to be memorised
    before the user can change it
    """
    before = set(sys.modules.keys())
    mod = __import__(*args, **kwds)
    after = set(sys.modules.keys()).difference(before)
    for m in after:
        memorise(sys.modules[m])
    return mod

Example 43

Project: QSTK
Source File: gui.py
View license
    def destroy(self, *e):
        if self._root is None: return

        # Unload any modules that we've imported
        for m in sys.modules.keys():
            if m not in self._old_modules: del sys.modules[m]
        self._root.destroy()
        self._root = None

Example 44

Project: dill
Source File: __diff.py
View license
def _imp(*args, **kwds):
    """
    Replaces the default __import__, to allow a module to be memorised
    before the user can change it
    """
    before = set(sys.modules.keys())
    mod = __import__(*args, **kwds)
    after = set(sys.modules.keys()).difference(before)
    for m in after:
        memorise(sys.modules[m])
    return mod

Example 45

Project: gitsome
Source File: completer.py
View license
    def module_complete(self, prefix):
        """Completes a name of a module to import."""
        prefixlow = prefix.lower()
        modules = set(sys.modules.keys())
        csc = builtins.__xonsh_env__.get('CASE_SENSITIVE_COMPLETIONS')
        startswither = startswithnorm if csc else startswithlow
        return {s for s in modules if startswither(s, prefix, prefixlow)}

Example 46

View license
    def test_all_app_containing_moderator_module_should_be_registered(self):
        auto_discover()

        if django_17():
            self.assertTrue("tests.moderator" in sys.modules.keys())
        else:

            from moderation import moderation

            self.assertTrue(Book in moderation._registered_models)

Example 47

View license
    def setUp(self):
        if 'THEANO_FLAGS' in os.environ:
            del os.environ['THEANO_FLAGS']
        if 'OMP_NUM_THREADS' in os.environ:
            del os.environ['OMP_NUM_THREADS']
        
        import theano

        self.removed = {}
        for name in list(sys.modules.keys()):
            if name.startswith('theano'):
                self.removed[name] = sys.modules[name]
                del sys.modules[name]
        sys.modules['sknn.platform'].configured = False

        self.buf = io.StringIO()
        self.hnd = logging.StreamHandler(self.buf)
        logging.getLogger('sknn').addHandler(self.hnd)
        logging.getLogger().setLevel(logging.WARNING)

Example 48

Project: pyff
Source File: PluginController.py
View license
    def unload_plugin(self):
        """Unload currently loaded plugin."""
        if self.oldModules:
            for mod in sys.modules.keys():
                if not self.oldModules.has_key(mod):
                    del sys.modules[mod]
            self.oldModules = None

Example 49

Project: idasec
Source File: MainWidget.py
View license
    def OnCreate(self, form):
        self.setupUi(self)
        self.connect(self.binsec_connect_button, QtCore.SIGNAL("clicked()"), self.connect_binsec)
        self.connect(self.dba_decode_button, QtCore.SIGNAL("clicked()"), self.decode_button_clicked)
        self.connect(self.here_decode_button, QtCore.SIGNAL("clicked()"), self.decode_here_clicked)
        self.idasec_title.mousePressEvent = self.change_logo
        self.connect(self.idasec_title, QtCore.SIGNAL("clicked()"), self.change_logo)

        self.pinsec_ip_field.setText("192.168.56.101")
        self.pinsec_port_field.setText("5555")
        self.binsec_port_field.setValidator(QIntValidator(0, 65535))
        self.pinsec_port_field.setValidator(QIntValidator(0, 65535))
        self.ok = QtGui.QPixmap(":/icons/icons/oxygen/22x22/ok.png")
        self.ko = QtGui.QPixmap(":/icons/icons/oxygen/22x22/ko.png")
        self.prev_modules = sys.modules.keys()

Example 50

Project: glymur
Source File: test_printing.py
View license
    @unittest.skipIf('lxml' not in sys.modules.keys(), "No lxml")
    def test_xml(self):
        """
        verify printing of XML box

        Original test file was input/conformance/file1.jp2
        """
        elt = ET.fromstring(fixtures.file1_xml)
        xml = ET.ElementTree(elt)
        box = glymur.jp2box.XMLBox(xml=xml, length=439, offset=36)
        actual = str(box)
        expected = fixtures.file1_xml_box
        self.assertEqual(actual, expected)