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

GitHub Action setup-python缓存生效后仍执行pip全量安装的原因

问题原因

setup-python的cache: 'pip'仅缓存pip下载的包文件(默认路径~/.cache/pip),而非已安装到Python环境的依赖。所以缓存命中后,pip只是从本地缓存读取包文件,仍会检查当前全新的GitHub Action虚拟机环境是否已安装对应版本的依赖——环境干净无已装依赖时,就会重新安装包,日志显示Using cached而非Requirement already satisfied。

解决方案

要实现"依赖已满足"的效果,需要同时缓存pip的下载缓存和Python的site-packages目录(已安装依赖的存放路径)。以下是修改后的工作流:

name: Python Testing

on:
  push:
    branches: [ master ]
  pull_request:
    branches: [ master ]

permissions:
  contents: read

jobs:
  coverage_check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-python@v4
        id: setup-python
        with:
          python-version: "3.6"
      # 获取pip缓存目录和site-packages路径
      - name: Get cache paths
        id: cache-paths
        run: |
          echo "pip-cache=$(pip cache dir)" >> $GITHUB_OUTPUT
          echo "site-packages=$(python -c 'import site; print(site.getsitepackages()[0])')" >> $GITHUB_OUTPUT
      # 缓存pip下载文件和已安装依赖
      - uses: actions/cache@v3
        with:
          path: |
            ${{ steps.cache-paths.outputs.pip-cache }}
            ${{ steps.cache-paths.outputs.site-packages }}
          # 缓存键包含系统、Python版本、requirements哈希,确保依赖变更时缓存失效
          key: ${{ runner.os }}-python-${{ steps.setup-python.outputs.python-version }}-pip-${{ hashFiles('requirements.txt') }}
          # 回退键:匹配相同系统和Python版本的缓存
          restore-keys: |
            ${{ runner.os }}-python-${{ steps.setup-python.outputs.python-version }}-pip-
      - run: pip install -r requirements.txt --use-deprecated=legacy-resolver
补充说明
  • 缓存键中加入requirements.txt的哈希值,确保当依赖版本变更时自动生成新缓存,避免使用旧依赖。
  • 如果使用pip install --user安装到用户目录,可将site-packages路径替换为~/.local/lib/python3.6/site-packages(对应Python 3.6)。
  • Python 3.6已停止官方维护,若条件允许建议升级到更高版本,提升安全性和兼容性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:25:22