sys.modules.iteritems

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

11 Examples 7

Example 1

Project: nvda Source File: appModuleHandler.py
def reloadAppModules():
	"""Reloads running appModules.
	especially, it clears the cache of running appModules and deletes them from sys.modules.
	Each appModule will be reloaded immediately as a reaction on a first event coming from the process.
	"""
	global appModules
	terminate()
	del appModules
	mods=[k for k,v in sys.modules.iteritems() if k.startswith("appModules") and v is not None]
	for mod in mods:
		del sys.modules[mod]
	import appModules
	initialize()

Example 2

Project: nvda Source File: globalPluginHandler.py
def reloadGlobalPlugins():
	"""Reloads running global plugins.
	"""
	global globalPlugins
	terminate()
	del globalPlugins
	mods=[k for k,v in sys.modules.iteritems() if k.startswith("globalPlugins") and v is not None]
	for mod in mods:
		del sys.modules[mod]
	import globalPlugins
	initialize()

Example 3

Project: music-player Source File: TaskSystem.py
	def intellisave_dict(self, obj):
		if len(obj) <= 5: # fastpath
			self.save_dict(obj)
			return
		for modname, mod in sys.modules.iteritems():
			if not mod: continue
			moddict = mod.__dict__
			if obj is moddict:
				self.save(getModuleDict)
				self.save((modname,))
				self.write(pickle.REDUCE)
				self.memoize(obj)
				return
		self.save_dict(obj)

Example 4

Project: ggrc-core Source File: package.py
Function: collect
  @classmethod
  def collect(cls):
    """Collects application root packages."""
    from ggrc import app
    app = app

    for name, module in sys.modules.iteritems():
      if name.startswith('ggrc') and '.' not in name:
        yield module

Example 5

Project: LiveRemoteScripts Source File: debug.py
	def _log_sys_modules(self):	
		pairs = ((v, k) for (v, k) in sys.modules.iteritems())
		for module in sorted(pairs):
			self.log_message('---' + str(module))
		for mod in sys.modules.keys():
			self.log_message('---------path' + str(sys.modules[mod]))

Example 6

Project: wxbanker Source File: pubsubconf.py
    def __removePubModule(self):
        '''Remove the given module object from the sys.modules map.'''
        pubsub1 = self.__pubsubDict['pub']
        import sys
        for (modName, modObj) in sys.modules.iteritems():
            if modObj is pubsub1:
                del sys.modules[modName]
                break

Example 7

Project: dodai-compute Source File: flags.py
Function: get_module_name
def __GetModuleName(globals_dict):
    """Given a globals dict, returns the name of the module that defines it.

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

    Returns:
    A string (the name of the module) or None (if the module could not
    be identified.

    """
    for name, module in sys.modules.iteritems():
        if getattr(module, '__dict__', None) is globals_dict:
            if name == '__main__':
                return sys.argv[0]
            return name
    return None

Example 8

Project: calabash Source File: __init__.py
def _get_tests():
    import doctest
    import inspect
    import sys
    import unittest

    def _from_module(module, object):
        """Backported fix for http://bugs.python.org/issue1108."""
        if module is None:
            return True
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif inspect.isfunction(object):
            return module.__dict__ is object.func_globals
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function")
    finder = doctest.DocTestFinder()
    finder._from_module = _from_module

    suite = unittest.TestSuite()
    for name, module in sys.modules.iteritems():
        if name.startswith('calabash'):
            try:
                mod_suite = doctest.DocTestSuite(module, test_finder=finder)
            except ValueError:
                continue
            suite.addTests(mod_suite)
    return suite

Example 9

Project: jsonpipe Source File: __init__.py
def _get_tests():
    import doctest
    import inspect
    import sys
    import unittest

    import jsonpipe.sh

    def _from_module(module, object):
        """Backported fix for http://bugs.python.org/issue1108."""
        if module is None:
            return True
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif inspect.isfunction(object):
            return module.__dict__ is object.func_globals
        elif inspect.isclass(object):
            return module.__name__ == object.__module__
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function")
    finder = doctest.DocTestFinder()
    finder._from_module = _from_module

    suite = unittest.TestSuite()
    for name, module in sys.modules.iteritems():
        if name.startswith('jsonpipe'):
            try:
                mod_suite = doctest.DocTestSuite(
                    module, test_finder=finder,
                    optionflags=(doctest.NORMALIZE_WHITESPACE |
                                 doctest.ELLIPSIS))
            except ValueError:
                continue
            suite.addTests(mod_suite)
    return suite

