pkgutil.py 24 KB

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