python pip安装-r requirements.txt失败:此环境由外部管理

33qvvth1  于 2023-03-11  发布在  Python
关注(0)|答案(1)|浏览(2372)
pip install -r requirements.txt
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.

我希望有人能给我解释一下该怎么做以及如何解决这个问题

nfs0ujit

nfs0ujit1#

这是因为您的发行版采用了PEP 668 – Marking Python base environments as “externally managed”
TL;DR:使用venv

python3 -m venv .venv
source .venv/bin/activate
python3 -m pip install -r requirements.txt

说来话长:您的发行版试图防止混合apt提供的包和pip提供的包,混合两个包管理器(aptpip)总是一个坏主意,也是许多问题的根源。
PEP 668是发行版明确告诉用户避免掉到这个坑里的一种方式。你的发行版在消息中告诉你三种解决方案,但只有第二种完全适用于你的用例:

  • 使用apt install python3-xxx。它并不完全适用于你,因为你有一个requirements.txt,而不是一个单一的依赖关系。如果你在文件中只有几个需求,并且可以为每个需求手动完成,比如apt install python3-xxx python3-yyy python3-zzz,它会起作用。在这种情况下,没有奇怪的包管理器混合:您使用apt安装了python3,您正在使用apt安装依赖项:没有意外。
  • 使用venv:python3 -m venv .venv,然后source .venv/bin/activate,最后pip install -r requirements.txt。在这种情况下,安装包含在.venv目录中:没有混合apt和pip的功能,没有惊喜。
  • 使用pipx并不完全适用于您的情况,pipx很适合安装和使用像pipx install black这样的程序,但在这里您需要安装需求文件中列出的库,而不是程序。

还有另一种方法,我自己经常使用,因为我经常需要多个 * 不同 * 的Python版本:

  • 使用一个不是由你的发行版提供的Python,这样它就不会弄乱apt安装的东西,也不会采用PEP 668。我经常使用a short bash function自己编译许多Python解释器,这些解释器使用--prefix=~/.local/,用于测试目的。对于那些Python,我使用venv或者一个好的老pip install,在这种情况下,pip将把它安装在~/.local/中,同样,aptpip之间没有冲突,没有坏的意外。

相关问题