pkgutil.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. """Utilities to support packages."""
  2. from collections import namedtuple
  3. from functools import singledispatch as simplegeneric
  4. import importlib
  5. import importlib.util
  6. import importlib.machinery
  7. import os
  8. import os.path
  9. import sys
  10. from types import ModuleType
  11. import warnings
  12. __all__ = [
  13. 'get_importer', 'iter_importers', 'get_loader', 'find_loader',
  14. 'walk_packages', 'iter_modules', 'get_data',
  15. 'read_code', 'extend_path',
  16. 'ModuleInfo',
  17. ]
  18. ModuleInfo = namedtuple('ModuleInfo', 'module_finder name ispkg')
  19. ModuleInfo.__doc__ = 'A namedtuple with minimal info about a module.'
  20. def read_code(stream):
  21. # This helper is needed in order for the PEP 302 emulation to
  22. # correctly handle compiled files
  23. import marshal
  24. magic = stream.read(4)
  25. if magic != importlib.util.MAGIC_NUMBER:
  26. return None
  27. stream.read(12) # Skip rest of the header
  28. return marshal.load(stream)
  29. def walk_packages(path=None, prefix='', onerror=None):
  30. """Yields ModuleInfo for all modules recursively
  31. on path, or, if path is None, all accessible modules.
  32. 'path' should be either None or a list of paths to look for
  33. modules in.
  34. 'prefix' is a string to output on the front of every module name
  35. on output.
  36. Note that this function must import all *packages* (NOT all
  37. modules!) on the given path, in order to access the __path__
  38. attribute to find submodules.
  39. 'onerror' is a function which gets called with one argument (the
  40. name of the package which was being imported) if any exception
  41. occurs while trying to import a package. If no onerror function is
  42. supplied, ImportErrors are caught and ignored, while all other
  43. exceptions are propagated, terminating the search.
  44. Examples:
  45. # list all modules python can access
  46. walk_packages()
  47. # list all submodules of ctypes
  48. walk_packages(ctypes.__path__, ctypes.__name__+'.')
  49. """
  50. def seen(p, m={}):
  51. if p in m:
  52. return True
  53. m[p] = True
  54. for info in iter_modules(path, prefix):
  55. yield info
  56. if info.ispkg:
  57. try:
  58. __import__(info.name)
  59. except ImportError:
  60. if onerror is not None:
  61. onerror(info.name)
  62. except Exception:
  63. if onerror is not None:
  64. onerror(info.name)
  65. else:
  66. raise
  67. else:
  68. path = getattr(sys.modules[info.name], '__path__', None) or []
  69. # don't traverse path items we've seen before
  70. path = [p for p in path if not seen(p)]
  71. yield from walk_packages(path, info.name+'.', onerror)
  72. def iter_modules(path=None, prefix=''):
  73. """Yields ModuleInfo for all submodules on path,
  74. or, if path is None, all top-level modules on sys.path.
  75. 'path' should be either None or a list of paths to look for
  76. modules in.
  77. 'prefix' is a string to output on the front of every module name
  78. on output.
  79. """
  80. if path is None:
  81. importers = iter_importers()
  82. elif isinstance(path, str):
  83. raise ValueError("path must be None or list of paths to look for "
  84. "modules in")
  85. else:
  86. importers = map(get_importer, path)
  87. yielded = {}
  88. for i in importers:
  89. for name, ispkg in iter_importer_modules(i, prefix):
  90. if name not in yielded:
  91. yielded[name] = 1
  92. yield ModuleInfo(i, name, ispkg)
  93. @simplegeneric
  94. def iter_importer_modules(importer, prefix=''):
  95. if not hasattr(importer, 'iter_modules'):
  96. return []
  97. return importer.iter_modules(prefix)
  98. # Implement a file walker for the normal importlib path hook
  99. def _iter_file_finder_modules(importer, prefix=''):
  100. if importer.path is None or not os.path.isdir(importer.path):
  101. return
  102. yielded = {}
  103. import inspect
  104. try:
  105. filenames = os.listdir(importer.path)
  106. except OSError:
  107. # ignore unreadable directories like import does
  108. filenames = []
  109. filenames.sort() # handle packages before same-named modules
  110. for fn in filenames:
  111. modname = inspect.getmodulename(fn)
  112. if modname=='__init__' or modname in yielded:
  113. continue
  114. path = os.path.join(importer.path, fn)
  115. ispkg = False
  116. if not modname and os.path.isdir(path) and '.' not in fn:
  117. modname = fn
  118. try:
  119. dircontents = os.listdir(path)
  120. except OSError:
  121. # ignore unreadable directories like import does
  122. dircontents = []
  123. for fn in dircontents:
  124. subname = inspect.getmodulename(fn)
  125. if subname=='__init__':
  126. ispkg = True
  127. break
  128. else:
  129. continue # not a package
  130. if modname and '.' not in modname:
  131. yielded[modname] = 1
  132. yield prefix + modname, ispkg
  133. iter_importer_modules.register(
  134. importlib.machinery.FileFinder, _iter_file_finder_modules)
  135. try:
  136. import zipimport
  137. from zipimport import zipimporter
  138. def iter_zipimport_modules(importer, prefix=''):
  139. dirlist = sorted(zipimport._zip_directory_cache[importer.archive])
  140. _prefix = importer.prefix
  141. plen = len(_prefix)
  142. yielded = {}
  143. import inspect
  144. for fn in dirlist:
  145. if not fn.startswith(_prefix):
  146. continue
  147. fn = fn[plen:].split(os.sep)
  148. if len(fn)==2 and fn[1].startswith('__init__.py'):
  149. if fn[0] not in yielded:
  150. yielded[fn[0]] = 1
  151. yield prefix + fn[0], True
  152. if len(fn)!=1:
  153. continue
  154. modname = inspect.getmodulename(fn[0])
  155. if modname=='__init__':
  156. continue
  157. if modname and '.' not in modname and modname not in yielded:
  158. yielded[modname] = 1
  159. yield prefix + modname, False
  160. iter_importer_modules.register(zipimporter, iter_zipimport_modules)
  161. except ImportError:
  162. pass
  163. def get_importer(path_item):
  164. """Retrieve a finder for the given path item
  165. The returned finder is cached in sys.path_importer_cache
  166. if it was newly created by a path hook.
  167. The cache (or part of it) can be cleared manually if a
  168. rescan of sys.path_hooks is necessary.
  169. """
  170. path_item = os.fsdecode(path_item)
  171. try:
  172. importer = sys.path_importer_cache[path_item]
  173. except KeyError:
  174. for path_hook in sys.path_hooks:
  175. try:
  176. importer = path_hook(path_item)
  177. sys.path_importer_cache.setdefault(path_item, importer)
  178. break
  179. except ImportError:
  180. pass
  181. else:
  182. importer = None
  183. return importer
  184. def iter_importers(fullname=""):
  185. """Yield finders for the given module name
  186. If fullname contains a '.', the finders will be for the package
  187. containing fullname, otherwise they will be all registered top level
  188. finders (i.e. those on both sys.meta_path and sys.path_hooks).
  189. If the named module is in a package, that package is imported as a side
  190. effect of invoking this function.
  191. If no module name is specified, all top level finders are produced.
  192. """
  193. if fullname.startswith('.'):
  194. msg = "Relative module name {!r} not supported".format(fullname)
  195. raise ImportError(msg)
  196. if '.' in fullname:
  197. # Get the containing package's __path__
  198. pkg_name = fullname.rpartition(".")[0]
  199. pkg = importlib.import_module(pkg_name)
  200. path = getattr(pkg, '__path__', None)
  201. if path is None:
  202. return
  203. else:
  204. yield from sys.meta_path
  205. path = sys.path
  206. for item in path:
  207. yield get_importer(item)
  208. def get_loader(module_or_name):
  209. """Get a "loader" object for module_or_name
  210. Returns None if the module cannot be found or imported.
  211. If the named module is not already imported, its containing package
  212. (if any) is imported, in order to establish the package __path__.
  213. """
  214. warnings._deprecated("pkgutil.get_loader",
  215. f"{warnings._DEPRECATED_MSG}; "
  216. "use importlib.util.find_spec() instead",
  217. remove=(3, 14))
  218. if module_or_name in sys.modules:
  219. module_or_name = sys.modules[module_or_name]
  220. if module_or_name is None:
  221. return None
  222. if isinstance(module_or_name, ModuleType):
  223. module = module_or_name
  224. loader = getattr(module, '__loader__', None)
  225. if loader is not None:
  226. return loader
  227. if getattr(module, '__spec__', None) is None:
  228. return None
  229. fullname = module.__name__
  230. else:
  231. fullname = module_or_name
  232. return find_loader(fullname)
  233. def find_loader(fullname):
  234. """Find a "loader" object for fullname
  235. This is a backwards compatibility wrapper around
  236. importlib.util.find_spec that converts most failures to ImportError
  237. and only returns the loader rather than the full spec
  238. """
  239. warnings._deprecated("pkgutil.find_loader",
  240. f"{warnings._DEPRECATED_MSG}; "
  241. "use importlib.util.find_spec() instead",
  242. remove=(3, 14))
  243. if fullname.startswith('.'):
  244. msg = "Relative module name {!r} not supported".format(fullname)
  245. raise ImportError(msg)
  246. try:
  247. spec = importlib.util.find_spec(fullname)
  248. except (ImportError, AttributeError, TypeError, ValueError) as ex:
  249. # This hack fixes an impedance mismatch between pkgutil and
  250. # importlib, where the latter raises other errors for cases where
  251. # pkgutil previously raised ImportError
  252. msg = "Error while finding loader for {!r} ({}: {})"
  253. raise ImportError(msg.format(fullname, type(ex), ex)) from ex
  254. return spec.loader if spec is not None else None
  255. def extend_path(path, name):
  256. """Extend a package's path.
  257. Intended use is to place the following code in a package's __init__.py:
  258. from pkgutil import extend_path
  259. __path__ = extend_path(__path__, __name__)
  260. For each directory on sys.path that has a subdirectory that
  261. matches the package name, add the subdirectory to the package's
  262. __path__. This is useful if one wants to distribute different
  263. parts of a single logical package as multiple directories.
  264. It also looks for *.pkg files beginning where * matches the name
  265. argument. This feature is similar to *.pth files (see site.py),
  266. except that it doesn't special-case lines starting with 'import'.
  267. A *.pkg file is trusted at face value: apart from checking for
  268. duplicates, all entries found in a *.pkg file are added to the
  269. path, regardless of whether they are exist the filesystem. (This
  270. is a feature.)
  271. If the input path is not a list (as is the case for frozen
  272. packages) it is returned unchanged. The input path is not
  273. modified; an extended copy is returned. Items are only appended
  274. to the copy at the end.
  275. It is assumed that sys.path is a sequence. Items of sys.path that
  276. are not (unicode or 8-bit) strings referring to existing
  277. directories are ignored. Unicode items of sys.path that cause
  278. errors when used as filenames may cause this function to raise an
  279. exception (in line with os.path.isdir() behavior).
  280. """
  281. if not isinstance(path, list):
  282. # This could happen e.g. when this is called from inside a
  283. # frozen package. Return the path unchanged in that case.
  284. return path
  285. sname_pkg = name + ".pkg"
  286. path = path[:] # Start with a copy of the existing path
  287. parent_package, _, final_name = name.rpartition('.')
  288. if parent_package:
  289. try:
  290. search_path = sys.modules[parent_package].__path__
  291. except (KeyError, AttributeError):
  292. # We can't do anything: find_loader() returns None when
  293. # passed a dotted name.
  294. return path
  295. else:
  296. search_path = sys.path
  297. for dir in search_path:
  298. if not isinstance(dir, str):
  299. continue
  300. finder = get_importer(dir)
  301. if finder is not None:
  302. portions = []
  303. if hasattr(finder, 'find_spec'):
  304. spec = finder.find_spec(final_name)
  305. if spec is not None:
  306. portions = spec.submodule_search_locations or []
  307. # Is this finder PEP 420 compliant?
  308. elif hasattr(finder, 'find_loader'):
  309. _, portions = finder.find_loader(final_name)
  310. for portion in portions:
  311. # XXX This may still add duplicate entries to path on
  312. # case-insensitive filesystems
  313. if portion not in path:
  314. path.append(portion)
  315. # XXX Is this the right thing for subpackages like zope.app?
  316. # It looks for a file named "zope.app.pkg"
  317. pkgfile = os.path.join(dir, sname_pkg)
  318. if os.path.isfile(pkgfile):
  319. try:
  320. f = open(pkgfile)
  321. except OSError as msg:
  322. sys.stderr.write("Can't open %s: %s\n" %
  323. (pkgfile, msg))
  324. else:
  325. with f:
  326. for line in f:
  327. line = line.rstrip('\n')
  328. if not line or line.startswith('#'):
  329. continue
  330. path.append(line) # Don't check for existence!
  331. return path
  332. def get_data(package, resource):
  333. """Get a resource from a package.
  334. This is a wrapper round the PEP 302 loader get_data API. The package
  335. argument should be the name of a package, in standard module format
  336. (foo.bar). The resource argument should be in the form of a relative
  337. filename, using '/' as the path separator. The parent directory name '..'
  338. is not allowed, and nor is a rooted name (starting with a '/').
  339. The function returns a binary string, which is the contents of the
  340. specified resource.
  341. For packages located in the filesystem, which have already been imported,
  342. this is the rough equivalent of
  343. d = os.path.dirname(sys.modules[package].__file__)
  344. data = open(os.path.join(d, resource), 'rb').read()
  345. If the package cannot be located or loaded, or it uses a PEP 302 loader
  346. which does not support get_data(), then None is returned.
  347. """
  348. spec = importlib.util.find_spec(package)
  349. if spec is None:
  350. return None
  351. loader = spec.loader
  352. if loader is None or not hasattr(loader, 'get_data'):
  353. return None
  354. # XXX needs test
  355. mod = (sys.modules.get(package) or
  356. importlib._bootstrap._load(spec))
  357. if mod is None or not hasattr(mod, '__file__'):
  358. return None
  359. # Modify the resource name to be compatible with the loader.get_data
  360. # signature - an os.path format "filename" starting with the dirname of
  361. # the package's __file__
  362. parts = resource.split('/')
  363. parts.insert(0, os.path.dirname(mod.__file__))
  364. resource_name = os.path.join(*parts)
  365. return loader.get_data(resource_name)
  366. _NAME_PATTERN = None
  367. def resolve_name(name):
  368. """
  369. Resolve a name to an object.
  370. It is expected that `name` will be a string in one of the following
  371. formats, where W is shorthand for a valid Python identifier and dot stands
  372. for a literal period in these pseudo-regexes:
  373. W(.W)*
  374. W(.W)*:(W(.W)*)?
  375. The first form is intended for backward compatibility only. It assumes that
  376. some part of the dotted name is a package, and the rest is an object
  377. somewhere within that package, possibly nested inside other objects.
  378. Because the place where the package stops and the object hierarchy starts
  379. can't be inferred by inspection, repeated attempts to import must be done
  380. with this form.
  381. In the second form, the caller makes the division point clear through the
  382. provision of a single colon: the dotted name to the left of the colon is a
  383. package to be imported, and the dotted name to the right is the object
  384. hierarchy within that package. Only one import is needed in this form. If
  385. it ends with the colon, then a module object is returned.
  386. The function will return an object (which might be a module), or raise one
  387. of the following exceptions:
  388. ValueError - if `name` isn't in a recognised format
  389. ImportError - if an import failed when it shouldn't have
  390. AttributeError - if a failure occurred when traversing the object hierarchy
  391. within the imported package to get to the desired object.
  392. """
  393. global _NAME_PATTERN
  394. if _NAME_PATTERN is None:
  395. # Lazy import to speedup Python startup time
  396. import re
  397. dotted_words = r'(?!\d)(\w+)(\.(?!\d)(\w+))*'
  398. _NAME_PATTERN = re.compile(f'^(?P<pkg>{dotted_words})'
  399. f'(?P<cln>:(?P<obj>{dotted_words})?)?$',
  400. re.UNICODE)
  401. m = _NAME_PATTERN.match(name)
  402. if not m:
  403. raise ValueError(f'invalid format: {name!r}')
  404. gd = m.groupdict()
  405. if gd.get('cln'):
  406. # there is a colon - a one-step import is all that's needed
  407. mod = importlib.import_module(gd['pkg'])
  408. parts = gd.get('obj')
  409. parts = parts.split('.') if parts else []
  410. else:
  411. # no colon - have to iterate to find the package boundary
  412. parts = name.split('.')
  413. modname = parts.pop(0)
  414. # first part *must* be a module/package.
  415. mod = importlib.import_module(modname)
  416. while parts:
  417. p = parts[0]
  418. s = f'{modname}.{p}'
  419. try:
  420. mod = importlib.import_module(s)
  421. parts.pop(0)
  422. modname = s
  423. except ImportError:
  424. break
  425. # if we reach this point, mod is the module, already imported, and
  426. # parts is the list of parts in the object hierarchy to be traversed, or
  427. # an empty list if just the module is wanted.
  428. result = mod
  429. for p in parts:
  430. result = getattr(result, p)
  431. return result