当前位置: 首页>>代码示例>>Python>>正文


Python sys.modules方法代码示例

本文整理汇总了Python中sys.modules方法的典型用法代码示例。如果您正苦于以下问题:Python sys.modules方法的具体用法?Python sys.modules怎么用?Python sys.modules使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sys的用法示例。


在下文中一共展示了sys.modules方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: load_module

# 需要导入模块: import sys [as 别名]
# 或者: from sys import modules [as 别名]
def load_module(self, fullname):
        print('load_module {}'.format(fullname))
        if fullname in sys.modules:
            return sys.modules[fullname]

        # 先从 sys.meta_path 中删除自定义的 finder
        # 防止下面执行 import_module 的时候再次触发此 finder
        # 从而出现递归调用的问题
        finder = sys.meta_path.pop(0)
        # 导入 module
        module = importlib.import_module(fullname)

        module_hook(fullname, module)

        sys.meta_path.insert(0, finder)
        return module 
开发者ID:mozillazg,项目名称:apm-python-agent-principle,代码行数:18,代码来源:_hook.py

示例2: mock_pywin32

# 需要导入模块: import sys [as 别名]
# 或者: from sys import modules [as 别名]
def mock_pywin32():
    """Mock pywin32 module.

    Resulting in Linux hosts, including ReadTheDocs,
    and other environments that don't have pywin32 can generate the docs
    properly including the PDF version.
    See:
    http://read-the-docs.readthedocs.org/en/latest/faq.html#i-get-import-errors-on-libraries-that-depend-on-c-modules
    """
    if try_import('win32api'):
        return

    from unittest import mock

    MOCK_MODULES = [
        'win32api', 'win32con', 'win32event', 'win32service',
        'win32serviceutil',
    ]
    for mod_name in MOCK_MODULES:
        sys.modules[mod_name] = mock.MagicMock() 
开发者ID:cherrypy,项目名称:cherrypy,代码行数:22,代码来源:conf.py

示例3: build_Name

# 需要导入模块: import sys [as 别名]
# 或者: from sys import modules [as 别名]
def build_Name(self, o):
        name = o.id
        if name == 'None':
            return None
        if name == 'True':
            return True
        if name == 'False':
            return False

        # See if the Name is a package or module. If it is, import it.
        try:
            return modules(name)
        except ImportError:
            pass

        # See if the Name is in builtins.
        try:
            return getattr(builtins, name)
        except AttributeError:
            pass

        raise TypeError('unrepr could not resolve the name %s' % repr(name)) 
开发者ID:cherrypy,项目名称:cherrypy,代码行数:24,代码来源:reprconf.py

示例4: attributes

# 需要导入模块: import sys [as 别名]
# 或者: from sys import modules [as 别名]
def attributes(full_attribute_name):
    """Load a module and retrieve an attribute of that module."""

    # Parse out the path, module, and attribute
    last_dot = full_attribute_name.rfind('.')
    attr_name = full_attribute_name[last_dot + 1:]
    mod_path = full_attribute_name[:last_dot]

    mod = modules(mod_path)
    # Let an AttributeError propagate outward.
    try:
        attr = getattr(mod, attr_name)
    except AttributeError:
        raise AttributeError("'%s' object has no attribute '%s'"
                             % (mod_path, attr_name))

    # Return a reference to the attribute.
    return attr 
开发者ID:cherrypy,项目名称:cherrypy,代码行数:20,代码来源:reprconf.py

示例5: __call__

# 需要导入模块: import sys [as 别名]
# 或者: from sys import modules [as 别名]
def __call__(self, func):
        module = sys.modules[func.__module__]

        # Get the command name as Django expects it
        self.name = func.__module__.rsplit(".", 1)[-1]

        # Build the click command
        decorators = [
            click.command(name=self.name, cls=self.cls, **self.kwargs),
        ] + self.get_params(self.name)

        for decorator in reversed(decorators):
            func = decorator(func)

        # Django expects the command to be callable (it instantiates the class
        # pointed at by the `Command` module-level property)...
        # ...let's make it happy.
        module.Command = lambda: func

        return func 
开发者ID:GaretJax,项目名称:django-click,代码行数:22,代码来源:adapter.py

示例6: unloadmodcmd

# 需要导入模块: import sys [as 别名]
# 或者: from sys import modules [as 别名]
def unloadmodcmd(self, message):
        """Unload module by class name"""
        args = utils.get_args(message)
        if not args:
            await utils.answer(message, self.strings["what_class"])
            return
        clazz = args[0]
        worked = self.allmodules.unload_module(clazz)
        without_prefix = []
        for mod in worked:
            assert mod.startswith("friendly-telegram.modules."), mod
            without_prefix += [unescape_percent(mod[len("friendly-telegram.modules."):])]
        it = set(self._db.get(__name__, "loaded_modules", [])).difference(without_prefix)
        self._db.set(__name__, "loaded_modules", list(it))
        it = set(self._db.get(__name__, "unloaded_modules", [])).union(without_prefix)
        self._db.set(__name__, "unloaded_modules", list(it))
        if worked:
            await utils.answer(message, self.strings["unloaded"])
        else:
            await utils.answer(message, self.strings["not_unloaded"]) 
