Python Azure Function CI流水线无法找到已安装的pytest模块
问题:Azure DevOps流水线安装pytest后无法找到模块
我正尝试创建Python Azure Function的CI流水线构建。在YAML文件中完成依赖安装(requirements.txt包含pytest)后,系统无法找到pytest模块,无法确定问题所在,遗漏了什么?
相关配置与信息
YAML流水线配置
- task: UsePythonVersion@0 displayName: Use Python 3.11 inputs: versionSpec: 3.11 - task: Bash@3 displayName: Install Application Dependencies inputs: targetType: inline script: >- python -m pip install --upgrade pip pip install --target="$(System.DefaultWorkingDirectory)/.python_packages/lib/site-packages" -r requirements.txt - script: pytest . --verbose
requirements.txt内容
pytest~=8.1.1
已尝试操作
- 添加
--target参数(如上所示) - 为pytest脚本添加
target: host - 使用venv(可正常工作,但不想使用venv)
Azure DevOps在pytest步骤执行失败,提示找不到pytest模块。
原因分析
你用--target参数将依赖安装到了指定的自定义目录($(System.DefaultWorkingDirectory)/.python_packages/lib/site-packages),但系统默认的Python环境路径并未包含这个目录,导致直接执行pytest命令时,系统找不到对应的可执行文件和模块。
解决方案
方案1:移除--target参数(推荐,若无需为Azure Function打包特定目录)
如果不需要将依赖安装到特定目录用于Azure Function部署,直接全局安装依赖即可,这样pytest会被添加到系统可执行路径中:
- task: UsePythonVersion@0 displayName: Use Python 3.11 inputs: versionSpec: 3.11 - task: Bash@3 displayName: Install Application Dependencies inputs: targetType: inline script: >- python -m pip install --upgrade pip pip install -r requirements.txt - script: pytest . --verbose
方案2:保留--target并配置PYTHONPATH
如果必须将依赖安装到指定目录(比如Azure Function部署要求),需要将该目录添加到PYTHONPATH环境变量,同时通过python -m pytest的方式调用(避免直接找可执行文件的路径问题):
- task: UsePythonVersion@0 displayName: Use Python 3.11 inputs: versionSpec: 3.11 - task: Bash@3 displayName: Install Application Dependencies inputs: targetType: inline script: >- python -m pip install --upgrade pip pip install --target="$(System.DefaultWorkingDirectory)/.python_packages/lib/site-packages" -r requirements.txt # 将目标目录添加到PYTHONPATH echo "##vso[task.setvariable variable=PYTHONPATH]$(System.DefaultWorkingDirectory)/.python_packages/lib/site-packages:$PYTHONPATH" - script: python -m pytest . --verbose
也可以直接调用目标目录下的pytest可执行文件(部分系统中pytest会安装在bin子目录):
- script: $(System.DefaultWorkingDirectory)/.python_packages/lib/site-packages/bin/pytest . --verbose
内容的提问来源于stack exchange,提问作者Deniz Ademoglu
相关产品推荐
相关产品推荐

