pkgutil.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  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. try:
  338. importer = sys.path_importer_cache[path_item]
  339. except KeyError:
  340. for path_hook in sys.path_hooks:
  341. try:
  342. importer = path_hook(path_item)
  343. sys.path_importer_cache.setdefault(path_item, importer)
  344. break
  345. except ImportError:
  346. pass
  347. else:
  348. importer = None
  349. return importer
  350. def iter_importers(fullname=""):
  351. """Yield finders for the given module name
  352. If fullname contains a '.', the finders will be for the package
  353. containing fullname, otherwise they will be all registered top level
  354. finders (i.e. those on both sys.meta_path and sys.path_hooks).
  355. If the named module is in a package, that package is imported as a side
  356. effect of invoking this function.
  357. If no module name is specified, all top level finders are produced.
  358. """
  359. if fullname.startswith('.'):
  360. msg = "Relative module name {!r} not supported".format(fullname)
  361. raise ImportError(msg)
  362. if '.' in fullname:
  363. # Get the containing package's __path__
  364. pkg_name = fullname.rpartition(".")[0]
  365. pkg = importlib.import_module(pkg_name)
  366. path = getattr(pkg, '__path__', None)
  367. if path is None:
  368. return
  369. else:
  370. yield from sys.meta_path
  371. path = sys.path
  372. for item in path:
  373. yield get_importer(item)
  374. def get_loader(module_or_name):
  375. """Get a "loader" object for module_or_name
  376. Returns None if the module cannot be found or imported.
  377. If the named module is not already imported, its containing package
  378. (if any) is imported, in order to establish the package __path__.
  379. """
  380. if module_or_name in sys.modules:
  381. module_or_name = sys.modules[module_or_name]
  382. if module_or_name is None:
  383. return None
  384. if isinstance(module_or_name, ModuleType):
  385. module = module_or_name
  386. loader = getattr(module, '__loader__', None)
  387. if loader is not None:
  388. return loader
  389. if getattr(module, '__spec__', None) is None:
  390. return None
  391. fullname = module.__name__
  392. else:
  393. fullname = module_or_name
  394. return find_loader(fullname)
  395. def find_loader(fullname):
  396. """Find a "loader" object for fullname
  397. This is a backwards compatibility wrapper around
  398. importlib.util.find_spec that converts most failures to ImportError
  399. and only returns the loader rather than the full spec
  400. """
  401. if fullname.startswith('.'):
  402. msg = "Relative module name {!r} not supported".format(fullname)
  403. raise ImportError(msg)
  404. try:
  405. spec = importlib.util.find_spec(fullname)
  406. except (ImportError, AttributeError, TypeError, ValueError) as ex:
  407. # This hack fixes an impedance mismatch between pkgutil and
  408. # importlib, where the latter raises other errors for cases where
  409. # pkgutil previously raised ImportError
  410. msg = "Error while finding loader for {!r} ({}: {})"
  411. raise ImportError(msg.format(fullname, type(ex), ex)) from ex
  412. return spec.loader if spec is not None else None
  413. def extend_path(path, name):
  414. """Extend a package's path.
  415. Intended use is to place the following code in a package's __init__.py:
  416. from pkgutil import extend_path
  417. __path__ = extend_path(__path__, __name__)
  418. This will add to the package's __path__ all subdirectories of
  419. directories on sys.path named after the package. This is useful
  420. if one wants to distribute different parts of a single logical
  421. package as multiple directories.
  422. It also looks for *.pkg files beginning where * matches the name
  423. argument. This feature is similar to *.pth files (see site.py),
  424. except that it doesn't special-case lines starting with 'import'.
  425. A *.pkg file is trusted at face value: apart from checking for
  426. duplicates, all entries found in a *.pkg file are added to the
  427. path, regardless of whether they are exist the filesystem. (This
  428. is a feature.)
  429. If the input path is not a list (as is the case for frozen
  430. packages) it is returned unchanged. The input path is not
  431. modified; an extended copy is returned. Items are only appended
  432. to the copy at the end.
  433. It is assumed that sys.path is a sequence. Items of sys.path that
  434. are not (unicode or 8-bit) strings referring to existing
  435. directories are ignored. Unicode items of sys.path that cause
  436. errors when used as filenames may cause this function to raise an
  437. exception (in line with os.path.isdir() behavior).
  438. """
  439. if not isinstance(path, list):
  440. # This could happen e.g. when this is called from inside a
  441. # frozen package. Return the path unchanged in that case.
  442. return path
  443. sname_pkg = name + ".pkg"
  444. path = path[:] # Start with a copy of the existing path
  445. parent_package, _, final_name = name.rpartition('.')
  446. if parent_package:
  447. try:
  448. search_path = sys.modules[parent_package].__path__
  449. except (KeyError, AttributeError):
  450. # We can't do anything: find_loader() returns None when
  451. # passed a dotted name.
  452. return path
  453. else:
  454. search_path = sys.path
  455. for dir in search_path:
  456. if not isinstance(dir, str):
  457. continue
  458. finder = get_importer(dir)
  459. if finder is not None:
  460. portions = []
  461. if hasattr(finder, 'find_spec'):
  462. spec = finder.find_spec(final_name)
  463. if spec is not None:
  464. portions = spec.submodule_search_locations or []
  465. # Is this finder PEP 420 compliant?
  466. elif hasattr(finder, 'find_loader'):
  467. _, portions = finder.find_loader(final_name)
  468. for portion in portions:
  469. # XXX This may still add duplicate entries to path on
  470. # case-insensitive filesystems
  471. if portion not in path:
  472. path.append(portion)
  473. # XXX Is this the right thing for subpackages like zope.app?
  474. # It looks for a file named "zope.app.pkg"
  475. pkgfile = os.path.join(dir, sname_pkg)
  476. if os.path.isfile(pkgfile):
  477. try:
  478. f = open(pkgfile)
  479. except OSError as msg:
  480. sys.stderr.write("Can't open %s: %s\n" %
  481. (pkgfile, msg))
  482. else:
  483. with f:
  484. for line in f:
  485. line = line.rstrip('\n')
  486. if not line or line.startswith('#'):
  487. continue
  488. path.append(line) # Don't check for existence!
  489. return path
  490. def get_data(package, resource):
  491. """Get a resource from a package.
  492. This is a wrapper round the PEP 302 loader get_data API. The package
  493. argument should be the name of a package, in standard module format
  494. (foo.bar). The resource argument should be in the form of a relative
  495. filename, using '/' as the path separator. The parent directory name '..'
  496. is not allowed, and nor is a rooted name (starting with a '/').
  497. The function returns a binary string, which is the contents of the
  498. specified resource.
  499. For packages located in the filesystem, which have already been imported,
  500. this is the rough equivalent of
  501. d = os.path.dirname(sys.modules[package].__file__)
  502. data = open(os.path.join(d, resource), 'rb').read()
  503. If the package cannot be located or loaded, or it uses a PEP 302 loader
  504. which does not support get_data(), then None is returned.
  505. """
  506. spec = importlib.util.find_spec(package)
  507. if spec is None:
  508. return None
  509. loader = spec.loader
  510. if loader is None or not hasattr(loader, 'get_data'):
  511. return None
  512. # XXX needs test
  513. mod = (sys.modules.get(package) or
  514. importlib._bootstrap._load(spec))
  515. if mod is None or not hasattr(mod, '__file__'):
  516. return None
  517. # Modify the resource name to be compatible with the loader.get_data
  518. # signature - an os.path format "filename" starting with the dirname of
  519. # the package's __file__
  520. parts = resource.split('/')
  521. parts.insert(0, os.path.dirname(mod.__file__))
  522. resource_name = os.path.join(*parts)
  523. return loader.get_data(resource_name)
  524. _DOTTED_WORDS = r'(?!\d)(\w+)(\.(?!\d)(\w+))*'
  525. _NAME_PATTERN = re.compile(f'^(?P<pkg>{_DOTTED_WORDS})(?P<cln>:(?P<obj>{_DOTTED_WORDS})?)?$', re.U)
  526. del _DOTTED_WORDS
  527. def resolve_name(name):
  528. """
  529. Resolve a name to an object.
  530. It is expected that `name` will be a string in one of the following
  531. formats, where W is shorthand for a valid Python identifier and dot stands
  532. for a literal period in these pseudo-regexes:
  533. W(.W)*
  534. W(.W)*:(W(.W)*)?
  535. The first form is intended for backward compatibility only. It assumes that
  536. some part of the dotted name is a package, and the rest is an object
  537. somewhere within that package, possibly nested inside other objects.
  538. Because the place where the package stops and the object hierarchy starts
  539. can't be inferred by inspection, repeated attempts to import must be done
  540. with this form.
  541. In the second form, the caller makes the division point clear through the
  542. provision of a single colon: the dotted name to the left of the colon is a
  543. package to be imported, and the dotted name to the right is the object
  544. hierarchy within that package. Only one import is needed in this form. If
  545. it ends with the colon, then a module object is returned.
  546. The function will return an object (which might be a module), or raise one
  547. of the following exceptions:
  548. ValueError - if `name` isn't in a recognised format
  549. ImportError - if an import failed when it shouldn't have
  550. AttributeError - if a failure occurred when traversing the object hierarchy
  551. within the imported package to get to the desired object)
  552. """
  553. m = _NAME_PATTERN.match(name)
  554. if not m:
  555. raise ValueError(f'invalid format: {name!r}')
  556. gd = m.groupdict()
  557. if gd.get('cln'):
  558. # there is a colon - a one-step import is all that's needed
  559. mod = importlib.import_module(gd['pkg'])
  560. parts = gd.get('obj')
  561. parts = parts.split('.') if parts else []
  562. else:
  563. # no colon - have to iterate to find the package boundary
  564. parts = name.split('.')
  565. modname = parts.pop(0)
  566. # first part *must* be a module/package.
  567. mod = importlib.import_module(modname)
  568. while parts:
  569. p = parts[0]
  570. s = f'{modname}.{p}'
  571. try:
  572. mod = importlib.import_module(s)
  573. parts.pop(0)
  574. modname = s
  575. except ImportError:
  576. break
  577. # if we reach this point, mod is the module, already imported, and
  578. # parts is the list of parts in the object hierarchy to be traversed, or
  579. # an empty list if just the module is wanted.
  580. result = mod
  581. for p in parts:
  582. result = getattr(result, p)
  583. return result