Python3 独立运行环境
错误提示
直接使用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.
在 Debian/Ubuntu 系统上,需要安装 python3-venv
1 | apt install python3.11-venv |
或者直接安装全量包
1 | apt install python3-full |
解决
使用 venv
为每一个应用创建一套“隔离”的Python运行环境。
比如说使用/root/001
目录为一个隔离运行环境(该目录不存在会自动创建)
1 | python3 -m venv /root/001 |
进入bin
目录,Linux/Mac
用source activate
,Windows用activate.bat
激活该venv环境
1 | cd /root/001/bin |
环境如果激活成功,命令提示符会有一个当前环境的前缀,表示当前环境是一个名为(001)
的Python环境。
此时,就可以正常使用pip安装各种包了。
退出当前的环境,使用deactivate
命令即可
1 | deactivate |
此时就回到了正常的环境
如果不再使用某个venv,首先确认该venv没有处于“激活”状态,然后直接把整个目录(001)
删掉就行。