_imp.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 importlib.util 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_spec(module, paths):
  15. finder = (
  16. importlib.machinery.PathFinder().find_spec
  17. if isinstance(paths, list)
  18. else importlib.util.find_spec
  19. )
  20. return finder(module, paths)
  21. def find_module(module, paths=None):
  22. """Just like 'imp.find_module()', but with package support"""
  23. spec = find_spec(module, paths)
  24. if spec is None:
  25. raise ImportError("Can't find %s" % module)
  26. if not spec.has_location and hasattr(spec, 'submodule_search_locations'):
  27. spec = importlib.util.spec_from_loader('__init__.py', spec.loader)
  28. kind = -1
  29. file = None
  30. static = isinstance(spec.loader, type)
  31. if (
  32. spec.origin == 'frozen'
  33. or static
  34. and issubclass(spec.loader, importlib.machinery.FrozenImporter)
  35. ):
  36. kind = PY_FROZEN
  37. path = None # imp compabilty
  38. suffix = mode = '' # imp compatibility
  39. elif (
  40. spec.origin == 'built-in'
  41. or static
  42. and issubclass(spec.loader, importlib.machinery.BuiltinImporter)
  43. ):
  44. kind = C_BUILTIN
  45. path = None # imp compabilty
  46. suffix = mode = '' # imp compatibility
  47. elif spec.has_location:
  48. path = spec.origin
  49. suffix = os.path.splitext(path)[1]
  50. mode = 'r' if suffix in importlib.machinery.SOURCE_SUFFIXES else 'rb'
  51. if suffix in importlib.machinery.SOURCE_SUFFIXES:
  52. kind = PY_SOURCE
  53. elif suffix in importlib.machinery.BYTECODE_SUFFIXES:
  54. kind = PY_COMPILED
  55. elif suffix in importlib.machinery.EXTENSION_SUFFIXES:
  56. kind = C_EXTENSION
  57. if kind in {PY_SOURCE, PY_COMPILED}:
  58. file = open(path, mode)
  59. else:
  60. path = None
  61. suffix = mode = ''
  62. return file, path, (suffix, mode, kind)
  63. def get_frozen_object(module, paths=None):
  64. spec = find_spec(module, paths)
  65. if not spec:
  66. raise ImportError("Can't find %s" % module)
  67. return spec.loader.get_code(module)
  68. def get_module(module, paths, info):
  69. spec = find_spec(module, paths)
  70. if not spec:
  71. raise ImportError("Can't find %s" % module)
  72. return module_from_spec(spec)