import sys, imp, os from importlib._bootstrap import set_package, set_loader, FileFinder from importlib._bootstrap import ExtensionFileLoader, SourceFileLoader from importlib._bootstrap import SourcelessFileLoader from importlib._bootstrap import SOURCE_SUFFIXES, BYTECODE_SUFFIXES class WindowsRegistryImporter: """Meta path import for modules declared in the Windows registry. """ REGISTRY_KEY = ("Software\\Python\\PythonCore\\{sys_version}" "\\Modules\\{fullname}") if '_d.pyd' in imp.extension_suffixes(): REGISTRY_KEY += "\\Debug" @classmethod def _open_registry(cls, key): try: return winreg.OpenKey(winreg.HKEY_CURRENT_USER, key) except WindowsError: return winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key) @classmethod def _search_registry(cls, fullname): key = cls.REGISTRY_KEY.format(fullname=fullname, sys_version=sys.version[:3]) try: with cls._open_registry(key) as hkey: fullname = winreg.QueryValue(hkey, "") except WindowsError: return None return fullname # XXX reuse code from _bootstrap._install() LOADERS = [ (ExtensionFileLoader, imp.extension_suffixes()), (SourceFileLoader, SOURCE_SUFFIXES), (SourcelessFileLoader, BYTECODE_SUFFIXES)] @classmethod def find_module(cls, fullname, path=None): """Find module named in the registry.""" full_path = cls._search_registry(fullname) if full_path is None: return None try: os.stat(full_path) except OSError: return None for loader, suffixes in cls.LOADERS: if full_path.endswith(tuple(suffixes)): return loader(fullname, full_path) sys.meta_path.append(WindowsRegistryImporter) # A small fake winreg implementation for non-windows platforms... try: WindowsError import winreg except (ImportError, NameError): WindowsError = ValueError class winreg: FAKE_REGISTRY = { r"Software\Python\PythonCore\3.3\Modules\from_registry": "/home/amauryfa/python/cpython3.x/setup.py", } HKEY_CURRENT_USER = "HKCU" HKEY_LOCAL_MACHINE = "HKLM" @staticmethod def OpenKey(root, key): if key in winreg.FAKE_REGISTRY: return winreg(key) else: raise WindowsError def QueryValue(self, subkey): assert not subkey return winreg.FAKE_REGISTRY[self.key] def __init__(self, key): self.key = key def __enter__(self): return self def __exit__(self, *args): pass # Test it! import from_registry print(from_registry)