使用GitHub Actions设置Python环境教程
1. 项目介绍
setup-python
是一个由GitHub Actions团队开发的开源项目,旨在帮助用户在GitHub Actions工作流中轻松设置和管理Python环境。该项目支持安装特定版本的Python或PyPy,并将其添加到系统的PATH中。此外,它还提供了缓存依赖项的功能,以加速构建过程。
2. 项目快速启动
2.1 创建GitHub Actions工作流文件
在你的GitHub仓库中,创建一个名为 .github/workflows/main.yml
的文件,并添加以下内容:
name: Python CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.10' # 指定Python版本
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Run tests
run: |
python -m unittest discover
2.2 运行工作流
提交并推送你的更改,GitHub Actions将自动触发并运行你定义的工作流。你可以在GitHub仓库的“Actions”选项卡中查看工作流的运行状态和日志。
3. 应用案例和最佳实践
3.1 缓存依赖项
为了加速构建过程,可以使用 setup-python
的缓存功能。以下是一个示例,展示了如何缓存 pip
依赖项:
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.9'
cache: 'pip'
- run: pip install -r requirements.txt
3.2 使用PyPy
如果你需要使用PyPy来加速Python代码的执行,可以按如下方式配置:
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: 'pypy3.9'
- run: python my_script.py
4. 典型生态项目
4.1 actions/checkout
actions/checkout
是一个常用的GitHub Actions,用于从GitHub仓库中检出代码。它通常与 setup-python
一起使用,以确保工作流能够访问仓库中的代码。
4.2 actions/cache
actions/cache
是一个用于缓存构建依赖项的GitHub Actions。虽然 setup-python
已经内置了缓存功能,但在某些情况下,你可能需要更细粒度的缓存控制,这时可以使用 actions/cache
。
4.3 actions/upload-artifact
actions/upload-artifact
用于将构建输出上传到GitHub Actions的工件存储中,以便在后续步骤或工作流中使用。
通过结合使用这些生态项目,你可以构建一个高效、可靠的CI/CD工作流,确保你的Python项目在每次提交时都能得到充分的测试和验证。