Search code examples
pythongroovyjenkins-pipeline

Get output of a python script into a variable in Jenkinsfile


I have a Python script which returns a string on stdout. The value rerturned by the python script can be collected in a bash script like below:

#!/bin/bash

outputString=$(./my_python_script.py -some_parameter 2>&1)
echo "The output string is $outputString"

On a scripted pipeline with the Jenkinsfile written in Groovy, I need to call my python script from the Jenkinsfile and collect the output into a variable in the Jenkinsfile.

Question:
How do I do this provided that my Jenkinsfile run on a macOS node. Following is the way how I can at least get the output in a shell variable.

stage('My build') {
    node('my_build_node') {
        sh 'output_string=$(./my_python_script.py -some_parameter 2>&1) && sh 'echo The output_string is $output_string'
    }
}

Solution

  • def outputString = sh returnStdout:true, script:'./my_python_script.py -some_parameter 2>&1'
    println "the output string is: ${outputString}"
    

    sh step parameters details: https://www.jenkins.io/doc/pipeline/steps/workflow-durable-task-step/#sh-shell-script