You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Github Actions中Python虚拟环境缓存加载失败问题排查

问题分析与解决方案

缓存未命中的核心原因

缓存key生成失败,从日志可见key: venv-Linux-末尾无哈希值,说明hashFiles('**/_requirements_1.txt')未匹配到任何文件——你的依赖文件是requirements_1.txt,但表达式多了前缀下划线_,导致哈希计算为空,无法生成有效缓存key。

路径重复的说明

/home/runner/work/nn-playground/nn-playground/是GitHub Actions默认工作目录结构:第一个nn-playground是工作区根目录,第二个是代码checkout的目标目录(由actions/checkout@v2默认行为导致),属于正常现象,不影响缓存功能,无需修改。

修复后的完整CI/CD配置

name: CI/CD Pipeline

on:
  push:
    branches:
      - master

jobs:
  build-and-test:
    runs-on: ubuntu-latest

    steps:
      - name: Check out repository
        uses: actions/checkout@v2

      - uses: actions/setup-python@v4
        id: setup_python
        with:
          python-version: '3.11'

      - name: Cache venv directory
        uses: actions/cache@v4
        id: cache_venv
        with:
          path: ./.boston_house_price_prediction_venv
          key: venv-${{ runner.os }}-${{ steps.setup_python.outputs.python-version }}-${{ hashFiles('**/requirements_1.txt') }}
          # 可选:添加restore-keys实现同版本兼容缓存
          restore-keys: |
            venv-${{ runner.os }}-${{ steps.setup_python.outputs.python-version }}-

      - name: Install dependencies (if cache miss)
        if: steps.cache_venv.outputs.cache-hit != 'true'
        run: |
          python -m venv .boston_house_price_prediction_venv
          source .boston_house_price_prediction_venv/bin/activate
          python -m pip install --upgrade pip
          python -m pip install -r requirements_1.txt

      - name: Run tests
        run: |
          source .boston_house_price_prediction_venv/bin/activate
          pytest --cov=src src/tests/boston_housing_price_prediction/test_*.py

关键改动说明

  • 修复缓存key:将hashFiles('**/_requirements_1.txt')改为hashFiles('**/requirements_1.txt')匹配实际依赖文件;同时加入Python版本到key中,避免不同Python版本的缓存冲突。
  • 添加缓存命中判断:用if: steps.cache_venv.outputs.cache-hit != 'true'控制依赖安装逻辑,仅缓存未命中时才创建虚拟环境并安装依赖,避免重复操作覆盖缓存。
  • 拆分测试环节的激活命令:每个step是独立shell会话,环境变量不会自动继承,测试步骤需单独激活虚拟环境。
  • 可选restore-keys:当依赖文件更新时,会尝试加载同Python版本的旧缓存,进一步加速依赖安装。

内容的提问来源于stack exchange,提问作者joesan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 11:16:07