pkgutil
— Package extension utility包扩展实用程序¶
Source code: Lib/pkgutil.py
This module provides utilities for the import system, in particular package support.本模块为导入系统提供实用程序,特别是软件包支持。
-
class
pkgutil.
ModuleInfo
(module_finder, name, ispkg)¶ A namedtuple that holds a brief summary of a module’s info.包含模块信息的简短摘要的命名元组。New in version 3.6.版本3.6中新增。
-
pkgutil.
extend_path
(path, name)¶ Extend the search path for the modules which comprise a package.扩展包含包的模块的搜索路径。Intended use is to place the following code in a package’s预期用途是将以下代码放在包的__init__.py
:__init__.py
中:from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)This will add to the package’s这将向包的__path__
all subdirectories of directories onsys.path
named after the package.__path__
添加sys.path
上以包命名的目录的所有子目录。This is useful if one wants to distribute different parts of a single logical package as multiple directories.如果希望将单个逻辑包的不同部分作为多个目录分发,这很有用。It also looks for它还查找以*.pkg
files beginning where*
matches the name argument.*
匹配name
参数开头的*.pkg
文件。This feature is similar to这个特性类似于*.pth
files (see thesite
module for more information), except that it doesn’t special-case lines starting withimport
.*.pth
文件(有关更多信息,请参阅site
模块),只是它没有以import
开头的特殊情况行。A一个*.pkg
file is trusted at face value: apart from checking for duplicates, all entries found in a*.pkg
file are added to the path, regardless of whether they exist on the filesystem.*.pkg
文件的面值是可信的:除了检查重复项之外,无论文件系统中是否存在,在*.pkg
文件中找到的所有条目都会添加到路径中。(This is a feature.)(这是一项功能。)If the input path is not a list (as is the case for frozen packages) it is returned unchanged.如果输入路径不是一个列表(对于冻结的包也是如此),则返回的路径不变。The input path is not modified; an extended copy is returned.未修改输入路径;返回扩展副本。Items are only appended to the copy at the end.项目仅在末尾附加到副本。It is assumed that假设sys.path
is a sequence.sys.path
是一个序列。Items of忽略sys.path
that are not strings referring to existing directories are ignored.sys.path
中不是引用现有目录的字符串的项。Unicode items onsys.path
that cause errors when used as filenames may cause this function to raise an exception (in line withos.path.isdir()
behavior).sys.path
上的Unicode项在用作文件名时会导致错误,这可能会导致此函数引发异常(符合os.path.isdir()
行为)。
-
class
pkgutil.
ImpImporter
(dirname=None)¶ PEP 302
Finder that wraps Python’s “classic” import algorithm.包装Python“经典”导入算法的查找器。If dirname is a string, a PEP 302 finder is created that searches that directory.如果dirname是字符串,则会创建一个PEP 302查找器来搜索该目录。If dirname is如果dirname为None
, a PEP 302 finder is created that searches the currentsys.path
, plus any modules that are frozen or built-in.None
,则会创建一个PEP 302查找器,用于搜索当前系统路径以及冻结或内置的任何模块。Note that请注意,ImpImporter
does not currently support being used by placement onsys.meta_path
.ImpImporter
当前不支持放置在sys.meta_path
上使用。
-
class
pkgutil.
ImpLoader
(fullname, file, filename, etc)¶ Loader
that wraps Python’s “classic” import algorithm.它包装了Python的“经典”导入算法。
-
pkgutil.
find_loader
(fullname)¶ Retrieve a module loader for the given fullname.检索给定fullname的模块加载器。This is a backwards compatibility wrapper around这是一个关于importlib.util.find_spec()
that converts most failures toImportError
and only returns the loader rather than the fullModuleSpec
.importlib.util.find_spec()
的向后兼容包装器,它将大多数失败转换为ImportError
,并且只返回加载器而不是完整的ModuleSpec
。
-
pkgutil.
get_importer
(path_item)¶ Retrieve a finder for the given path_item.检索给定path_item的查找器。The returned finder is cached in如果返回的查找器是由路径挂钩新创建的,则将其缓存在sys.path_importer_cache
if it was newly created by a path hook.sys.path_importer_cache
中。The cache (or part of it) can be cleared manually if a rescan of如果需要重新扫描sys.path_hooks
is necessary.sys.path_hooks
,可以手动清除缓存(或部分缓存)。
-
pkgutil.
get_loader
(module_or_name)¶ Get a loader object for module_or_name.获取module_or_name的加载器对象。If the module or package is accessible via the normal import mechanism, a wrapper around the relevant part of that machinery is returned.如果模块或包装可通过正常的导入机制访问,则返回该机器相关部分的包装。Returns如果无法找到或导入模块,则返回None
if the module cannot be found or imported.None
。If the named module is not already imported, its containing package (if any) is imported, in order to establish the package如果命名模块尚未导入,则导入其包含的包(如果有),以建立包__path__
.__path__
。
-
pkgutil.
iter_importers
(fullname='')¶ Yield finder objects for the given module name.为给定的模块名称生成查找器对象。If fullname contains a如果全名包含'.'
, the finders will be for the package containing fullname, otherwise they will be all registered top level finders (i.e. those on bothsys.meta_path
andsys.path_hooks
).'.'
,查找器将用于包含全名的包,否则它们将是所有注册的顶级查找器(即sys.meta_path
和sys.path_hooks
上的查找器)。If the named module is in a package, that package is imported as a side effect of invoking this function.如果命名模块位于包中,则作为调用此函数的副作用导入该包。If no module name is specified, all top level finders are produced.如果未指定模块名称,则生成所有顶级查找器。
-
pkgutil.
iter_modules
(path=None, prefix='')¶ Yields为path上的所有子模块生成ModuleInfo
for all submodules on path, or, if path isNone
, all top-level modules onsys.path
.ModuleInfo
,如果path为None
,则为sys.path
上的所有顶级模块。path should be eitherpath应该是None
or a list of paths to look for modules in.None
或要在其中查找模块的路径列表。prefix
is a string to output on the front of every module name on output.是要在输出的每个模块名称前面输出的字符串。Note
Only works for a finder which defines an仅适用于定义iter_modules()
method.iter_modules()
方法的查找器。This interface is non-standard, so the module also provides implementations for该接口是非标准的,因此该模块还提供了importlib.machinery.FileFinder
andzipimport.zipimporter
.importlib.machinery.FileFinder
和zipimport.zipimporter
的实现。
-
pkgutil.
walk_packages
(path=None, prefix='', onerror=None)¶ Yields递归地为path上的所有模块生成ModuleInfo
for all modules recursively on path, or, if path isNone
, all accessible modules.ModuleInfo
,如果path为None
,则为所有可访问模块。path should be eitherpath应该是None
or a list of paths to look for modules in.None
或要在其中查找模块的路径列表。prefix
is a string to output on the front of every module name on output.是要在输出的每个模块名称前面输出的字符串。Note that this function must import all packages (not all modules!) on the given path, in order to access the请注意,此函数必须导入给定path上的所有packages(而不是所有模块!),以便访问__path__
attribute to find submodules.__path__
属性以查找子模块。onerror
is a function which gets called with one argument (the name of the package which was being imported) if any exception occurs while trying to import a package.是一个函数,如果在尝试导入包时发生任何异常,将使用一个参数(正在导入的包的名称)调用该函数。If no onerror function is supplied,如果未提供onerror函数,则捕获并忽略ImportError
s are caught and ignored, while all other exceptions are propagated, terminating the search.ImportError
,同时传播所有其他异常,从而终止搜索。Examples:
# list all modules python can access
walk_packages()
# list all submodules of ctypes
walk_packages(ctypes.__path__, ctypes.__name__ + '.')Note
Only works for a finder which defines an仅适用于定义iter_modules()
method.iter_modules()
方法的查找器。This interface is non-standard, so the module also provides implementations for该接口是非标准的,因此该模块还提供了importlib.machinery.FileFinder
andzipimport.zipimporter
.importlib.machinery.FileFinder
和zipimport.zipimporter
的实现。
-
pkgutil.
get_data
(package, resource)¶ Get a resource from a package.从包中获取资源。This is a wrapper for the loader这是加载器get_data
API.get_data
API的包装器。The package argument should be the name of a package, in standard module format (foo.bar
).package
参数应该是标准模块格式(foo.bar
)的包名。The resource argument should be in the form of a relative filename, usingresource参数应采用相对文件名的形式,使用/
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 that is the contents of the specified resource.该函数返回一个二进制字符串,该字符串是指定资源的内容。For packages located in the filesystem, which have already been imported, this is the rough equivalent of:对于文件系统中已导入的包,这大致相当于:d = 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 loader which does not support如果无法找到或加载包,或者它使用的加载程序不支持get_data
, thenNone
is returned.get_data
,则返回None
。In particular, the loader for namespace packages does not support特别是,命名空间包的加载器不支持get_data
.get_data
。
-
pkgutil.
resolve_name
(name)¶ Resolve a name to an object.解析对象的名称。This functionality is used in numerous places in the standard library (see bpo-12915) - and equivalent functionality is also in widely used third-party packages such as setuptools, Django and Pyramid.该功能在标准库中的许多地方都有使用(参见bpo-12915),而类似的功能也在广泛使用的第三方软件包中,如setuptools、Django和Pyramid。It is expected that name will be a string in one of the following formats, where W is shorthand for a valid Python identifier and dot stands for a literal period in these pseudo-regexes:name应该是以下格式之一的字符串,其中W是有效Python标识符的缩写,dot代表这些伪正则表达式中的文字句点:W(.W)*
W(.W)*:(W(.W)*)?
The first form is intended for backward compatibility only.第一种形式仅用于向后兼容。It assumes that some part of the dotted name is a package, and the rest is an object somewhere within that package, possibly nested inside other objects.它假设虚线名称的一部分是一个包,其余部分是该包中的某个对象,可能嵌套在其他对象中。Because the place where the package stops and the object hierarchy starts can’t be inferred by inspection, repeated attempts to import must be done with this form.由于检查无法推断包停止和对象层次结构开始的位置,因此必须使用此表单重复尝试导入。In the second form, the caller makes the division point clear through the provision of a single colon: the dotted name to the left of the colon is a package to be imported, and the dotted name to the right is the object hierarchy within that package.在第二种形式中,调用者通过提供一个冒号来明确划分点:冒号左边的虚线名称是要导入的包,右边的虚线名称则是该包中的对象层次结构。Only one import is needed in this form.此表单中只需要一个导入。If it ends with the colon, then a module object is returned.如果以冒号结尾,则返回模块对象。The function will return an object (which might be a module), or raise one of the following exceptions:该函数将返回一个对象(可能是一个模块),或引发以下异常之一:ValueError
–if name isn’t in a recognised format.如果name格式不正确。ImportError
–if an import failed when it shouldn’t have.如果导入失败,而不应该失败。AttributeError
–If a failure occurred when traversing the object hierarchy within the imported package to get to the desired object.如果在遍历导入包中的对象层次结构以获取所需对象时发生故障。New in version 3.9.版本3.9中新增。