codekingpro/portable-devtools
115k
1"""2Re-implementation of find_module and get_frozen_object3from the deprecated imp module.4"""5 6import importlib.machinery7import importlib.util8import os9import tokenize10from importlib.util import module_from_spec11 12PY_SOURCE = 113PY_COMPILED = 214C_EXTENSION = 315C_BUILTIN = 616PY_FROZEN = 717 18 19def find_spec(module, paths):20 finder = (21 importlib.machinery.PathFinder().find_spec22 if isinstance(paths, list)23 else importlib.util.find_spec24 )25 return finder(module, paths)26 27 28def find_module(module, paths=None):29 """Just like 'imp.find_module()', but with package support"""30 spec = find_spec(module, paths)31 if spec is None:32 raise ImportError(f"Can't find {module}")33 if not spec.has_location and hasattr(spec, 'submodule_search_locations'):34 spec = importlib.util.spec_from_loader('__init__.py', spec.loader)35 36 kind = -137 file = None38 static = isinstance(spec.loader, type)39 if (40 spec.origin == 'frozen'41 or static42 and issubclass(spec.loader, importlib.machinery.FrozenImporter)43 ):44 kind = PY_FROZEN45 path = None # imp compabilty46 suffix = mode = '' # imp compatibility47 elif (48 spec.origin == 'built-in'49 or static50 and issubclass(spec.loader, importlib.machinery.BuiltinImporter)51 ):52 kind = C_BUILTIN53 path = None # imp compabilty54 suffix = mode = '' # imp compatibility55 elif spec.has_location:56 path = spec.origin57 suffix = os.path.splitext(path)[1]58 mode = 'r' if suffix in importlib.machinery.SOURCE_SUFFIXES else 'rb'59 60 if suffix in importlib.machinery.SOURCE_SUFFIXES:61 kind = PY_SOURCE62 file = tokenize.open(path)63 elif suffix in importlib.machinery.BYTECODE_SUFFIXES:64 kind = PY_COMPILED65 file = open(path, 'rb')66 elif suffix in importlib.machinery.EXTENSION_SUFFIXES:67 kind = C_EXTENSION68 69 else:70 path = None71 suffix = mode = ''72 73 return file, path, (suffix, mode, kind)74 75 76def get_frozen_object(module, paths=None):77 spec = find_spec(module, paths)78 if not spec:79 raise ImportError(f"Can't find {module}")80 return spec.loader.get_code(module)81 82 83def get_module(module, paths, info):84 spec = find_spec(module, paths)85 if not spec:86 raise ImportError(f"Can't find {module}")87 return module_from_spec(spec)88 