2025,在 linux 上安装 pipenv 的正确姿势,避免低版本 pipenv 和高版本 cpython 兼容报错

之前在 linux(比如 debian11、ubuntu22 这些发行版)安装 pipenv 有两种方式

第一种方式:apt install python3-pipenv 利用 debian 系的 apt 包管理器安装 pipenv,但是这样会有一个问题,就是 pipenv 的版本会非常的滞后,和发行版自带的 cpython 版本兼容是没有问题,但是如果你安装了额外的 cpython ,尤其是更加新版本的 cpython (比如系统自带的是 cpython3.10,你自己编译安装了一个 cpython3.12,这个时候,想用 apt 安装的旧 pipenv 为 cpython3.12 创建虚拟环境几乎是 100% 报错失败)

第二种方式:pip3 install pipenv 利用系统上的系统的 pip 命令,安装一个 pipenv,这样可以避免上面的旧版本 pipenv 的问题,但是现在较新的 linux 发行版,都禁止使用系统的 pip 直接安装第三方命令了(为了避免搞乱系统的依赖)具体可看:如何突破 debian12 对于系统的 pip 安装第三方包的限制?

在 debian12 中,直接使用 pip 安装 pipenv 会报错如下⬇️

root@720338de0393:/# pip install pipenv
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.

所以我们要怎么安装 pipenv 呢?我建议使用 pipx

apt install pipx

pipx 的子命令用法和 pip 差不多

要安装 pipenv 就直接 pipx install pipenv 即可

root@720338de0393:/# pipx install pipenv
  installed package pipenv 2024.4.1, installed using Python 3.12.3
  These apps are now globally available
    - pipenv
    - pipenv-resolver
⚠️  Note: '/root/.local/bin' is not on your PATH environment variable. These apps will not be globally accessible until your PATH is updated. Run `pipx ensurepath` to automatically add it, or manually modify your PATH in your shell's config file (i.e. ~/.bashrc).
done! ✨ 🌟 ✨

⚠️ 注意输出中提到的 PATH 环境变量的问题


universe_king
3.4k 声望686 粉丝