pkgutilPackage extension utility包扩展实用程序

Source code: Lib/pkgutil.py


This module provides utilities for the import system, in particular package support.本模块为导入系统提供实用程序,特别是软件包支持。

classpkgutil.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 on sys.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 the site module for more information), except that it doesn’t special-case lines starting with import. 这个特性类似于*.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 on sys.path that cause errors when used as filenames may cause this function to raise an exception (in line with os.path.isdir() behavior).sys.path上的Unicode项在用作文件名时会导致错误,这可能会导致此函数引发异常(符合os.path.isdir()行为)。

classpkgutil.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 None, a PEP 302 finder is created that searches the current sys.path, plus any modules that are frozen or built-in.如果dirnameNone,则会创建一个PEP 302查找器,用于搜索当前系统路径以及冻结或内置的任何模块。

Note that ImpImporter does not currently support being used by placement on sys.meta_path.请注意,ImpImporter当前不支持放置在sys.meta_path上使用。

Deprecated since version 3.3: 自3.3版起已弃用:This emulation is no longer needed, as the standard import mechanism is now fully PEP 302 compliant and available in importlib.不再需要这种仿真,因为标准导入机制现在完全符合PEP 302,并且可以在importlib中使用。

classpkgutil.ImpLoader(fullname, file, filename, etc)

Loader that wraps Python’s “classic” import algorithm.它包装了Python的“经典”导入算法。

Deprecated since version 3.3: 自3.3版起已弃用:This emulation is no longer needed, as the standard import mechanism is now fully PEP 302 compliant and available in importlib.不再需要这种仿真,因为标准导入机制现在完全符合PEP 302,并且可以在importlib中使用。

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 to ImportError and only returns the loader rather than the full ModuleSpec.这是一个关于importlib.util.find_spec()的向后兼容包装器,它将大多数失败转换为ImportError,并且只返回加载器而不是完整的ModuleSpec

Changed in version 3.3:版本3.3中更改: Updated to be based directly on importlib rather than relying on the package internal PEP 302 import emulation.更新为直接基于importlib,而不是依赖包内部PEP 302导入仿真。

Changed in version 3.4:版本3.4中更改: Updated to be based on PEP 451根据PEP 451更新

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,可以手动清除缓存(或部分缓存)。

Changed in version 3.3:版本3.3中更改: Updated to be based directly on importlib rather than relying on the package internal PEP 302 import emulation.更新为直接基于importlib,而不是依赖包内部PEP 302导入仿真。

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. 如果无法找到或导入模块,则返回NoneIf the named module is not already imported, its containing package (if any) is imported, in order to establish the package __path__.如果命名模块尚未导入,则导入其包含的包(如果有),以建立包__path__

Changed in version 3.3:版本3.3中更改: Updated to be based directly on importlib rather than relying on the package internal PEP 302 import emulation.更新为直接基于importlib,而不是依赖包内部PEP 302导入仿真。

Changed in version 3.4:版本3.4中更改: Updated to be based on PEP 451根据PEP 451更新

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 both sys.meta_path and sys.path_hooks).如果全名包含'.',查找器将用于包含全名的包,否则它们将是所有注册的顶级查找器(即sys.meta_pathsys.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.如果未指定模块名称,则生成所有顶级查找器。

Changed in version 3.3:版本3.3中更改: Updated to be based directly on importlib rather than relying on the package internal PEP 302 import emulation.更新为直接基于importlib,而不是依赖包内部PEP 302导入仿真。

pkgutil.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上的所有子模块生成ModuleInfo,如果pathNone,则为sys.path上的所有顶级模块。

path should be either None or a list of paths to look for modules in.path应该是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 and zipimport.zipimporter.该接口是非标准的,因此该模块还提供了importlib.machinery.FileFinderzipimport.zipimporter的实现。

Changed in version 3.3:版本3.3中更改: Updated to be based directly on importlib rather than relying on the package internal PEP 302 import emulation.更新为直接基于importlib,而不是依赖包内部PEP 302导入仿真。

pkgutil.walk_packages(path=None, prefix='', onerror=None)

Yields ModuleInfo for all modules recursively on path, or, if path is None, all accessible modules.递归地为path上的所有模块生成ModuleInfo,如果pathNone,则为所有可访问模块。

path should be either None or a list of paths to look for modules in.path应该是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__ attribute to find submodules.请注意,此函数必须导入给定path上的所有packages(而不是所有模块!),以便访问__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, ImportErrors are caught and ignored, while all other exceptions are propagated, terminating the search.如果未提供onerror函数,则捕获并忽略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 and zipimport.zipimporter.该接口是非标准的,因此该模块还提供了importlib.machinery.FileFinderzipimport.zipimporter的实现。

Changed in version 3.3:版本3.3中更改: Updated to be based directly on importlib rather than relying on the package internal PEP 302 import emulation.更新为直接基于importlib,而不是依赖包内部PEP 302导入仿真。

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, using / as the path separator. resource参数应采用相对文件名的形式,使用/作为路径分隔符。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, then None is returned. 如果无法找到或加载包,或者它使用的加载程序不支持get_data,则返回NoneIn 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:该函数将返回一个对象(可能是一个模块),或引发以下异常之一:

ValueErrorif name isn’t in a recognised format.如果name格式不正确。

ImportErrorif an import failed when it shouldn’t have.如果导入失败,而不应该失败。

AttributeErrorIf 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中新增。