Example 10

Project: golismero Source File: golismero.py
def command_update(parser, P, cmdParams, auditParams):

    # Fail if we got any arguments.
    if P.targets:
        parser.error("too many arguments")

    # Setup a dummy environment so we can call the API.
    with PluginTester(autoinit=False) as t:
        t.orchestrator_config.ui_mode = "console"
        t.orchestrator_config.verbose = cmdParams.verbose
        t.orchestrator_config.color   = cmdParams.color
        t.init_environment(mock_audit=False)

        # Flag to tell if we fetched new code.
        did_update = False

        # Run Git here to download the latest version.
        if cmdParams.verbose:
            Logger.log("Updating GoLismero...")
        if os.path.exists(os.path.join(here, ".git")):
            helper = _GitHelper(cmdParams.verbose)
            run_external_tool("git", ["pull"], cwd = here, callback = helper)
            did_update = helper.did_update
        elif cmdParams.verbose:
            Logger.log_error(
                "Cannot update GoLismero if installed from a zip file! You"
                " must install it from the Git repository to get updates.")

        # Update the TLD names.
        if cmdParams.verbose:
            Logger.log("Updating list of TLD names...")
        import tldextract
        tldextract.TLDExtract().update(True)

        # If no code was updated, just quit here.
        if not did_update:
            if cmdParams.verbose:
                Logger.log("Update complete.")
            exit(0)

        # Tell the user we're about to restart.
        if cmdParams.verbose:
            Logger.log("Reloading GoLismero...")

    # Unload GoLismero.
    import golismero.patches.mp
    golismero.patches.mp.undo()
    x = here
    if not x.endswith(os.path.sep):
        x += os.path.sep
    our_modules = {
        n: m for n, m in sys.modules.iteritems()
        if n.startswith("golismero.") or (
            hasattr(m, "__file__") and m.__file__.startswith(x)
        )
    }
    for n in our_modules.iterkeys():
        if n.startswith("golismero.") or n.startswith("plugin_"):
            del sys.modules[n]

    # Restart GoLismero.
    # Note that after this point we need to explicitly import the classes we
    # use, and make sure they're the newer versions of them. That means:
    # ALWAYS USE FULLY QUALIFIED NAMES FROM HERE ON.
    import golismero.api.logger
    import golismero.main.testing
    with golismero.main.testing.PluginTester(autoinit=False) as t:
        t.orchestrator_config.ui_mode = "console"
        t.orchestrator_config.verbose = cmdParams.verbose
        t.orchestrator_config.color   = cmdParams.color
        t.init_environment(mock_audit=False)

        # Call the plugin hooks.
        all_plugins = sorted(
            t.orchestrator.pluginManager.load_plugins().iteritems())
        for plugin_id, plugin in all_plugins:
            if hasattr(plugin, "update"):
                if cmdParams.verbose:
                    golismero.api.logger.Logger.log(
                        "Updating plugin %r..." % plugin_id)
                try:
                    t.run_plugin_method(plugin_id, "update")
                except Exception:
                    golismero.api.logger.Logger.log_error(format_exc())

        # Done!
        if cmdParams.verbose:
            golismero.api.logger.Logger.log("Update complete.")
        exit(0)

Example 11

Project: apiary Source File: lsprof.py
Function: label
def label(code):
    if isinstance(code, str):
        return code
    try:
        mname = _fn2mod[code.co_filename]
    except KeyError:
        for k, v in sys.modules.iteritems():
            if v is None:
                continue
            if not hasattr(v, '__file__'):
                continue
            if not isinstance(v.__file__, str):
                continue
            if v.__file__.startswith(code.co_filename):
                mname = _fn2mod[code.co_filename] = k
                break
        else:
            mname = _fn2mod[code.co_filename] = '<%s>' % code.co_filename

    return '%s:%d(%s)' % (mname, code.co_firstlineno, code.co_name)