我使用虚拟环境在 github 上的多个 CI 作业中缓存已安装的 python 包。 该环境应该在 CMake(调用 python 脚本)中使用。 然而,如下所示,尽管在激活 env 后调用了 CMake,但 CMake 仍无法识别虚拟环境。
有人遇到过类似的问题吗?
我创建了一个最小(非)工作示例。您会注意到,“打印 python 版本”步骤的输出按预期工作:
/opt/hostedtoolcache/Python/3.10.13/x64/bin/python
Python 3.10.13
/home/runner/work/ci_pipeline_cmake_meets_python/ci_pipeline_cmake_meets_python/.venv/bin/python
Python 3.10.13
当我使用CMake执行脚本时,出现以下错误:
-- Found Python3: /opt/hostedtoolcache/Python/3.10.13/x64/bin/python3.10 (found version "3.10.13") found components: Interpreter
--
Traceback (most recent call last):
File "/home/runner/work/ci_pipeline_cmake_meets_python/ci_pipeline_cmake_meets_python/main.py", line 1, in <module>
import jinja2
ModuleNotFoundError: No module named 'jinja2'
在这里,您可以找到 Workflow-file 和 CMakeLists.txt
在您的日志中,即使在激活
venv
后,Python3 的路径也是默认路径:
-- Found Python3: /opt/hostedtoolcache/Python/3.10.13/x64/bin/python3.10 (found version "3.10.13") found components: Interpreter
然而,它应该是来自
venv
本身的。
Python3_ROOT_DIR
env var 等 是由 actions/setup-python
设置的,我怀疑这是造成此问题的原因。在命令级别重置它使其工作:
Python3_ROOT_DIR= cmake -B build -S .
CMake 日志和输出:
-- Found Python3: /home/runner/work/ci_pipeline_cmake_meets_python/ci_pipeline_cmake_meets_python/.venv/bin/python3.10 (found version "3.10.13") found components: Interpreter
--
Hello World
这是我用于此测试的更新工作流程:
name: 'test'
on: workflow_dispatch
jobs:
install-and-build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.10"
# cache: "pip"
- name: Cache virtualenv
uses: actions/cache@v3
id: cache-venv
with:
path: ./.venv/
key: ${{ runner.os }}-.10-venv-${{ hashFiles('requirements.txt') }}
restore-keys: |
${{ runner.os }}-3.10-venv-
- name: 'Install python dependencies for generator'
if: steps.cache-venv.outputs.cache-hit != 'true'
run: |
python --version
python -m venv ./.venv
source ./.venv/bin/activate
python -m pip install --upgrade pip
if [[ -f requirements.txt ]]; then
pip install -r requirements.txt
fi
- name: 'Print python version'
run: |
which python
python --version
source ./.venv/bin/activate
which python
python --version
- name: 'Run a simple python script directly'
run: |
source ./.venv/bin/activate
python main.py
- name: 'Use CMake for the same script'
run: |
source ./.venv/bin/activate
Python3_ROOT_DIR= cmake -B build -S .
除此之外,我为
cache: "pip"
评论了actions/setup-python
,因为pip
的缓存目录也必须被缓存以供后续工作流程使用。希望您能够解决这个问题。