python(77) python脚本与jenkins pipeline交互的5种方式

1. 在 Pipeline 中执行 Python 脚本并获取输出

在 Jenkins Pipeline 中,利用sh(适用于 Linux、macOS)或bat(适用于 Windows)步骤来运行 Python 脚本,并通过returnStdout参数捕获脚本的标准输出。

groovy

复制代码
pipeline {
    agent any
    stages {
        stage('执行Python脚本') {
            steps {
                script {
                    def pythonOutput
                    if (isUnix()) {
                        // 在Linux或macOS上执行
                        pythonOutput = sh(
                            script: 'python3 your_script.py || python your_script.py', 
                            returnStdout: true
                        ).trim()
                    } else {
                        // 在Windows上执行
                        pythonOutput = bat(
                            script: 'python your_script.py', 
                            returnStdout: true
                        ).trim()
                    }
                    echo "Python脚本输出: ${pythonOutput}"
                }
            }
        }
    }
}

说明your_script.py是需要执行的 Python 脚本,returnStdout: true表示获取脚本的标准输出,.trim()用于去除输出结果中的首尾空格和换行符。

python脚本打印print信息默认会显示在pipeline console output中,实时输出需要加-u参数:

python -u demo.py

2. 向 Python 脚本传递参数

可以在执行 Python 脚本时,通过命令行参数的形式将 Pipeline 中的变量传递给 Python 脚本,Python 脚本通过sys.argv获取这些参数。

  • Jenkins Pipeline 脚本

groovy

复制代码
pipeline {
    agent any
    stages {
        stage('传递参数给Python脚本') {
            steps {
                script {
                    def paramValue = "Hello from Pipeline"
                    if (isUnix()) {
                        sh "python3 your_script.py ${paramValue}"
                    } else {
                        bat "python your_script.py ${paramValue}"
                    }
                }
            }
        }
    }
}
  • Python 脚本(your_script.py

python

运行

复制代码
import sys
if len(sys.argv) > 1:
    received_param = sys.argv[1]
    print(f"接收到的参数: {received_param}")

说明 :在 Pipeline 中定义变量paramValue,并将其作为参数传递给 Python 脚本,Python 脚本通过sys.argv获取并处理该参数。

3. 使用 Python 库与 Jenkins 进行远程交互

可以使用python-jenkins库在 Python 脚本中远程调用 Jenkins 的 API,实现诸如触发构建、获取构建状态等操作。

  • 安装python-jenkinspip install python-jenkins
  • Python 脚本示例

python

运行

复制代码
import jenkins

server = jenkins.Jenkins('http://your_jenkins_url', username='your_username', password='your_password')
job_name = 'your_job_name'
# 触发构建
server.build_job(job_name)
# 获取构建信息
last_build_number = server.get_job_info(job_name)['lastBuild']['number']
build_info = server.get_build_info(job_name, last_build_number)
print(f"构建状态: {build_info['result']}")

说明 :此方式适用于需要在 Python 脚本中主动操作 Jenkins 任务的场景,通过python-jenkins库提供的接口与 Jenkins 服务器进行通信。

4. 通过文件共享数据

在 Pipeline 中,可以使用writeFile步骤将数据写入文件,Python 脚本读取该文件获取数据;反之,Python 脚本也可以将处理结果写入文件,Pipeline 再通过readFile步骤读取。

  • Jenkins Pipeline 脚本

groovy

复制代码
pipeline {
    agent any
    stages {
        stage('写入数据到文件') {
            steps {
                script {
                    def dataToWrite = "Some important data"
                    writeFile file: 'data.txt', text: dataToWrite
                }
            }
        }
        stage('执行Python脚本处理文件数据') {
            steps {
                script {
                    if (isUnix()) {
                        sh 'python3 process_data.py'
                    } else {
                        bat 'python process_data.py'
                    }
                }
            }
        }
        stage('读取Python脚本处理后的结果') {
            steps {
                script {
                    def result = readFile file: 'output.txt'
                    echo "处理结果: ${result}"
                }
            }
        }
    }
}
  • Python 脚本(process_data.py

python

运行

复制代码
with open('data.txt', 'r') as file:
    input_data = file.read()
# 处理数据
processed_data = input_data.upper()
with open('output.txt', 'w') as output_file:
    output_file.write(processed_data)

说明:Pipeline 先将数据写入文件,Python 脚本读取并处理后再写回文件,最后 Pipeline 读取处理后的结果文件。

这些方式各有适用场景,可根据具体需求选择合适的交互方式,实现 Jenkins Pipeline 与 Python 脚本之间高效的数据交互和功能协作。

5.通过数据库共享数据mysql, redis

相关推荐
vx_dmxq2112 小时前
免费领源码-Spring boot的物流管理系统 |可做计算机毕设Java、Python、PHP、小程序APP、C#、爬虫大数据、单片机、文案
java·大数据·python·jupyter·课程设计
飞翔的佩奇2 小时前
【完整源码+数据集+部署教程】鸡只与养殖场环境物品图像分割: yolov8-seg等50+全套改进创新点发刊_一键训练教程_Web前端展示
python·yolo·计算机视觉·数据集·yolov8·yolo11·鸡只与养殖场环境物品图像分割
dreams_dream2 小时前
Django 数据库迁移命令
数据库·python·django
两只程序猿3 小时前
数据可视化 | 热力图Heatmap绘制Python代码 相关性矩阵学术可视化
python·信息可视化·矩阵
倔强青铜三3 小时前
苦练Python第58天:filecmp模块——文件和目录“找不同”的利器
人工智能·python·面试
倔强青铜三3 小时前
苦练Python第59天:tempfile模块,临时文件自动删!再也不用手动清理到怀疑人生
人工智能·python·面试
IT教程资源3 小时前
(免费分享)基于python的飞机大战游戏
python·游戏·pygame
hello 早上好3 小时前
深入理解 SPI:从定义到 Spring Boot 实践
java·spring boot·python
蒋星熠4 小时前
脑机接口(BCI):从信号到交互的工程实践
人工智能·python·神经网络·算法·机器学习·ai·交互