电脑本来只有一个 Python3.10, 可能是由于系统升级的原因,发现电脑多了一个 Python3.11 版本,这带来了好多麻烦,比如我很多软件包都安装在 python3.10 中,但是命令行输入 pip 调用的是 python3.11 的,并且之前创建的虚拟环境感觉也不太正常了。
我决定删除旧版本 Python
python3.10 -m pip freeze > backup.txt # 备份已安装的包
sudo apt purge python3.10
sudo apt autoremove
接下来是恢复之前安装的软件包,不过这里遇到了错误
$ pip install -r backup.txt
error: externally-managed-environment
× This environment is externally managed
╰─> To install Python packages system-wide, try apt install
python3-xyz, where xyz is the package you are trying to
install.
If you wish to install a non-Debian-packaged Python package,
create a virtual environment using python3 -m venv path/to/venv.
Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make
sure you have python3-full installed.
If you wish to install a non-Debian packaged Python application,
it may be easiest to use pipx install xyz, which will manage a
virtual environment for you. Make sure you have pipx installed.
See /usr/share/doc/python3.11/README.venv for more information.
note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages.
hint: See PEP 668 for the detailed specification.
查阅了一番资料后,发现,原因可能在于,现在电脑上的 Python3.11 是 Linux 系统包管理器提供的,使用 pip 安装软件包可能会干扰到原本系统软件包的正常工作,因此在这种情况下,比较推荐的做法是:
- 系统层面的 python 软件包,使用包管理器安装,例如
apt install python3-xxx
- 项目/本地层面创建虚拟环境,在虚拟环境内使用
pip
安装
最终,我选择在系统层面 apt install python3-virtualenv
方便创建虚拟环境,其余的依赖项则在项目文件夹中 pip 安装。
系统层面可以安装一些基础性的软件包,不过可惜的是并没有 pipreqs 可以安装,只能 pip 安装……
为了方便,我在 zsh 设定中添加了下面的函数方便调用:
create-virtualenv() {
virtualenv .venv
source ./venv/bin/activate
pip install pipreqs
}
参考资料:
- python - How do I solve "error: externally-managed-environment" everytime I use pip3? - Stack Overflow
- python - pip install -r requirements.txt is failing: This environment is externally managed - Stack Overflow
- PEP 668 support breaks --user/--editable · Issue #11776 · pypa/pip
- PEP 668 – Marking Python base environments as “externally managed” | peps.python.org --- PEP 668-将 Python 基础环境标记为“外部管理”| peps.Python.org
其他说明
如果保留两个版本,只需要日常使用时稍微注意下就好了,例如,需要使用 Python3.10 时:
python3.10
python3.10 -m pip
标签:venv,版本,Python,environment,install,Ubuntu,pip,安装
From: https://www.cnblogs.com/zkmjolnir/p/17603917.html