同步操作将从 OpenHarmony-SIG/python 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
"""Utilities to support packages."""from collections import namedtuplefrom functools import singledispatch as simplegenericimport importlibimport importlib.utilimport importlib.machineryimport osimport os.pathimport sysfrom types import ModuleTypeimport warnings__all__ = ['get_importer', 'iter_importers', 'get_loader', 'find_loader','walk_packages', 'iter_modules', 'get_data','ImpImporter', 'ImpLoader', 'read_code', 'extend_path','ModuleInfo',]ModuleInfo = namedtuple('ModuleInfo', 'module_finder name ispkg')ModuleInfo.__doc__ = 'A namedtuple with minimal info about a module.'def _get_spec(finder, name):"""Return the finder-specific module spec."""# Works with legacy finders.try:find_spec = finder.find_specexcept AttributeError:loader = finder.find_module(name)if loader is None:return Nonereturn importlib.util.spec_from_loader(name, loader)else:return find_spec(name)def read_code(stream):# This helper is needed in order for the PEP 302 emulation to# correctly handle compiled filesimport marshalmagic = stream.read(4)if magic != importlib.util.MAGIC_NUMBER:return Nonestream.read(12) # Skip rest of the headerreturn marshal.load(stream)def walk_packages(path=None, prefix='', onerror=None):"""Yields ModuleInfo for all modules recursivelyon path, or, if path is None, all accessible modules.'path' should be either None or a list of paths to look formodules in.'prefix' is a string to output on the front of every module nameon output.Note that this function must import all *packages* (NOT allmodules!) on the given path, in order to access the __path__attribute to find submodules.'onerror' is a function which gets called with one argument (thename of the package which was being imported) if any exceptionoccurs while trying to import a package. If no onerror function issupplied, ImportErrors are caught and ignored, while all otherexceptions are propagated, terminating the search.Examples:# list all modules python can accesswalk_packages()# list all submodules of ctypeswalk_packages(ctypes.__path__, ctypes.__name__+'.')"""def seen(p, m={}):if p in m:return Truem[p] = Truefor info in iter_modules(path, prefix):yield infoif info.ispkg:try:__import__(info.name)except ImportError:if onerror is not None:onerror(info.name)except Exception:if onerror is not None:onerror(info.name)else:raiseelse:path = getattr(sys.modules[info.name], '__path__', None) or []# don't traverse path items we've seen beforepath = [p for p in path if not seen(p)]yield from walk_packages(path, info.name+'.', onerror)def iter_modules(path=None, prefix=''):"""Yields ModuleInfo for all submodules on path,or, if path is None, all top-level modules on sys.path.'path' should be either None or a list of paths to look formodules in.'prefix' is a string to output on the front of every module nameon output."""if path is None:importers = iter_importers()elif isinstance(path, str):raise ValueError("path must be None or list of paths to look for ""modules in")else:importers = map(get_importer, path)yielded = {}for i in importers:for name, ispkg in iter_importer_modules(i, prefix):if name not in yielded:yielded[name] = 1yield ModuleInfo(i, name, ispkg)@simplegenericdef iter_importer_modules(importer, prefix=''):if not hasattr(importer, 'iter_modules'):return []return importer.iter_modules(prefix)# Implement a file walker for the normal importlib path hookdef _iter_file_finder_modules(importer, prefix=''):if importer.path is None or not os.path.isdir(importer.path):returnyielded = {}import inspecttry:filenames = os.listdir(importer.path)except OSError:# ignore unreadable directories like import doesfilenames = []filenames.sort() # handle packages before same-named modulesfor fn in filenames:modname = inspect.getmodulename(fn)if modname=='__init__' or modname in yielded:continuepath = os.path.join(importer.path, fn)ispkg = Falseif not modname and os.path.isdir(path) and '.' not in fn:modname = fntry:dircontents = os.listdir(path)except OSError:# ignore unreadable directories like import doesdircontents = []for fn in dircontents:subname = inspect.getmodulename(fn)if subname=='__init__':ispkg = Truebreakelse:continue # not a packageif modname and '.' not in modname:yielded[modname] = 1yield prefix + modname, ispkgiter_importer_modules.register(importlib.machinery.FileFinder, _iter_file_finder_modules)def _import_imp():global impwith warnings.catch_warnings():warnings.simplefilter('ignore', DeprecationWarning)imp = importlib.import_module('imp')class ImpImporter:"""PEP 302 Finder that wraps Python's "classic" import algorithmImpImporter(dirname) produces a PEP 302 finder that searches thatdirectory. ImpImporter(None) produces a PEP 302 finder that searchesthe current sys.path, plus any modules that are frozen or built-in.Note that ImpImporter does not currently support being used by placementon sys.meta_path."""def __init__(self, path=None):global impwarnings.warn("This emulation is deprecated, use 'importlib' instead",DeprecationWarning)_import_imp()self.path = pathdef find_module(self, fullname, path=None):# Note: we ignore 'path' argument since it is only used via meta_pathsubname = fullname.split(".")[-1]if subname != fullname and self.path is None:return Noneif self.path is None:path = Noneelse:path = [os.path.realpath(self.path)]try:file, filename, etc = imp.find_module(subname, path)except ImportError:return Nonereturn ImpLoader(fullname, file, filename, etc)def iter_modules(self, prefix=''):if self.path is None or not os.path.isdir(self.path):returnyielded = {}import inspecttry:filenames = os.listdir(self.path)except OSError:# ignore unreadable directories like import doesfilenames = []filenames.sort() # handle packages before same-named modulesfor fn in filenames:modname = inspect.getmodulename(fn)if modname=='__init__' or modname in yielded:continuepath = os.path.join(self.path, fn)ispkg = Falseif not modname and os.path.isdir(path) and '.' not in fn:modname = fntry:dircontents = os.listdir(path)except OSError:# ignore unreadable directories like import doesdircontents = []for fn in dircontents:subname = inspect.getmodulename(fn)if subname=='__init__':ispkg = Truebreakelse:continue # not a packageif modname and '.' not in modname:yielded[modname] = 1yield prefix + modname, ispkgclass ImpLoader:"""PEP 302 Loader that wraps Python's "classic" import algorithm"""code = source = Nonedef __init__(self, fullname, file, filename, etc):warnings.warn("This emulation is deprecated, use 'importlib' instead",DeprecationWarning)_import_imp()self.file = fileself.filename = filenameself.fullname = fullnameself.etc = etcdef load_module(self, fullname):self._reopen()try:mod = imp.load_module(fullname, self.file, self.filename, self.etc)finally:if self.file:self.file.close()# Note: we don't set __loader__ because we want the module to look# normal; i.e. this is just a wrapper for standard import machineryreturn moddef get_data(self, pathname):with open(pathname, "rb") as file:return file.read()def _reopen(self):if self.file and self.file.closed:mod_type = self.etc[2]if mod_type==imp.PY_SOURCE:self.file = open(self.filename, 'r')elif mod_type in (imp.PY_COMPILED, imp.C_EXTENSION):self.file = open(self.filename, 'rb')def _fix_name(self, fullname):if fullname is None:fullname = self.fullnameelif fullname != self.fullname:raise ImportError("Loader for module %s cannot handle ""module %s" % (self.fullname, fullname))return fullnamedef is_package(self, fullname):fullname = self._fix_name(fullname)return self.etc[2]==imp.PKG_DIRECTORYdef get_code(self, fullname=None):fullname = self._fix_name(fullname)if self.code is None:mod_type = self.etc[2]if mod_type==imp.PY_SOURCE:source = self.get_source(fullname)self.code = compile(source, self.filename, 'exec')elif mod_type==imp.PY_COMPILED:self._reopen()try:self.code = read_code(self.file)finally:self.file.close()elif mod_type==imp.PKG_DIRECTORY:self.code = self._get_delegate().get_code()return self.codedef get_source(self, fullname=None):fullname = self._fix_name(fullname)if self.source is None:mod_type = self.etc[2]if mod_type==imp.PY_SOURCE:self._reopen()try:self.source = self.file.read()finally:self.file.close()elif mod_type==imp.PY_COMPILED:if os.path.exists(self.filename[:-1]):with open(self.filename[:-1], 'r') as f:self.source = f.read()elif mod_type==imp.PKG_DIRECTORY:self.source = self._get_delegate().get_source()return self.sourcedef _get_delegate(self):finder = ImpImporter(self.filename)spec = _get_spec(finder, '__init__')return spec.loaderdef get_filename(self, fullname=None):fullname = self._fix_name(fullname)mod_type = self.etc[2]if mod_type==imp.PKG_DIRECTORY:return self._get_delegate().get_filename()elif mod_type in (imp.PY_SOURCE, imp.PY_COMPILED, imp.C_EXTENSION):return self.filenamereturn Nonetry:import zipimportfrom zipimport import zipimporterdef iter_zipimport_modules(importer, prefix=''):dirlist = sorted(zipimport._zip_directory_cache[importer.archive])_prefix = importer.prefixplen = len(_prefix)yielded = {}import inspectfor fn in dirlist:if not fn.startswith(_prefix):continuefn = fn[plen:].split(os.sep)if len(fn)==2 and fn[1].startswith('__init__.py'):if fn[0] not in yielded:yielded[fn[0]] = 1yield prefix + fn[0], Trueif len(fn)!=1:continuemodname = inspect.getmodulename(fn[0])if modname=='__init__':continueif modname and '.' not in modname and modname not in yielded:yielded[modname] = 1yield prefix + modname, Falseiter_importer_modules.register(zipimporter, iter_zipimport_modules)except ImportError:passdef get_importer(path_item):"""Retrieve a finder for the given path itemThe returned finder is cached in sys.path_importer_cacheif it was newly created by a path hook.The cache (or part of it) can be cleared manually if arescan of sys.path_hooks is necessary."""try:importer = sys.path_importer_cache[path_item]except KeyError:for path_hook in sys.path_hooks:try:importer = path_hook(path_item)sys.path_importer_cache.setdefault(path_item, importer)breakexcept ImportError:passelse:importer = Nonereturn importerdef iter_importers(fullname=""):"""Yield finders for the given module nameIf fullname contains a '.', the finders will be for the packagecontaining fullname, otherwise they will be all registered top levelfinders (i.e. those on both sys.meta_path and sys.path_hooks).If the named module is in a package, that package is imported as a sideeffect of invoking this function.If no module name is specified, all top level finders are produced."""if fullname.startswith('.'):msg = "Relative module name {!r} not supported".format(fullname)raise ImportError(msg)if '.' in fullname:# Get the containing package's __path__pkg_name = fullname.rpartition(".")[0]pkg = importlib.import_module(pkg_name)path = getattr(pkg, '__path__', None)if path is None:returnelse:yield from sys.meta_pathpath = sys.pathfor item in path:yield get_importer(item)def get_loader(module_or_name):"""Get a "loader" object for module_or_nameReturns None if the module cannot be found or imported.If the named module is not already imported, its containing package(if any) is imported, in order to establish the package __path__."""if module_or_name in sys.modules:module_or_name = sys.modules[module_or_name]if module_or_name is None:return Noneif isinstance(module_or_name, ModuleType):module = module_or_nameloader = getattr(module, '__loader__', None)if loader is not None:return loaderif getattr(module, '__spec__', None) is None:return Nonefullname = module.__name__else:fullname = module_or_namereturn find_loader(fullname)def find_loader(fullname):"""Find a "loader" object for fullnameThis is a backwards compatibility wrapper aroundimportlib.util.find_spec that converts most failures to ImportErrorand only returns the loader rather than the full spec"""if fullname.startswith('.'):msg = "Relative module name {!r} not supported".format(fullname)raise ImportError(msg)try:spec = importlib.util.find_spec(fullname)except (ImportError, AttributeError, TypeError, ValueError) as ex:# This hack fixes an impedance mismatch between pkgutil and# importlib, where the latter raises other errors for cases where# pkgutil previously raised ImportErrormsg = "Error while finding loader for {!r} ({}: {})"raise ImportError(msg.format(fullname, type(ex), ex)) from exreturn spec.loader if spec is not None else Nonedef extend_path(path, name):"""Extend a package's path.Intended use is to place the following code in a package's __init__.py:from pkgutil import extend_path__path__ = extend_path(__path__, __name__)This will add to the package's __path__ all subdirectories ofdirectories on sys.path named after the package. This is usefulif one wants to distribute different parts of a single logicalpackage as multiple directories.It also looks for *.pkg files beginning where * matches the nameargument. This feature is similar to *.pth files (see site.py),except that it doesn't special-case lines starting with 'import'.A *.pkg file is trusted at face value: apart from checking forduplicates, all entries found in a *.pkg file are added to thepath, regardless of whether they are exist the filesystem. (Thisis a feature.)If the input path is not a list (as is the case for frozenpackages) it is returned unchanged. The input path is notmodified; an extended copy is returned. Items are only appendedto the copy at the end.It is assumed that sys.path is a sequence. Items of sys.path thatare not (unicode or 8-bit) strings referring to existingdirectories are ignored. Unicode items of sys.path that causeerrors when used as filenames may cause this function to raise anexception (in line with os.path.isdir() behavior)."""if not isinstance(path, list):# This could happen e.g. when this is called from inside a# frozen package. Return the path unchanged in that case.return pathsname_pkg = name + ".pkg"path = path[:] # Start with a copy of the existing pathparent_package, _, final_name = name.rpartition('.')if parent_package:try:search_path = sys.modules[parent_package].__path__except (KeyError, AttributeError):# We can't do anything: find_loader() returns None when# passed a dotted name.return pathelse:search_path = sys.pathfor dir in search_path:if not isinstance(dir, str):continuefinder = get_importer(dir)if finder is not None:portions = []if hasattr(finder, 'find_spec'):spec = finder.find_spec(final_name)if spec is not None:portions = spec.submodule_search_locations or []# Is this finder PEP 420 compliant?elif hasattr(finder, 'find_loader'):_, portions = finder.find_loader(final_name)for portion in portions:# XXX This may still add duplicate entries to path on# case-insensitive filesystemsif portion not in path:path.append(portion)# XXX Is this the right thing for subpackages like zope.app?# It looks for a file named "zope.app.pkg"pkgfile = os.path.join(dir, sname_pkg)if os.path.isfile(pkgfile):try:f = open(pkgfile)except OSError as msg:sys.stderr.write("Can't open %s: %s\n" %(pkgfile, msg))else:with f:for line in f:line = line.rstrip('\n')if not line or line.startswith('#'):continuepath.append(line) # Don't check for existence!return pathdef get_data(package, resource):"""Get a resource from a package.This is a wrapper round the PEP 302 loader get_data API. The packageargument should be the name of a package, in standard module format(foo.bar). The resource argument should be in the form of a relativefilename, using '/' as the path separator. The parent directory name '..'is not allowed, and nor is a rooted name (starting with a '/').The function returns a binary string, which is the contents of thespecified resource.For packages located in the filesystem, which have already been imported,this is the rough equivalent ofd = os.path.dirname(sys.modules[package].__file__)data = open(os.path.join(d, resource), 'rb').read()If the package cannot be located or loaded, or it uses a PEP 302 loaderwhich does not support get_data(), then None is returned."""spec = importlib.util.find_spec(package)if spec is None:return Noneloader = spec.loaderif loader is None or not hasattr(loader, 'get_data'):return None# XXX needs testmod = (sys.modules.get(package) orimportlib._bootstrap._load(spec))if mod is None or not hasattr(mod, '__file__'):return None# Modify the resource name to be compatible with the loader.get_data# signature - an os.path format "filename" starting with the dirname of# the package's __file__parts = resource.split('/')parts.insert(0, os.path.dirname(mod.__file__))resource_name = os.path.join(*parts)return loader.get_data(resource_name)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。