macox安装pytest报错解决方案
错误提示信息如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
pip3 install pytest
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.
|
提示信息已经明确给出3种解决方案。
方案1,创建虚拟环境来安装
- 创建虚拟环境
1
|
python -m venv /usr/local/Cellar/python@3.12/3.12.3/
|
指定虚拟环境地址为本机python安装位置
- 激活进入虚拟环境,并执行安装指令
1
2
|
source /usr/local/Cellar/python@3.12/3.12.3/bin/activate
(3.12.3) ➜ pip3 install pytest
|
- 退出虚拟环境
- 配置环境加载
编辑环境配置文件
~/.zshrc
,添加配置:
1
|
alias pytest='/usr/local/Cellar/python@3.12/3.12.3/bin/pytest'
|
or
1
|
export PATH=$PATH:/usr/local/Cellar/python@3.12/3.12.3/bin
|
- 测试验证安装成功
1
2
3
4
5
6
7
8
9
10
11
|
pytest --version
pytest 8.2.2
pip3 list
Package Version
--------- -------
iniconfig 2.0.0
packaging 24.0
pip 24.0
pluggy 1.5.0
pytest 8.2.2
|
方案2,使用pipx工具安装
推荐使用 pipx 工具来安装。
pipx — Install and Run Python Applications in Isolated Environments
1
2
3
4
5
|
brew install pipx
pipx install pytest
pipx list
|
方案3,使用参数忽略错误
1
|
pip install pytest --break-system-packages --user
|
不推荐使用,有潜在的风险。
vscode选择venv环境
vscode打开命令面板,选择 Python: 创建环境,然后会显示两个环境类型:Venv 和 Conda
选择Venv在当前项目工作区创建.venv虚拟环境
选择后要求选择Python解释器,选择或输入Python解释器路径,如:/usr/local/bin/python3.12
然后会提示是否安装当前工作区依赖文件requirements.txt
中的依赖
选择安装后,就会自动进行安装,安装完成.venv虚拟环境就创建完成。
进入虚拟环境,并启动app项目:
1
2
3
4
5
6
7
8
|
# 进入虚拟环境
source .venv/bin/activate
# 启动app服务
(.venv) ➜ app uvicorn main:app --host 0.0.0.0 --port 80 --log-level debug
# 退出虚拟环境
(.venv) ➜ deactivate
|
pytest 使用示例
参考