2024年Python外部环境管理问题解决方法

python 在这里遇见问题如何解决:

  • error: externally-managed-environment
  • × This environment is externally managed
    ╰─> To install Python packages system-wide, try brew install
    xyz, where xyz is the package you are trying to
    install.

    If you wish to install a non-brew-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.
    
    If you wish to install a non-brew 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.
    

    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.

    创建并使用虚拟环境

    1. 创建虚拟环境

    python3 -m venv /path/to/venv
    

    2. 激活虚拟环境

    source /path/to/venv/bin/activate
    
    source /Users/wangyang/PycharmProjects/venv/bin/activate
    

    3.在虚拟环境中安装

    pip install  xxxx
    

    4. 退出虚拟环境

    deactivate
    

    如果你希望直接在你的系统环境中使用 pip 来安装包,而不通过虚拟环境,你遇到的 externally-managed-environment 错误表明你的 Python 环境是由外部系统(如 Homebrew)管理的。这种情况下,系统建议你不要直接使用 pip 安装包,以避免潜在的冲突和问题。不过,如果你确实需要绕过这个限制,有几种方法可以尝试:

    方法 1:使用 --user 选项

    你可以尝试使用 pip--user 选项来安装包,这将会安装包到你的用户目录而非全局系统目录,有助于减少对系统环境的干扰。

    bashCopy code
    pip install --user jupyter
    

    方法 2:使用 Homebrew 安装

    既然你的环境是由 Homebrew 管理的,你也可以考虑使用 Homebrew 来安装 Jupyter。Homebrew 有时会提供 Python 包的配方。

    bashCopy code
    brew install jupyterlab
    

    注意:Homebrew 安装的可能是 JupyterLab,一个 Jupyter Notebook 的新一代用户界面。如果你只想要 Jupyter Notebook,你还是需要通过 pip 来安装。

    方法 3:忽略警告(不推荐)

    错误信息提到了一个选项 --break-system-packages,这个选项可以强制 pip 安装包,但是这样做有破坏你的 Python 安装或操作系统的风险,因此强烈不推荐使用。

    bashCopy code
    pip install jupyter --break-system-packages
    

    最佳实践

    虽然上述方法可以让你直接使用 pip 安装包,但强烈推荐使用虚拟环境来避免潜在的依赖冲突和不必要的麻烦,特别是当你在同一系统上进行多个项目开发时。虚拟环境提供了一种干净、隔离的方式来管理每个项目的依赖,确保了项目的可移植性和复现性。

    作者:itwangyang520

    物联沃分享整理
    物联沃-IOTWORD物联网 » 2024年Python外部环境管理问题解决方法

    发表回复