# 错误：外部管理的环境
× 此环境由外部管理
╰> 要系统安装 Python 包，请尝试 apt install python3-xyz，其中 xyz 是你要安装的包。

如果你希望安装非 Debian 打包的 Python 包，请使用 python3 -m venv path/to/venv 创建虚拟环境。
然后使用 path/to/venv/bin/python 和 path/to/venv/bin/pip。确保已安装 python3-full。

如果你希望安装非 Debian 打包的 Python 应用程序，最简单的方法是使用 pipx install xyz，它会为你管理虚拟环境。确保已安装 pipx。

更多信息请参见 /usr/share/doc/python3.11/README.venv。

- **ID:** `pip/pep-668-externally-managed-environment`
- **领域:** pip
- **类别:** install_error
- **错误码:** `error`
- **验证级别:** ai_generated
- **修复率:** 92%

## 根因

Debian/Ubuntu 系统将系统 Python 安装标记为外部管理（根据 PEP 668），以防止 pip 覆盖由系统包管理器管理的包，但用户尝试在虚拟环境外部全局使用 pip 安装包。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| pip 23.0+ | active | — | — |
| Debian 12 | active | — | — |
| Ubuntu 23.04+ | active | — | — |
| Python 3.11 | active | — | — |

## 解决方案

1. ```
   创建并使用虚拟环境：python3 -m venv myenv && source myenv/bin/activate && pip install <package>
   ```
2. ```
   使用 pipx 安装 CLI 应用程序：pipx install <package>
   ```
3. ```
   通过 apt 安装包（如果可用）：apt install python3-<package>
   ```

## 无效尝试

- **Running pip with --break-system-packages flag** — This flag bypasses the protection but may break system tools that depend on specific package versions, leading to system instability or broken apt packages. (30% 失败率)
- **Removing the EXTERNALLY-MANAGED file from /usr/lib/python3.x/** — Deleting the marker file permanently disables the protection, but future system updates may restore it, and it violates the distribution's design intent. (40% 失败率)
- **Installing packages with sudo pip install** — Running pip as root in a system environment can corrupt system Python packages, cause permission conflicts, and is strongly discouraged by Python packaging guidelines. (60% 失败率)
