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

如何通过CodeBuild缓存Python项目的.venv虚拟环境?

解决CodeBuild中Python虚拟环境缓存的符号链接问题

问题场景

尝试通过CodeBuild缓存Python项目的.venv虚拟环境文件夹,使用的buildspec.yml配置如下:

version: 0.2
env: 
  shell: bash
phases:
  install:
    commands:
      - python3 -m venv .venv && source .venv/bin/activate
      - pip3 install -r requirements.txt
  build:
    commands:
      - pytest -v tests/
cache:
  paths:
    - .venv/**/*

执行时触发错误:

[Container] 2022/11/10 11:33:20 MkdirAll: /codebuild/local-cache/custom/11615810f/.venv
[Container] 2022/11/10 11:33:20 Symlinking: /codebuild/output/src682375820/src/hello.org/demo/.venv => /codebuild/local-cache/custom/11615810f/.venv

[Container] 2022/11/10 11:34:01 Running command python3 -m venv .venv && source .venv/bin/activate
Error: Unable to create directory '/codebuild/output/src682375820/src/hello.org/demo/.venv'

[Container] 2022/11/10 11:34:01 Command did not exit successfully python3 -m venv .venv && source .venv/bin/activate exit status 1
[Container] 2022/11/10 11:34:01 Phase complete: INSTALL State: FAILED
[Container] 2022/11/10 11:34:01 Phase context status code: COMMAND_EXECUTION_ERROR Message: Error while executing command: python3 -m venv .venv && source .venv/bin/activate. Reason: exit status 1

核心原因:CodeBuild会将配置的缓存路径创建为符号链接,而python3 -m venv无法在符号链接目录下生成新的虚拟环境。

解决方案

方法1:判断缓存状态,避免重复创建虚拟环境

修改install阶段命令,先检查.venv是否已存在(缓存生效时为指向缓存目录的符号链接),存在则直接激活,不存在再创建:

version: 0.2
env: 
  shell: bash
phases:
  install:
    commands:
      - |
        if [ ! -d .venv/bin ]; then
          python3 -m venv .venv
        fi
        source .venv/bin/activate
      - pip3 install -r requirements.txt
  build:
    commands:
      - pytest -v tests/
cache:
  paths:
    - .venv/**/*

方法2:直接在缓存目录创建虚拟环境,再链接到项目目录

指定虚拟环境直接在CodeBuild缓存目录生成,再通过软链接关联到项目目录:

version: 0.2
env: 
  shell: bash
  variables:
    VENV_PATH: "/codebuild/local-cache/custom/venv"
phases:
  install:
    commands:
      - |
        if [ ! -d $VENV_PATH/bin ]; then
          python3 -m venv $VENV_PATH
        fi
        ln -sf $VENV_PATH .venv
        source .venv/bin/activate
      - pip3 install -r requirements.txt
  build:
    commands:
      - pytest -v tests/
cache:
  paths:
    - /codebuild/local-cache/custom/venv/**/*

方法3:缓存pip下载包(简化方案)

若无需完整缓存虚拟环境,可只缓存pip的下载缓存,减少依赖安装时间:

version: 0.2
env: 
  shell: bash
phases:
  install:
    commands:
      - python3 -m venv .venv && source .venv/bin/activate
      - pip3 install --cache-dir /codebuild/local-cache/pip -r requirements.txt
  build:
    commands:
      - pytest -v tests/
cache:
  paths:
    - /codebuild/local-cache/pip/**/*

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 04:30:57