在 Debian 上配置 Python 持续集成
一 环境准备
sudo apt update && sudo apt upgrade -ysudo apt install -y git python3 python3-pip build-essentialpython3 -m venv .venv && source .venv/bin/activatepython -m pip install --upgrade pipsudo apt install -y docker.io && sudo systemctl enable --now docker二 方案一 Jenkins 自建 CI 服务器
sudo apt install -y openjdk-11-jdkwget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo apt-key add -echo "deb https://pkg.jenkins.io/debian-stable binary/" | sudo tee /etc/apt/sources.list.d/jenkins.listsudo apt update && sudo apt install -y jenkinssudo systemctl start jenkins && sudo systemctl enable jenkinspipeline {
agent any
environment {
PYTHON = 'python3'
}
stages {
stage('Checkout') {
steps { git url: 'https://github.com/your-org/your-python-app.git', branch: 'main' }
}
stage('Setup') {
steps {
sh '''
python3 -m venv .venv
. .venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt
'''
}
}
stage('Lint') {
steps {
sh '''
. .venv/bin/activate
pip install -U flake8
flake8 src tests
'''
}
}
stage('Test') {
steps {
sh '''
. .venv/bin/activate
pip install -U pytest pytest-cov
pytest --junitxml=reports/pytest.xml --cov=src --cov-report=xml:reports/coverage.xml
'''
}
}
}
post {
always {
junit 'reports/*.xml'
cleanWs()
}
}
}
三 方案二 GitHub Actions 云端 CI
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.11'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
pip install -U pytest pytest-cov
- name: Lint
run: |
pip install -U flake8
flake8 src tests
- name: Test
run: |
pytest --junitxml=reports/pytest.xml --cov=src --cov-report=xml:reports/coverage.xml
- name: Upload coverage
uses: codecov/codecov-action@v4
with:
token: ${{ secrets.CODECOV_TOKEN }} # 可选
四 关键实践与排错要点