importlib.metadata – Accessing package metadata — Python 3.15.2 documentation
Навігація індекс модулі | наступний | попередній | Python » 3.15.2 documentation » The Python standard library » Імпорт модулів » importlib.metadata – Accessing package metadata | Theme | importlib.metadata – Accessing package metadata ¶ Added in version 3.8. Змінено в версії 3.10: importlib.metadata більше не є тимчасовим. Вихідний код: 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 provides the entry point and metadata APIs that were previously exposed by the now-removed pkg_resources package. Along with importlib.resources , it supersedes 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 Ви можете отримати рядок версії для wheel , виконавши наступне: (example) $ python >>> from importlib.metadata import version >>> version ( 'wheel' ) '0.32.3' You can also get a collection of entry points selectable by properties of the EntryPoint (typically „group“ or „name“), such as console_scripts , distutils.commands and others.
Each group contains a collection of EntryPoint objects. Ви можете отримати метадані для дистрибутива : >>> from importlib.metadata import metadata >>> list ( metadata ( 'wheel' )) ['Metadata-Version', 'Name', 'Version', 'Summary', 'Home-page', 'Author', 'Author-email', 'Maintainer', 'Maintainer-email', 'License', 'Project-URL', 'Project-URL', 'Project-URL', 'Keywords', 'Platform', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Classifier', 'Requires-Python', 'Provides-Extra', 'Requires-Dist', 'Requires-Dist'] Ви також можете отримати номер версії дистрибутива , перелічити його складові файли та отримати список Вимоги до розповсюдження дистрибутива. exception importlib.metadata.
PackageNotFoundError ¶ Subclass of ModuleNotFoundError raised by several functions in this module when queried for a distribution package which is not installed in the current Python environment. exception importlib.metadata. MetadataNotFound ¶ Subclass of FileNotFoundError raised when attempting to load metadata from a distribution folder that is empty or otherwise does not contain a metadata file. Функціональний API ¶ Цей пакет забезпечує такі функції через свій загальнодоступний API.
Точки входу ¶ importlib.metadata. entry_points ( ** select_params ) ¶ Returns a EntryPoints instance describing entry points for the current environment. Any given keyword parameters are passed to the select() method for comparison to the attributes of the individual entry point definitions. Note: to query for entry points based on EntryPoint.dist attribute, use Distribution.entry_points() instead (as different Distribution instances do not currently compare equal, even if they have the same attributes) class importlib.metadata.
EntryPoints ¶ Details of a collection of installed entry points. Also provides a .groups attribute that reports all identified entry point groups, and a .names attribute that reports all identified entry point names. class importlib.metadata. EntryPoint ¶ Details of an installed entry point. Each EntryPoint instance has .name , .group , and .value attributes and a .load() method to resolve the value. There are also .module , .attr , and .extras attributes for getting the components of the .value attribute, and .dist for obtaining information regarding the distribution package that provides the entry point.
Запитувати всі точки входу: >>> eps = entry_points () The entry_points() function returns a EntryPoints object, a collection of all EntryPoint objects with names and groups attributes for convenience: >>> sorted ( eps . groups ) ['console_scripts', 'distutils.commands', 'distutils.setup_keywords', 'egg_info.writers', 'setuptools.installation'] EntryPoints has a select() method to select entry points matching specific properties.
Select entry points in the console_scripts group: >>> scripts = eps . select ( group = 'console_scripts' ) Equivalently, since entry_points() passes keyword arguments through to select: >>> scripts = entry_points ( group = 'console_scripts' ) Виберіть певний сценарій під назвою «колесо» (знаходиться в проекті колеса): >>> 'wheel' in scripts . names True >>> wheel = scripts [ 'wheel' ] Аналогічно, запитайте цю точку входу під час вибору: >>> ( wheel ,) = entry_points ( group = 'console_scripts' , name = 'wheel' ) >>> ( wheel ,) = entry_points () . select ( group = 'console_scripts' , name = 'wheel' ) Огляньте вирішену точку входу: >>> wheel EntryPoint(name='wheel', value='wheel.cli:main', group='console_scripts') >>> wheel . module 'wheel.cli' >>> wheel . attr 'main' >>> wheel . extras [] >>> main = wheel . load () >>> main <function main at 0x103528488> The group and name are arbitrary values defined by the package author and usually a client will wish to resolve all entry points for a particular group.
Read the setuptools docs for more information on entry points, their definition, and usage. Змінено в версії 3.12: The «selectable» entry points were introduced in importlib_metadata 3.6 and Python 3.10. Prior to those changes, entry_points accepted no parameters and always returned a dictionary of entry points, keyed by group. With importlib_metadata 5.0 and Python 3.12, entry_points always returns an EntryPoints object.
See backports.entry_points_selectable for compatibility options. Змінено в версії 3.13: EntryPoint objects no longer present a tuple-like interface ( __getitem__() ). Метадані розповсюдження ¶ importlib.metadata. metadata ( distribution_name ) ¶ Return the distribution metadata corresponding to the named distribution package as a PackageMetadata instance. Raises PackageNotFoundError if the named distribution package is not installed in the current Python environm
The rest of this page is on the live site.