通过Homebrew安装的Python,在使用pip包管理器直接安装包时会出现如下报错:

错误

hex@macbook ~ % pip3 install fastapi
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 Python library that isn't in Homebrew,
    use a virtual environment:

    python3 -m venv path/to/venv
    source path/to/venv/bin/activate
    python3 -m pip install xyz

    If you wish to install a Python application that isn't in Homebrew,
    it may be easiest to use 'pipx install xyz', which will manage a
    virtual environment for you. You can install pipx with

    brew install pipx

    You may restore the old behavior of pip by passing
    the '--break-system-packages' flag to pip, or by adding
    'break-system-packages = true' to your pip.conf file. The latter
    will permanently disable this error.

    If you disable this error, we STRONGLY recommend that you additionally
    pass the '--user' flag to pip, or set 'user = true' in your pip.conf
    file. Failure to do this can result in a broken Homebrew installation.

    Read more about this behavior here: <https://peps.python.org/pep-0668/  >

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.

出现错误的原因

Homebrew 对其管理的 Python 环境进行了保护,以防止系统范围内的 Python 环境被破坏。

解决办法

根据官方推荐,建议使用虚拟环境。

创建虚拟环境

python3 -m venv venv

激活虚拟环境

source venv/bin/activate

安装包

激活虚拟环境后,你会在shell中看到(venv),这就表示你已经在Python虚拟环境,接下来可以安装你需要的包。

pip install package_name

关闭虚拟环境

deactivate

添加命令别名

每次开发我们都要进入虚拟环境,激活虚拟环境的命令有点长,可以在shell的配置文件中添加别名,找到shell配置文件,比如~/.zshrc 或 ~/.bashrc,这是ZSH和BASH的配置文件。

alias venv='source venv/bin/activate'

添加完后,重新打开shell,就可以使用venv快速进入Python虚拟环境。

SOCKS的坑

在shell中配置了socks5代理,在使用pip时也会出现错误:

ERROR: Could not install packages due to an OSError: Missing dependencies for SOCKS support.

WARNING: There was an error checking the latest version of pip.

最简单的办法就是取消socks5代理,但是如果某些特殊原因必须使用代理,两种办法,一种是安装PySocks库,另外一种把socks5改成http代理即可解决(推荐)。