Skip to main content
 首页 » 编程设计

python之如何在 Gitlab-CI 上安装 Python

2025年05月04日22TianFang

如何在Gitlab-CI上安装各种版本的Python?

根据我之前使用 Travis-CI 的经验,我只是运行普通的 Ubuntu/Debian 命令来安装 deadsnakes 存储库,然后安装我需要的任何版本,例如:

sudo add-apt-repository -y ppa:fkrull/deadsnakes 
sudo apt-get -yq update 
sudo apt-get -yq install python2.7 python2.7-dev python3.4 python3.4-dev python3.6 python3.6-dev python3.7 python3.7-dev 

我已经用 Gitlab-CI 尝试过这种类似的配置:

image: ubuntu:latest 
 
before_script: 
  - add-apt-repository -y ppa:fkrull/deadsnakes 
  - apt-get -yq update 
  - apt-get -yq install python2.7 python2.7-dev python3.4 python3.4-dev python3.6 python3.6-dev python3.7 python3.7-dev 
  - python -V 
 
test: 
  script: 
  - ./run_my_tests.sh 

但这失败了:

/bin/bash: line 82: add-apt-repository: command not found 

我只能假设即使我运行的是 Ubuntu 镜像,Gitlab 也会限制可用的命令。在 Gitlab-CI 中安装 Python 的等效方法是什么?

请您参考如下方法:

您应该使用包含您需要的一切的基础图像。手动安装一些东西原则上应该可行,但会不必要地花费您 GitLab CI 流水线时间。

对于 python 3.7,您可以执行以下操作:

image: python:3.7-alpine3.9 

检查 DockerHub 以获取所有可用 python 图像的列表:https://hub.docker.com/_/python

如果您需要使用不同的 python 版本进行测试,我建议将您的任务拆分为不同的 GitLab CI 作业,每个作业使用不同的 python 基础镜像:

test-python-3-7: 
  image: python:3.7-alpine3.9 
  script: 
  - ./run_my_tests.sh 
 
test-python-2.7: 
  image: python:2.7.16-alpine3.8 
  script: 
  - ./run_my_tests.sh 

如果你绝对需要自己安装东西,因为没有合适的镜像,我仍然建议你创建一个包含你需要的所有东西的镜像,将它上传到 DockerHub 或者你自己的 GitLab 容器注册表,然后在你的CI 管道。