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.

131 Examples 7

Example 1

Project: hifive Source File: test_hic_data.py
    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 2

Project: apptools Source File: version_registry.py
Function: create_registry
def _create_registry():
    """Creates a reload safe, singleton registry.
    """
    registry = None
    for key in sys.modules.keys():
        if 'version_registry' in key:
            mod = sys.modules[key]
            if hasattr(mod, 'registry'):
                registry = mod.registry
                break
    if not registry:
        registry = HandlerRegistry()
    return registry

Example 3

Project: mirage Source File: api.py
Function: delete_module
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 4

Project: pyff Source File: RollbackImporter.py
    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 5

Project: flumotion Source File: project.py
Function: list
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 6

Project: locality-sensitive-hashing Source File: isolate.py
Function: aftercontext
    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 7

Project: PSO2Proxy Source File: commands.py
    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 8

Project: glymur Source File: test_printing.py
Function: test_suppress_xml
    @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 9

Project: pyleaf Source File: prj.py
    def _updateUserModule(self):
        import sys

        #the following is needed to sync the inspect module
        #with actual disk content
        import linecache
        linecache.checkcache()

        if self._modulename in sys.modules.keys():
            log.send('Reloading user module.')
            self._usermodule = sys.modules[self._modulename]
            reload(self._usermodule)
        else:
            log.send('Loading user module.')
            self._usermodule = __import__(self._modulename)

        log.send('Your module is: ' + str(self._usermodule), 2)

        return self._usermodule

Example 10

Project: idasec Source File: MainWidget.py
    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 11

Project: pyff Source File: HexoViz.py
Function: shut_down
    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 12

Project: python-haystack Source File: model.py
Function: reset
    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 13

Project: Voodoo-Mock Source File: untee.py
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 14

Project: hifive Source File: test_fivec_data.py
    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 15

Project: glymur Source File: test_printing.py
    @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 16

Project: alchemist Source File: utils.py
Function: unload_modules
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 17

Project: mirage Source File: test_module.py
    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 18

Project: django-moderation Source File: testauto_discover.py
    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 19

Project: glymur Source File: test_printing.py
    @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 20

Project: PyDev.Debugger Source File: pydev_umd.py
Function: init
    def __init__(self, namelist=None, pathlist=None):
        if namelist is None:
            namelist = []
        self.namelist = namelist
        if pathlist is None:
            pathlist = []
        self.pathlist = pathlist
        try:
            # blacklist all files in org.python.pydev/pysrc
            import pydev_pysrc, inspect
            self.pathlist.append(os.path.dirname(pydev_pysrc.__file__))
        except:
            pass
        self.previous_modules = list(sys.modules.keys())

Example 21

Project: zorro Source File: base.py
Function: tear_down
    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 22

Project: jaikuenginepatch Source File: settings_post.py
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 23

Project: glymur Source File: test_printing.py
    @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 24

Project: python-haystack Source File: vol.py
    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 25

Project: corduroy Source File: io.py
    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 26

Project: pyff Source File: HexoViz.py
    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 27

Project: QSTK Source File: gui.py
Function: destroy
    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 28

Project: ShinyMUD Source File: __init__.py
    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 29

Project: pyff Source File: PluginController.py
Function: unload_plugin
    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 30

Project: glymur Source File: test_printing.py
    @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 31

Project: flexx Source File: testing.py
Function: clear_our_modules
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 32

Project: locality-sensitive-hashing Source File: cover.py
Function: begin
    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 33

Project: hifive Source File: test_hic_data.py
    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 34

Project: glymur Source File: test_printing.py
    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 35

Project: clustershell Source File: Defaults.py
Function: load_worker_class
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 36

Project: mirage Source File: test_module.py
Function: tear_down
    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 37

Project: riglab Source File: riglab_plugin.py
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 38

Project: glymur Source File: test_printing.py
    @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 39

Project: scikit-neuralnetwork Source File: test_platform.py
Function: set_up
    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 40

Project: mirage Source File: test_match.py
Function: tear_down
    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 41

Project: gitsome Source File: completer.py
    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 42

Project: pybuilder Source File: coverage_plugin.py
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 43

Project: music-player Source File: PythonBrowser.py
    @objc.IBAction
    def pickRandomModule_(self, sender):
        """Test method, hooked up from the "Pick Random Module" menu in
        MainMenu.nib, to test changing the browsed object after the window
        has been created."""
        from random import choice
        mod = None
        while mod is None:
            mod = sys.modules[choice(sys.modules.keys())]
        self.setObject_(mod)

Example 44

Project: mirage Source File: api.py
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 45

Project: python-proboscis Source File: run_tests.py
    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 46

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

Example 47

Project: glymur Source File: test_printing.py
Function: test_xml
    @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)

Example 48

Project: glymur Source File: test_printing.py
    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 49

Project: scikit-learn Source File: gen_rst.py
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 50

Project: dill Source File: __diff.py
Function: imp
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
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3