Are there any function replacement for pip.get_installed_distributions() in pip 10.0.0 version?

自作多情 提交于 2020-01-13 08:58:13

问题


When I try to import pip package and use pip.get_installed_distributions(), console is printing error:

 AttributeError: 'module' object has no attribute 'get_installed_distributions'

Are there any solutions which exclude downgrading pip?


回答1:


Update

With Python 3.8, the standard library has got a way of querying the environment for installed distributions and their metadata: importlib.metadata. For older Python versions, there's a backport importlib_metadata:

$ pip install importlib-metadata

It is thus advisable to use it (or the backport) instead of relying on pip's internals.

Importing with backwards compatibility:

import sys

if sys.version_info >= (3, 8):
    from importlib import metadata as importlib_metadata
else:
    import importlib_metadata

Usage examples:

Get names, versions and licenses (check out more available metadata keys in core metadata spec) of all installed distributions:

dists = importlib_metadata.distributions()
for dist in dists:
    name = dist.metadata["Name"]
    version = dist.version
    license = dist.metadata["License"]
    print(f'found distribution {name}=={version}')

Querying single distribution by name:

wheel = importlib_metadata.distribution('wheel') 
print(wheel.metadata["Name"], 'installed')

Original answer:

The function was moved to the pip._internal subpackage. Import example with backwards compatibility:

try:
    from pip._internal.utils.misc import get_installed_distributions
except ImportError:  # pip<10
    from pip import get_installed_distributions



回答2:


@hoefling It is not recommended and is bad practice to import items from pip._internal pip has warned against this and preceding the release of pip 10 they made an announcement regarding this too.

A good alternative would be to use systemtools pkg_resources instead. From there you can use pkg_resources.working_set. See the comment from @pradyunsg here.

import pkg_resources

dists = [d for d in pkg_resources.working_set]
# You can filter and use information from the installed distributions.



回答3:


Adding to @Mmelcor answer, the items returned in the list comprehension is a PathMetadata object, something like:

[wrapt 1.10.11 (/Users/<username>/path/venv/lib/python3.6/site-packages),
 widgetsnbextension 3.2.1 (/Users/<username>/path/venv/lib/python3.6/site-packages),....]

You may need to get the string representation before filtering:

import pkg_resources
dists = [str(d) for d in pkg_resources.working_set]
print(dists)

Result:

['wrapt 1.10.11',
 'widgetsnbextension 3.2.1',...]


来源:https://stackoverflow.com/questions/49923671/are-there-any-function-replacement-for-pip-get-installed-distributions-in-pip

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!