在 ubuntu 系统中使用 apt 安装 python 第三方包版本可能滞后的原因以及如何解决此问题,已经成为许多用户关注的焦点。让我们深入探讨这个问题,并提供一些解决方案。
为什么 Ubuntu 系统中使用 apt 安装的 python 第三方包版本会滞后?
在 Ubuntu 系统中,当我们使用 apt 命令来安装 Python 第三方包时,常常会发现这些包的版本较旧,导致一些兼容性问题。最近,在尝试使用 certbot 安装 Let’s Encrypt 证书时,遇到了一些奇怪的错误,让人不禁疑惑:为什么使用 apt 安装的 Python 第三方包版本会如此滞后?
我的系统环境是 Ubuntu 22.04,并且已经执行了 apt update。在尝试安装 certbot 时,我使用了以下命令:
sudo apt install certbot python3-certbot-nginx
然而,在使用 certbot 时却出现了错误:
pon@aliyun2core2GB:~$ sudo certbot certonly --manual --preferred-challenges dns -d xxxxx.cn -d *.xxxxx.cn Traceback (most recent call last): File "/usr/lib/python3/dist-packages/requests_toolbelt/_compat.py", line 48, in <module> from requests.packages.urllib3.contrib import appengine as gaecontrib ImportError: cannot import name 'appengine' from 'requests.packages.urllib3.contrib' (/usr/local/lib/python3.10/dist-packages/urllib3/contrib/__init__.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/bin/certbot", line 33, in <module> sys.exit(load_entry_point('certbot==1.21.0', 'console_scripts', 'certbot')()) ...... from .._compat import poolmanager File "/usr/lib/python3/dist-packages/requests_toolbelt/_compat.py", line 50, in <module> from urllib3.contrib import appengine as gaecontrib ImportError: cannot import name 'appengine' from 'urllib3.contrib' (/usr/local/lib/python3.10/dist-packages/urllib3/contrib/__init__.py)
检查 certbot 的版本,发现它非常老:
立即学习“Python免费学习笔记(深入)”;
pon@aliyun2core2GB:~$ pip show certbot Name: certbot Version: 1.21.0 Summary: ACME client Home-page: https://github.com/letsencrypt/letsencrypt Author: Certbot Project Author-email: certbot-dev@eff.org License: apache License 2.0 Location: /usr/lib/python3/dist-packages Requires: Required-by:
这引发了一个问题:为什么 Ubuntu 系统中的 apt 包管理器会提供如此旧的 Python 第三方包版本?
经过一番测试和分析,发现 certbot 1.21.0 版本实际上是可以正常工作的,并不是版本不兼容的问题。问题的根源在于之前使用 pip 安装了 urllib3 这个依赖包。
观察报错信息,可以看到 urllib3 的文件路径在 /usr/local/lib/python3.10/dist-packages,而 certbot 则位于 /usr/lib/python3/dist-packages。这说明:
- 使用 apt install python-xxx 安装的包会被放置在 /usr/lib/python3/dist-packages 目录下。
- 使用 sudo pip install xxx 安装的包会被放置在 /usr/local/lib/python3.10/dist-packages 目录下。
Python 在加载包时会按照目录优先级进行搜索,优先级顺序如下:
- /usr/local/lib/python3.10/dist-packages
- /usr/lib/python3/dist-packages
因此,当系统中同时存在通过 apt 和 pip 安装的包时,pip 安装的包会优先被加载,导致版本冲突。
实际上,apt 已经解决了依赖问题,但 apt 安装的包优先级较低。为了避免这种情况,正确的做法是:
- 在系统中只使用 apt 进行包管理,不要混用 pip。
- 或者使用虚拟环境来隔离不同的包管理需求。
- 或者完全使用 pip 进行包管理。