Closed2

error: externally-managed-environmentの対処法

nn

経緯

pip install requests

を実行すると以下のエラーが出る。

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.
nn

対処法

  • 仮想環境を使用する
    エラーメッセージの中にもあるこの部分ですね。
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

仮想環境の作成と使用

  1. 仮想環境を作成する

    python3 -m venv myenv
    
  2. 仮想環境を有効化する

    source myenv/bin/activate
    
  3. 仮想環境内で pip を使ってパッケージをインストールする

    pip install requests
    
  4. 仮想環境を終了したい場合は下記コマンドを実行する

    deactivate
    
このスクラップは2024/12/31にクローズされました