Ubuntu24.04LTS中使用pip install时显示如下信息:
error: externally-managed-environment × This environment is externally managed ╰─> To install Python packages system-wide, try apt
installpython3-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.
原因是:Ubuntu系统或某些系统级服务管理的Python环境中使用pip来安装包,为确保系统稳定安全,将这个install认为是“外部管理”的,意味着它可能已经被Ubuntu的某些部分或其他系统级服务所依赖。直接在这个环境中使用pip安装或更新包可能会破坏这些系统级服务或应用的运行。
解决方法:知道了原因,就很好解决问题了。只要创建一个与之隔离的环境即可。
我这里选择创建一个全局的虚拟环境,然后新建一个otherpy别名来激活它。
第一步:安装venv包
sudo apt install python3-venv
第二步:创建虚拟环境
cd ~
mkdir .python_venv
cd .python_venv
python3 -m venv global
第三步:创建虚拟环境
打开~/.bashrc文件编辑
nano ~/.bashrc
在末尾添加:
alias otherpy='. ~/.python_venv/global/bin/activate'
然后重新source即可:
source ~/.bashrc
第四步:使用
source完成后在终端运行otherpy进行虚拟环境,即可实现pip install 安装。