×

在Ubuntu24.04上执行pip install 报错:error: externally-managed-environment

Falcon 2025-04-24 views:
自动摘要

正在生成中……

运行pip安装一个pipy上的包:

pip install barkcli

报错:


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.12/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 24.04 引入了 PEP 668 规范,限制了你在 系统的全局 Python 环境 中使用 pip install 安装非系统管理的软件包,以避免破坏系统依赖。

推荐的解决方案

✅ 方法1:使用虚拟环境(推荐)

这是最标准、安全的方式:

# 安装 python3-venv,如果没有的话
sudo apt install python3-venv

# 创建一个新的虚拟环境
python3 -m venv bark_env

# 启动虚拟环境
source bark_env/bin/activate

# 然后在虚拟环境中安装 barkcli
pip install barkcli

每次使用都需要激活虚拟环境,可以用 deactivate 退出。


✅ 方法2:使用 pipx(更方便安装 CLI 工具)

pipx 是专门用于安装 CLI 工具(如 barkcli)的工具,它自动创建隔离环境:

# 安装 pipx
sudo apt install pipx

# 确保 pipx 初始化路径
pipx ensurepath

# 然后安装 barkcli
pipx install barkcli

安装后你可以直接在终端中运行 barkcli


❌ 方法3:强行使用 --break-system-packages(不推荐)

pip install barkcli --break-system-packages

⚠️ 不推荐此方法,可能会破坏系统包依赖,尤其是在升级或安装系统软件时引发冲突。


我选择了方法2

本文收录于