Github Actions运行pytest时遭遇ModuleNotFoundError问题求助
问题分析与解决方案
核心问题
你的Github Actions依赖安装步骤中,使用了pip download -r /dev/stdin --dest=dest,这个命令仅将依赖包下载到dest目录,并未安装到当前Python运行环境。所以运行pytest时,Python找不到spacy、beautifulsoup4这些依赖,导致导入错误。
修正方案
方案1:直接安装依赖(最简单)
修改Install dependencies步骤中的最后一行,把pip download改成pip install,直接从pyproject.toml读取依赖并安装:
- name: Install dependencies run: | python -m pip install --upgrade pip python -m pip install flake8 pytest black pip install toml && python -c 'import toml; c = toml.load("pyproject.toml"); print("\n".join(c["build-system"]["requires"]))' | pip install -r /dev/stdin
方案2:先下载再安装(如需缓存包)
如果需要先下载包再安装(比如用于缓存优化),需添加安装步骤:
- name: Install dependencies run: | python -m pip install --upgrade pip python -m pip install flake8 pytest black pip install toml && python -c 'import toml; c = toml.load("pyproject.toml"); print("\n".join(c["build-system"]["requires"]))' | pip download -r /dev/stdin --dest=dest # 从下载的目录安装所有依赖 pip install --no-index --find-links=dest -r <(python -c 'import toml; c = toml.load("pyproject.toml"); print("\n".join(c["build-system"]["requires"]))')
额外规范建议
build-system.requires字段的设计初衷是仅包含构建包所需的依赖(比如setuptools、wheel),测试依赖(pytest、pytest-env)和业务依赖(numpy、spacy、beautifulsoup4)应该放在更合适的位置:
- 在pyproject.toml中添加
[project]字段声明业务依赖,添加[project.optional-dependencies]声明测试依赖:[project] name = "your-package-name" version = "0.1.0" dependencies = [ "numpy==1.21.6", "beautifulsoup4~=4.12.2", "spacy==3.4.4" ] [project.optional-dependencies] test = [ "pytest==7.3.1", "pytest-env==0.8.1" ] [build-system] requires = ["setuptools>=61.0", "wheel"] build-backend = "setuptools.build_meta" - 然后在Github Actions中安装包和测试依赖:
- name: Install dependencies run: | python -m pip install --upgrade pip python -m pip install flake8 black # 安装包本身及其测试依赖 pip install ".[test]"
内容的提问来源于stack exchange,提问作者dark_matter88
相关产品推荐
相关产品推荐

