You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

88 lines
2.4 KiB

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