_imp.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. """
  2. Re-implementation of find_module and get_frozen_object
  3. from the deprecated imp module.
  4. """
  5. import os
  6. import importlib.util
  7. import importlib.machinery
  8. from .py34compat import module_from_spec
  9. PY_SOURCE = 1
  10. PY_COMPILED = 2
  11. C_EXTENSION = 3
  12. C_BUILTIN = 6
  13. PY_FROZEN = 7
  14. def find_module(module, paths=None):
  15. """Just like 'imp.find_module()', but with package support"""
  16. spec = importlib.util.find_spec(module, paths)
  17. if spec is None:
  18. raise ImportError("Can't find %s" % module)
  19. if not spec.has_location and hasattr(spec, 'submodule_search_locations'):
  20. spec = importlib.util.spec_from_loader('__init__.py', spec.loader)
  21. kind = -1
  22. file = None
  23. static = isinstance(spec.loader, type)
  24. if spec.origin == 'frozen' or static and issubclass(
  25. spec.loader, importlib.machinery.FrozenImporter):
  26. kind = PY_FROZEN
  27. path = None # imp compabilty
  28. suffix = mode = '' # imp compability
  29. elif spec.origin == 'built-in' or static and issubclass(
  30. spec.loader, importlib.machinery.BuiltinImporter):
  31. kind = C_BUILTIN
  32. path = None # imp compabilty
  33. suffix = mode = '' # imp compability
  34. elif spec.has_location:
  35. path = spec.origin
  36. suffix = os.path.splitext(path)[1]
  37. mode = 'r' if suffix in importlib.machinery.SOURCE_SUFFIXES else 'rb'
  38. if suffix in importlib.machinery.SOURCE_SUFFIXES:
  39. kind = PY_SOURCE
  40. elif suffix in importlib.machinery.BYTECODE_SUFFIXES:
  41. kind = PY_COMPILED
  42. elif suffix in importlib.machinery.EXTENSION_SUFFIXES:
  43. kind = C_EXTENSION
  44. if kind in {PY_SOURCE, PY_COMPILED}:
  45. file = open(path, mode)
  46. else:
  47. path = None
  48. suffix = mode = ''
  49. return file, path, (suffix, mode, kind)
  50. def get_frozen_object(module, paths=None):
  51. spec = importlib.util.find_spec(module, paths)
  52. if not spec:
  53. raise ImportError("Can't find %s" % module)
  54. return spec.loader.get_code(module)
  55. def get_module(module, paths, info):
  56. spec = importlib.util.find_spec(module, paths)
  57. if not spec:
  58. raise ImportError("Can't find %s" % module)
  59. return module_from_spec(spec)