开发者ID:friendly-telegram,项目名称:friendly-telegram,代码行数:22,代码来源:loader.py

示例7: reload_neuropythy

# 需要导入模块: import sys [as 别名]
# 或者: from sys import modules [as 别名]
def reload_neuropythy():
    '''
    reload_neuropythy() reloads all of the modules of neuropythy and returns the reloaded
    neuropythy module. This is similar to reload(neuropythy) except that it reloads all the
    neuropythy submodules prior to reloading neuropythy.

    Example:
      import neuropythy as ny
      # ... some nonsense that breaks the library ...
      ny = ny.reload_neuropythy()
    '''
    import sys, six
    if not six.PY2:
        try:              from importlib import reload
        except Exception: from imp import reload
    for mdl in submodules:
        if mdl in sys.modules:
            sys.modules[mdl] = reload(sys.modules[mdl])
    return reload(sys.modules['neuropythy']) 
开发者ID:noahbenson,项目名称:neuropythy,代码行数:21,代码来源:__init__.py

示例8: _init_torch_module

# 需要导入模块: import sys [as 别名]
# 或者: from sys import modules [as 别名]
def _init_torch_module():
    """List and add all the torch backed ndarray functions to current module."""
    plist = ctypes.POINTER(FunctionHandle)()
    size = ctypes.c_uint()
    check_call(_LIB.MXListFunctions(ctypes.byref(size),
                                    ctypes.byref(plist)))

    module_obj = sys.modules[__name__]
    for i in range(size.value):
        hdl = FunctionHandle(plist[i])
        function = _make_torch_function(hdl)
        # if function name starts with underscore, register as static method of NDArray
        if function is not None:
            setattr(module_obj, function.__name__, function)

# Initialize the NDArray module 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:18,代码来源:torch.py

示例9: iterate_module_attributes

# 需要导入模块: import sys [as 别名]
# 或者: from sys import modules [as 别名]
def iterate_module_attributes(module):
    """
    Iterate over the attributes in a module.

    This is a generator function.

    Returns (name, value) tuples.
    """
    for name in dir(module):
        # Ignore fields marked as private or builtin.
        if name.startswith('_'):
            continue

        value = getattr(module, name)

        # Ignore callable objects (functions) and loaded modules.
        if callable(value) or isinstance(value, types.ModuleType):
            continue

        yield (name, value) 
开发者ID:ParadropLabs,项目名称:Paradrop,代码行数:22,代码来源:settings.py

示例10: load_from_file

# 需要导入模块: import sys [as 别名]
# 或者: from sys import modules [as 别名]
def load_from_file(path):
    """
    Load settings from an INI file.

    This will check the configuration file for a lowercase version of all of
    the settings in this module. It will look in a section called "base".

    The example below will set PORTAL_SERVER_PORT.

        [base]
        portal_server_port = 4444
    """
    config = configparser.SafeConfigParser()
    config.read(path)

    mod = sys.modules[__name__]
    for name, _ in iterate_module_attributes(mod):
        # Check if lowercase version exists in the file and load the
        # appropriately-typed value.
        key = name.lower()
        if config.has_option(constants.BASE_SETTINGS_SECTION, key):
            value = config.get(constants.BASE_SETTINGS_SECTION, key)
            setattr(mod, name, parseValue(value)) 
开发者ID:ParadropLabs,项目名称:Paradrop,代码行数:25,代码来源:settings.py

示例11: updatePaths

# 需要导入模块: import sys [as 别名]
# 或者: from sys import modules [as 别名]
def updatePaths(configHomeDir, runtimeHomeDir="/var/run/paradrop"):
    # Get a handle to our settings defined above
    mod = sys.modules[__name__]

    mod.CONFIG_HOME_DIR = configHomeDir
    mod.RUNTIME_HOME_DIR = runtimeHomeDir
    mod.FC_CHUTESTORAGE_FILE = os.path.join(mod.CONFIG_HOME_DIR, "chutes")
    mod.EXTERNAL_DATA_DIR = os.path.join(mod.CONFIG_HOME_DIR, "chute-data/{chute}/")
    mod.EXTERNAL_SYSTEM_DIR = os.path.join(runtimeHomeDir, "system", "{chute}")
    mod.LOG_DIR = os.path.join(mod.CONFIG_HOME_DIR, "logs/")
    mod.KEY_DIR = os.path.join(mod.CONFIG_HOME_DIR, "keys/")
    mod.MISC_DIR = os.path.join(mod.CONFIG_HOME_DIR, "misc/")
    mod.CONFIG_FILE = os.path.join(mod.CONFIG_HOME_DIR, "config")
    mod.HOST_CONFIG_FILE = os.path.join(mod.CONFIG_HOME_DIR, "hostconfig.yaml")
    mod.DEFAULT_HOST_CONFIG_FILE = os.path.join(mod.CONFIG_HOME_DIR, "hostconfig.default.yaml")
    mod.UCI_CONFIG_DIR = os.path.join(mod.CONFIG_HOME_DIR, "uci/config.d/")
    mod.UCI_BACKUP_DIR = os.path.join(mod.CONFIG_HOME_DIR, "uci/config-backup.d/")
    mod.PDCONFD_WRITE_DIR = os.path.join(mod.RUNTIME_HOME_DIR, 'pdconfd') 
