Linux 使用pip报错(error: externally-managed-environment )解决方案
**报错输出如下:**error: externally-managed-environment
点击查看代码zhuji@hcss-ecs-2045:~/$ sudo pip3 install -r requirements.txt
[sudo] zhuji 的密码:
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 toinstall.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. Makesure 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 avirtual 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.
造成原因:
这个错误提示说明当前Python环境是由操作系统外部管理的(通常是因为使用了系统自带的Python),
为了避免破坏系统环境,建议使用虚拟环境或者使用系统包管理器(apt)来安装包。
根据提示,我们可以采取以下几种方法之一:
方法1:使用apt安装对应的包(如果存在的话)
但是这里我们是通过requirements.txt安装,可能包不在系统仓库中。
方法2:使用虚拟环境(推荐)
步骤:
1.创建一个虚拟环境
确保安装了python3-venv(如果没有,请先安装)
sudo apt install python3-venv
在项目目录下创建虚拟环境(假设虚拟环境目录名为venv)
python3 -m venv venv
2.激活虚拟环境,在虚拟环境中安装requirements.txt中的包
点击查看代码激活虚拟环境
source venv/bin/activate
然后使用pip安装requirements.txt中的包
pip install -r requirements.txt
3.当不再使用时,可以退出虚拟环境
关闭虚拟环境后,下载的pip包会自动消失点击查看代码
当不再使用时,可以退出虚拟环境(关闭虚拟环境后,下载的pip包会自动消失)
deactivate
方法3:
使用pipx(适用于安装Python应用程序,但这里是一组包,可能不太适合)
点击查看代码# 安装 pipx
sudo apt install pipx# 用 pipx 安装包(示例)
pipx install 包名
方法4:
忽略警告(不推荐),使用–break-system-packages参数,但这样可能会破坏系统环境。
点击查看代码
# 如果坚持安装到系统环境(可能破坏系统稳定性),可添加 --break-system-packages 参数:
sudo pip3 install --break-system-packages -r requirements.txt