【问题标题】:Issue caching python dependencies in GitHub Actions在 GitHub Actions 中问题缓存 python 依赖项
【发布时间】:2021-10-24 00:21:30
【问题描述】:

我在 github 操作中有以下步骤:

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.

缓存依赖项的全部意义在于我不必在每次运行工作流时都安装它们。如何使用缓存的依赖项?

【问题讨论】:

    标签: python github pip github-actions


    【解决方案1】:

    您只缓存pip 下载的源压缩包二进制轮子。你没有缓存:

    • 已安装的 Python 包(即活动 Python 解释器的 site-packages/ 子目录)。
    • 已安装的入口点(即驻留在当前${PATH} 中的可执行命令)。

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

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

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

    接受挑战。这是可行的——尽管更脆弱。我建议只缓存 pip 下载,除非您已将 pip install 命令配置为重要的安装瓶颈。

    假设您仍想这样做。在这种情况下,类似于以下 sn-p 的东西应该可以让您到达您想去的地方:

      - 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 子字符串替换为特定于您的用例的内容。这就是为什么它非常脆弱的几个原因之一。另一个是the ${{ env.pythonLocation }} environment variable set by the setup-python GitHub Action has been infamously undocumented for several years</gulp>

    理论上,将上述内容直接添加到现有的uses: actions/cache@v2 列表项下就足够了。进入可怕的未知世界,祝你好运。

    【讨论】:

    • 感谢您的回复!是的,我在发布此消息后不久注意到删除if: steps.pip-cache.outputs.cache-hit != 'true' 解决了这个问题。我添加它是因为我看到 pip 输出说的是installing dependencies,但没有仔细看它说的是installing cached dependencies... 伙计们,请务必仔细阅读您的日志。
    猜你喜欢
    • 2021-11-18
    • 2020-07-23
    • 2021-02-18
    • 2021-07-12
    • 2021-01-21
    • 2015-09-30
    • 2020-06-02
    • 2020-12-10
    • 1970-01-01
    相关资源
    最近更新 更多