对错误进行完整的回溯会很有用。可能导致此问题的一种情况是安装了多个版本的 Python。
例如,在我的 Ubuntu 20.04.1 LTS 上,除了随 Ubuntu 20 分发的 Python 3.8 之外,我还从源代码安装了 Python 3.6。这是我pip3 --version
在安装 Python 3.6 后得到的:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 581, in _build_master
ws.require(__requires__)
File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 898, in require
needed = self.resolve(parse_requirements(requirements))
File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 789, in resolve
raise VersionConflict(dist, req).with_context(dependent_req)
pkg_resources.VersionConflict: (pip 20.2.3 (/usr/local/lib/python3.6/site-packages), Requirement.parse('pip==20.0.2'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/bin/pip3", line 6, in <module>
from pkg_resources import load_entry_point
File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3126, in <module>
@_call_aside
File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3110, in _call_aside
f(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3139, in _initialize_master_working_set
working_set = WorkingSet._build_master()
File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 583, in _build_master
return cls._build_from_requirements(__requires__)
File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 596, in _build_from_requirements
dists = ws.resolve(reqs, Environment())
File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 784, in resolve
raise DistributionNotFound(req, requirers)
pkg_resources.DistributionNotFound: The 'pip==20.0.2' distribution was not found and is required by the application
最后一行是有问题的错误,但请注意回溯中的一个重要细节:raise VersionConflict
.
这可以通过显式使用所需版本来解决pip
:
$ python3.6 -m pip --version
pip 20.2.3 from /usr/local/lib/python3.6/site-packages/pip (python 3.6)
或者简单地说:
$ pip3.6 --version
pip 20.2.3 from /usr/local/lib/python3.6/site-packages/pip (python 3.6)
另一个可能会偶然发现的问题是在执行以下操作时缺少 lsb_release问题pip3.6 install
:
File "/usr/local/lib/python3.6/subprocess.py", line 438, in run
output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '('lsb_release', '-a')' returned non-zero exit status 1.
这可以通过定位lsb_release.py
和创建符号链接来解决,例如:
sudo ln -s /usr/lib/python3/dist-packages/lsb_release.py /usr/local/lib/python3.6/site-packages/lsb_release.py
现在可以升级 pip3.6 并安装新软件包:
$ pip3.6 install --upgrade pip
$ pip3.6 install mypy
管理 Python 版本有不同的方法。小心使用类似sudo update-alternatives --config python
. 更改系统的默认 Python,可能会导致问题,包括终端无法打开等症状。最好有一个可用的备份终端,例如 Visual Studio Code 中的那个。