降级Pip至18.0版本后无法运行,出现ImportError报错求助
解决pip 18.0与Python 3.10兼容导致的ImportError问题
问题描述
执行sudo python -m pip install pip==18.0 --upgrade将pip降级至18.0版本后,运行pip/pip3或尝试pip3 install --upgrade pip升级时,触发以下错误:
Traceback (most recent call last): File "/usr/local/bin/pip3", line 5, in <module> from pip._internal import main File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pip/_internal/__init__.py", line 42, in <module> from pip._internal import cmdoptions File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pip/_internal/cmdoptions.py", line 16, in <module> from pip._internal.index import ( File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pip/_internal/index.py", line 14, in <module> from pip._vendor import html5lib, requests, six File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pip/_vendor/html5lib/__init__.py", line 25, in <module> from .html5parser import HTMLParser, parse, parseFragment File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pip/_vendor/html5lib/html5parser.py", line 8, in <module> from . import _tokenizer File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pip/_vendor/html5lib/_tokenizer.py", line 16, in <module> from ._trie import Trie File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pip/_vendor/html5lib/_trie/__init__.py", line 3, in <module> from .py import Trie as PyTrie File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pip/_vendor/html5lib/_trie/py.py", line 6, in <module> from ._base import Trie as ABCTrie File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pip/_vendor/html5lib/_trie/_base.py", line 3, in <module> from collections import Mapping ImportError: cannot import name 'Mapping' from 'collections' (/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/collections/__init__.py)
问题根源
Python 3.10中,collections.Mapping已被迁移至collections.abc模块,而pip 18.0是2018年发布的老旧版本,其内置的html5lib依赖仍在使用已被移除的collections.Mapping,导致兼容性错误。
解决方法
方法1:使用Python内置的ensurepip修复
执行以下命令,通过Python自带的ensurepip模块重新安装适配当前Python版本的pip:
sudo python3 -m ensurepip --upgrade
方法2:手动安装pip
如果ensurepip无法解决问题,可通过官方脚本重新安装:
- 获取
get-pip.py脚本(从Python官方pip项目获取) - 执行安装命令:
sudo python3 get-pip.py
验证修复
执行以下命令确认pip版本已更新至兼容Python 3.10的版本(建议21.0及以上):
pip3 --version
内容的提问来源于stack exchange,提问作者koifish5242
相关产品推荐
相关产品推荐

