pip3 install black
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.

1 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及其包时会遇到。这种情况下,直接使用 pip3 install 命令安装Python包可能会导致环境混乱或损坏。错误信息提供了几种解决方案,具体取决于你的需求:

如果你想安装系统级别的Python包:

尝试使用Homebrew来安装,比如:

1
brew install package_name

在这里,package_name 是你想要安装的包在Homebrew中的名字,注意这不一定和pip中的名字一样。

如果你正在尝试安装不在Homebrew中的Python库:

建议使用虚拟环境来避免污染全局环境。以下是创建和激活虚拟环境的步骤:

  1. 创建虚拟环境:

1
python3 -m venv path/to/venv
  1. 激活虚拟环境:

1
source path/to/venv/bin/activate
  1. 现在你可以安全地安装任何包了:

1
python3 -m pip install package_name

如果你想安装不在Homebrew中的Python应用:

可以使用 pipx 来安装,这样每个应用都会在其自己的虚拟环境中运行,避免了依赖冲突。首先,你需要安装 pipx

1
brew install pipx

然后使用 pipx 来安装应用:

1
pipx install package_name

如果你确定要在这个被外部管理的环境中安装包:

你可以尝试使用 --break-system-packages 标志来覆盖这个保护机制,但这是不推荐的,因为它可能会破坏你的Python安装或操作系统。如果你选择这条路,请确保你理解可能的后果,并考虑使用 --user 标志来将安装限制在用户级别,减少系统级别的风险:

1
python3 -m pip install --user --break-system-packages package_name

请确保你完全理解这些操作的含义和潜在的风险,在进行任何更改之前备份重要数据。