Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 792
WebDevNewbieGirl Avatar asked Apr 19 '18 14:04

WebDevNewbieGirl


3 Answers

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
like image 120
hoefling Avatar answered Nov 06 '22 01:11

hoefling


@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 setuptools 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.
like image 30
Mmelcor Avatar answered Nov 06 '22 03:11

Mmelcor


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',...]
like image 1
sedeh Avatar answered Nov 06 '22 01:11

sedeh