在GitHub Actions中缓存Python依赖项的问题。

3

我在Github Actions中有以下步骤:

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

      - name: Cache dependencies
        id: pip-cache
        uses: actions/cache@v2
        with:
          path: ~.cache/pip
          key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
          restore-keys: |
            ${{ runner.os }}-pip-

      - name: Install dependencies
        if: steps.pip-cache.outputs.cache-hit != 'true'
        run: pip install -r requirements.txt
     
      - name: run mypy
        run: mypy .

缓存运作正常,但是当发生缓存命中并尝试运行mypy时,会出现以下错误:
Run mypy .
/home/runner/work/_temp/9887df5b-d5cc-46d7-90e1-b884d8c49272.sh: line 1: mypy: command not found
Error: Process completed with exit code 127.

整个缓存依赖的目的是为了我不必在每次运行工作流时都安装它们。我该如何使用缓存的依赖项?
1个回答

7
你只缓存由pip下载的源代码tar包二进制wheel包。你不会缓存以下内容:
  • 已安装的Python包(即活动Python解释器的site-packages/子目录)。
  • 已安装的入口点(即位于当前${PATH}中的可执行命令)。

这并不一定是件坏事。仅下载资产往往会消耗大量稀缺的GitHub Actions (GA)分钟;缓存资产可以轻松缓解这个问题。

换句话说,删除if: steps.pip-cache.outputs.cache-hit != 'true'行以恢复您的GitHub Actions (GA)工作流的正常运行。

但是...我想缓存已安装的包!

接受挑战。虽然更加脆弱,但这是可行的。我建议仅缓存pip下载,除非您已经对pip install命令进行了详细分析,并确定它是一个重要的安装瓶颈。

假设您仍然想这样做。在这种情况下,类似以下代码片段的内容应该能够满足您的需求:

  - uses: 'actions/setup-python@v2'
    with:
      # CAUTION: Replace this hardcoded "3.7" string with the
      # major and minor version of your desired Python interpreter.
      python-version: "3.7"
  - uses: 'actions/cache@v2'
    id: cache
    with:
      # CAUTION: Replace this hardcoded "python3.7" dirname with
      # the dirname providing your desired Python interpreter.
      path: ${{ env.pythonLocation }}/lib/python3.7/site-packages/*
      key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
      restore-keys: |
        ${{ runner.os }}-pip-
        ${{ runner.os }}-

正如所述,您需要手动替换上面硬编码的3.7python3.7子字符串,以便与您的用例具体相关。这是为什么它危险脆弱的几个原因之一。另一个原因是由setup-python GitHub操作设置的${{ env.pythonLocation }}环境变量已经臭名昭着地未记录了数年。 (env.pythonLocation文档已从v4.0.0添加。)</gulp> 理论上,在您现有的uses: actions/cache@v2列表项下直接添加上述内容应该就足够了。祝你好运并在进入可怕的未知领域时保持勇气。

谢谢回复!是的,我发帖后不久就注意到删除 if: steps.pip-cache.outputs.cache-hit != 'true' 就可以解决问题了。我添加它是因为我看到 pip 的输出说 installing dependencies,但没有仔细看到它说的是 installing cached dependencies... 大家一定要仔细阅读日志。 - rcb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接