开发者ID:ParadropLabs,项目名称:Paradrop,代码行数:20,代码来源:settings.py

示例12: test_iter_builders_side_effect

# 需要导入模块: import sys [as 别名]
# 或者: from sys import modules [as 别名]
def test_iter_builders_side_effect(self):
        # inject dummy module and add cleanup
        mod = ModuleType('calmjs_testing_dummy')
        mod.complete = generic_builder
        self.addCleanup(sys.modules.pop, 'calmjs_testing_dummy')
        sys.modules['calmjs_testing_dummy'] = mod

        working_dir = utils.mkdtemp(self)
        utils.make_dummy_dist(self, (
            ('entry_points.txt', '\n'.join([
                '[calmjs.artifacts]',
                'artifact.js = calmjs_testing_dummy:complete',
            ])),
        ), 'app', '1.0', working_dir=working_dir)
        mock_ws = WorkingSet([working_dir])
        registry = ArtifactRegistry('calmjs.artifacts', _working_set=mock_ws)
        registry.update_artifact_metadata('app', {})

        root = join(working_dir, 'app-1.0.egg-info', 'calmjs_artifacts')
        self.assertFalse(exists(root))
        ep, toolchain, spec = next(registry.iter_builders_for('app'))
        self.assertFalse(exists(root))
        # directory only created after the toolchain is executed
        toolchain(spec)
        self.assertTrue(exists(root)) 
开发者ID:calmjs,项目名称:calmjs,代码行数:27,代码来源:test_artifact.py

示例13: test_missing_distribution

# 需要导入模块: import sys [as 别名]
# 或者: from sys import modules [as 别名]
def test_missing_distribution(self):
        d_egg_root = join(mkdtemp(self), 'dummyns')
        make_dummy_dist(self, ((
            'namespace_packages.txt',
            'not_ns\n',
        ), (
            'entry_points.txt',
            '[dummyns]\n'
            'dummyns = dummyns:attr\n',
        ),), 'dummyns', '2.0', working_dir=d_egg_root)
        working_set = pkg_resources.WorkingSet([
            d_egg_root,
            self.ds_egg_root,
        ])
        dummyns_ep = next(working_set.iter_entry_points('dummyns'))
        with pretty_logging(stream=StringIO()) as fd:
            p = indexer.resource_filename_mod_entry_point(
                'dummyns', dummyns_ep)
        # not stubbed working_set, so this is derived using fallback
        # value from the sys.modules['dummyns'] location
        self.assertEqual(normcase(p), normcase(self.dummyns_path))
        self.assertIn("distribution 'dummyns 2.0' not found", fd.getvalue()) 
开发者ID:calmjs,项目名称:calmjs,代码行数:24,代码来源:test_indexer.py

示例14: _patch_modules

# 需要导入模块: import sys [as 别名]
# 或者: from sys import modules [as 别名]
def _patch_modules() -> None:
    if "flask" in sys.modules:
        raise ImportError("Cannot mock flask, already imported")

    # Create a set of Flask modules, prioritising those within the
    # flask_patch namespace over simple references to the Quart
    # versions.
    flask_modules = {}
    for name, module in list(sys.modules.items()):
        if name.startswith("quart.flask_patch._"):
            continue
        elif name.startswith("quart.flask_patch"):
            setattr(module, "_QUART_PATCHED", True)
            flask_modules[name.replace("quart.flask_patch", "flask")] = module
        elif name.startswith("quart.") and not name.startswith("quart.serving"):
            flask_name = name.replace("quart.", "flask.")
            if flask_name not in flask_modules:
                flask_modules[flask_name] = _convert_module(flask_name, module)

    sys.modules.update(flask_modules) 
开发者ID:pgjones,项目名称:quart,代码行数:22,代码来源:_patch.py

示例15: find_package

# 需要导入模块: import sys [as 别名]
# 或者: from sys import modules [as 别名]
def find_package(name: str) -> Tuple[Optional[Path], Path]:
    """Finds packages install prefix (or None) and it's containing Folder
    """
    module = name.split(".")[0]
    loader = pkgutil.get_loader(module)
    if name == "__main__" or loader is None:
        package_path = Path.cwd()
    else:
        if hasattr(loader, "get_filename"):
            filename = loader.get_filename(module)  # type: ignore
        else:
            __import__(name)
            filename = sys.modules[name].__file__
        package_path = Path(filename).resolve().parent
        if hasattr(loader, "is_package"):
            is_package = loader.is_package(module)  # type: ignore
            if is_package:
                package_path = Path(package_path).resolve().parent
    sys_prefix = Path(sys.prefix).resolve()
    try:
        package_path.relative_to(sys_prefix)
    except ValueError:
        return None, package_path
    else:
        return sys_prefix, package_path 
开发者ID:pgjones,项目名称:quart,代码行数:27,代码来源:helpers.py


注:本文中的sys.modules方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。