新版ubuntu使用pip时发生的错误
新版ubuntu使用pip时发生错误:
- 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.
收到一个错误提示:error: externally-managed-environment
,即“外部管理环境”错误,但这不是一个 bug,新的发行版中,正在使用 Python 包来实现此增强功能,这个更新是为了避免操作系统包管理器 (如pacman、yum、apt) 和 pip 等特定于 Python 的包管理工具之间的冲突,这些冲突包括 Python 级 API 不兼容和文件所有权冲突。
可以看一下python官方的说明:
PEP 668 – Python base environments Python 增强提案 (PEP)https://realpython.com/python-virtual-environments-a-primer/?ref=yaolong.net
解决方案:
1:如果你习惯于原来的用法可以强制删除此警告:
sudo mv /usr/lib/python3.x/EXTERNALLY-MANAGED /usr/lib/python3.x/EXTERNALLY-MANAGED.bk
注意python版本号写你自己的别直接抄,不知道到底是多少可以进/user/lib看看:
find /usr/lib/ -type d -name "*python*"
2:老实点使用pipx
安装pipx:
sudo apt install pipx
以后就使用Pipx去安装包文件了:
pipx install package_name
添加环境变量:
pipx ensurepath
删除使用pipx安装的软件包:
pipx uninstall package_name
3:使用venv
如果你是专业开发人员,在运行或构建py文件时遇到“ModuleNotFoundError: No module named 'xxx'”
错误,推荐使用Python虚拟环境,借助虚拟环境,使用不同版本的包依赖项和Python,避免包之间的任何冲突。
安装 venv:
- sudo apt install python3-venv
- #或者
- sudo apt install python3.10-venv
生成Python虚拟环境:
mkdir -p $HOME/.env && python3 -m venv $HOME/.env/project_name
将看到一个.env在主目录中,并且你将在 .env 中拥有项目目录,每个虚拟环境项目目录中都会有自己的 Python 和 Pip 副本。
安装模块:
- $HOME/.env/project_name/bin/python -m pip install --upgrade pip
- $HOME/.env/project_name/bin/python -m pip install package_name
用新的虚拟环境执行py文件:
- source $HOME/.env/project_name/bin/activate
- $HOME/.env/project_name/bin/python ./xxxx.py