pip 10.0.0中pip.get_installed_distributions()的替代函数及报错解决方案
Hey there! Let's break down your two pip questions clearly, no jargon overload:
问题1:在pip 10.0.0版本中,是否存在pip.get_installed_distributions()的替代函数?
Absolutely! That function didn't disappear entirely—it just moved to a different part of pip's codebase. In pip 10+, you'll find it in the pip._internal.utils.misc module. But a quick heads-up: pip's internal modules (the ones starting with _internal) aren't meant for public use—they can change without warning in future versions.
For a more stable, future-proof approach, you should use either pkg_resources (part of setuptools, which is almost always installed alongside pip) or importlib.metadata (Python's official modern alternative, available in 3.8+).
问题2:解决AttributeError: 'module' object has no attribute 'get_installed_distributions'的办法(无需降级pip)
Got it, this error pops up because pip 10 completely restructured its API, moving the old get_installed_distributions() out of the top-level pip module. Here are three solid solutions, ordered from "quick temporary fix" to "long-term best practice":
Quick fix (use pip's internal API, not recommended for production):
If you just need a workaround to get things running fast, you can import the function from its new internal home:from pip._internal.utils.misc import get_installed_distributions # Example: Print all installed packages with versions for dist in get_installed_distributions(): print(f"{dist.project_name} == {dist.version}")Remember: This relies on pip's internal code, so it might break in future pip updates.
Stable, widely-supported option with
pkg_resources:
This method works across nearly all Python environments since setuptools is usually pre-installed with pip:import pkg_resources # Get a list of installed package names installed_packages = [pkg.key for pkg in pkg_resources.working_set] # Or get names + full version strings installed_packages_with_versions = [f"{pkg.key}=={pkg.version}" for pkg in pkg_resources.working_set]Modern, official solution with
importlib.metadata:
For Python 3.8 and above, this is the recommended approach (it's part of the standard library, no extra installs needed):from importlib.metadata import distributions # List all installed package names installed_packages = [dist.metadata["Name"] for dist in distributions()] # Get names + versions installed_packages_with_versions = [f"{dist.metadata['Name']}=={dist.version}" for dist in distributions()]If you're on Python 3.7 or older, install the backport first with
pip install importlib-metadata, then use:from importlib_metadata import distributions # Same usage as the Python 3.8+ example above
内容的提问来源于stack exchange,提问作者WebDevNewbieGirl

