importlib.metadata – Accessing package metadata

Added in version 3.8.

3.10 版改变: importlib.metadata is no longer provisional.

源代码: Lib/importlib/metadata/__init__.py

importlib.metadata is a library that provides access to the metadata of an installed Distribution Package , such as its entry points or its top-level names ( Import Package s, modules, if any). Built in part on Python’s import system, this library intends to replace similar functionality in the entry point API and metadata API of pkg_resources . Along with importlib.resources , this package can eliminate the need to use the older and less efficient pkg_resources 包。

importlib.metadata operates on third-party distribution packages installed into Python’s site-packages directory via tools such as pip . Specifically, it works with distributions with discoverable dist-info or egg-info directories, and metadata defined by the Core metadata specifications .

重要

These are not necessarily equivalent to or correspond 1:1 with the top-level import package names that can be imported inside Python code. One distribution package can contain multiple import packages (and single modules), and one top-level import package may map to multiple distribution packages if it is a namespace package. You can use packages_distributions() to get a mapping between them.

By default, distribution metadata can live on the file system or in zip archives on sys.path . Through an extension mechanism, the metadata can live almost anywhere.

另请参阅

https://importlib-metadata.readthedocs.io/

The documentation for importlib_metadata , which supplies a backport of importlib.metadata . This includes an API reference for this module’s classes and functions, as well as a migration guide for existing users of pkg_resources .

概述

Let’s say you wanted to get the version string for a Distribution Package you’ve installed using pip . We start by creating a virtual environment and installing something into it:

$ python -m venv example
$ source example/bin/activate
(example) $ python -m pip install wheel
										

You can get the version string for wheel by running the following:

(example) $ python
>>> from importlib.metadata import version
>>> version('wheel')
'0.32.3'