在GitHub Actions中无法缓存Python依赖(ruff、pytest)的问题
解决GitHub Actions中pip缓存不生效的问题
首先明确:你看到的Cache not found日志在第一次运行Workflow时是正常现象——此时还未生成任何缓存,Workflow会执行依赖安装并在运行结束后创建缓存,后续相同配置的运行才会命中缓存。
不过当前的缓存配置存在优化空间,下面给出具体改进方案:
1. 使用requirements.txt(或pyproject.toml)管理依赖
直接在命令行安装依赖的方式无法让缓存感知到依赖版本变化,建议将依赖写入requirements.txt文件:
# requirements.txt ruff pytest
若需要固定版本,可指定具体版本号(比如ruff==0.1.15),避免依赖自动更新导致缓存失效。
修改Workflow中的安装步骤:
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt
2. 优化缓存Key策略
将requirements.txt的哈希值加入缓存Key,这样只有当依赖列表变化时才会重新生成缓存,否则复用已有缓存。修改缓存步骤:
- name: Cache pip uses: actions/cache@v3 with: path: ~/.cache/pip key: ${{ runner.os }}-pip-${{ matrix.python-version }}-${{ hashFiles('requirements.txt') }} restore-keys: | ${{ runner.os }}-pip-${{ matrix.python-version }}-
3. 可选:使用专业依赖管理工具(Poetry/Pipenv)
如果项目规模较大,推荐用Poetry或Pipenv这类工具,它们会生成锁文件(poetry.lock/Pipfile.lock),能更精准地控制依赖版本,缓存策略也更可靠。以Poetry为例,Workflow配置可调整为:
- name: Install Poetry run: pip install poetry - name: Cache Poetry dependencies uses: actions/cache@v3 with: path: | ~/.cache/pypoetry .venv key: ${{ runner.os }}-poetry-${{ matrix.python-version }}-${{ hashFiles('poetry.lock') }} restore-keys: | ${{ runner.os }}-poetry-${{ matrix.python-version }}- - name: Install dependencies run: poetry install --no-root
修改后的完整Workflow示例
name: Code analysis on: pull_request: push: branches: main jobs: analyze: runs-on: ubuntu-latest strategy: matrix: python-version: ["3.8", "3.9", "3.10"] steps: - name: Check out repository uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 with: python-version: ${{ matrix.python-version }} - name: Cache pip uses: actions/cache@v3 with: path: ~/.cache/pip key: ${{ runner.os }}-pip-${{ matrix.python-version }}-${{ hashFiles('requirements.txt') }} restore-keys: | ${{ runner.os }}-pip-${{ matrix.python-version }}- - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run Ruff run: ruff check script.py tests.py - name: Run pytest run: pytest tests.py
注意:修改后第一次运行仍会显示Cache not found,但运行结束后会创建缓存,第二次及后续运行就能正常命中缓存了。
内容的提问来源于stack exchange,提问作者Swantewit
相关产品推荐
相关产品推荐

