
大家好,我是搞自动化的大飞~
今天碰到个挺长的Python报错,顺手记录一下,以防也有人会遇到。
这是在一台 Debian 服务器上跑 pip install xyz,报错信息:
× 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 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.
这个错误翻译成人话就是:系统不再允许使用 pip 直接安装全局包了
其实从 Python 3.11 开始,一些 Debian/Ubuntu 系统就默认启用了这个保护机制——目的是保护系统级的 Python 环境
别慌,系统环境不能安装,我们直接用虚拟环境安装就完事了
首先确认一下有没有 venv:
sudo apt update
sudo apt install python3-venv
如果是 macOS,用 Homebrew 安装的 Python 会默认自带 venv。其他系统则不会
在你项目的根目录执行:
python3 -m venv .venv
.venv 这个名字随便起,爱叫什么叫什么。执行完会在当前目录下生成一个 .venv 文件夹,所有东西都隔离在里面,跟系统环境互不干扰。
什么也不需要改,每次执行命令带上前缀即可
.venv/bin/pip3 install 包名
.venv/bin/python3 脚本.py
优点是不需要任何操作,缺点是每次都要加上前缀
使用命令激活:source .venv/bin/activate
激活之后,命令行前面会出现 (.venv) 的标识,这时候直接用 pip 和 python 就行了,不用再带路径:
pip3 install 包名
python3 脚本.py
用完退出环境:
deactivate
externally-managed-environment 这个报错,不用慌。使用命令新建一个虚拟环境,再安装就完事儿了今天就到这,你之前遇到过这个报错吗?评论区聊聊你是怎么解决的,下期见👋
点个关注,获取更多编程技巧~