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.

20 Examples 7

Example 1

Project: nvda
Source File: appModuleHandler.py
View license
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
View license
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
View license
	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: PythonHotswap
Source File: ExtendedPickler.py
View license
	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 5

Project: ggrc-core
Source File: package.py
View license
  @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 6

Project: LiveRemoteScripts
Source File: debug.py
View license
	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 7

Project: LiveRemoteScripts
Source File: debug.py
View license
	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 8

Project: LiveRemoteScripts
Source File: Debug.py
View license
	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 9

Project: LiveRemoteScripts
Source File: Debug.py
View license
	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 10

Project: LiveRemoteScripts
Source File: Debug.py.new.py
View license
	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 11

Project: LiveRemoteScripts
Source File: Debug.py.new.py
View license
	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 12

Project: wxbanker
Source File: pubsubconf.py
View license
    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 13

Project: wxbanker
Source File: pubsubconf.py
View license
    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 14

Project: dodai-compute
Source File: flags.py
View license
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 15

Project: dodai-compute
Source File: flags.py
View license
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 16

Project: calabash
Source File: __init__.py
View license
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 17

Project: jsonpipe
Source File: __init__.py
View license
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 18

Project: golismero
Source File: golismero.py
View license
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 19

Project: apiary
Source File: lsprof.py
View license
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)

Example 20

Project: apiary
Source File: lsprof.py
View license
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)