pip で error: externally-managed-environment が出てパッケージがインストールできない
問題
以下のようなメッセージが出て、モジュールのインストールやアップデートができない。
code:console
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.11/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.
原因
なぜ、こうなっているのか
「OS のベースシステムとして、OS のパッケージ管理システムによってインストールされる Python は、その整合性を保つためにはOSのパッケージ管理システムでモジュールまで管理されるべきで、pip で外部からモジュールをインストールされるべきではない。個人が使う Python は、個人が仮想環境(venv)で個別にインストールして管理するべき。」という考え方になったため。
対応
「正しい」対処方法
メッセージに書いてあるように、別の Python 環境を作る。
先に pythonx.xx-venv のインストールが必要
code:console
$ python3 -m venv ~/local_python
The virtual environment was not created successfully because ensurepip is not
available. On Debian/Ubuntu systems, you need to install the python3-venv
package using the following command.
apt install python3.11-venv
You may need to use sudo with that command. After installing the python3-venv
package, recreate your virtual environment.
$ sudo apt install python3.11-venv
code:console
$ python3 -m venv ~/local_python
path に、~/local_python/bin を追加。
無理矢理パッケージを導入する方法
よくないがシステムの Python で動かなければならないモジュールをインストールする場合はこれしかなさげ
pip コマンドに --break-system-package オプションを渡せばインストールできる。