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-jenkins
库 :pip 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 脚本之间高效的数据交互和功能协作。