Jenkins groovy管道使用try catch和变量从python退出



我在jenkins上有一个管道,它在一个阶段内使用try-catch框架来尝试运行python脚本。一旦运行,python脚本要么打印一个正确的值,要么打印一个错误的值并退出,这取决于输入。我的目标是以后使用它来进行测试,所以我的要求是我需要能够区分python脚本是否成功,或者它是否以exit('ERR_MESSAGE')终止。

我已经使它工作,如果python运行到最后。但是,如果python以exit命令结束,jenkinsfile会正确理解该命令并跟随其后进行catch,但它不会像我需要的那样存储之前python脚本打印的文本。

你能帮忙吗?我做错了什么?请参见下面的jenkinsfile stage

stage('Test branch') {
steps {
script {
test_results = 'position 1'
try {
test_results = sh (
script: "python3 ${WORKSPACE}/testingjenkinsexit.py notpass",
returnStdout: true
).trim()
echo "Test results in passed test: ${test_results}"
} catch (err) {
echo "Test results in failed test numb 1: " + test_results
echo "Test results in failed test numb 2: ${test_results}"
echo err.getMessage()
println err.dump()
}
}
}
}

在上面的代码中,我调用脚本'testingjenkinsexit.py',输入'notpass',因为这是python脚本将以exit结束的脚本。如果我使用input pass,那么它会正常工作,因为python不会以exit结束。

下面的python脚本
from sys        import argv
def testingjenkins(desired_output):
#print relevant test results. If at least one test failed, stop execution
if desired_output == "'pass'":
print(desired_output)
else:
print('tests did not pass')
exit('Deployement interrupted by python.')
desired_output = "'" + str(argv[1]) + "'"
if __name__ == "__main__":
testingjenkins(desired_output)

非常感谢你的帮助。

我在jenkinsfile中使用try - catch来调用一个python脚本,该脚本打印值,如果输入错误,可能会以exit('MESSAGE')终止。我期望try-catch能够处理以exit结束的python(它与成功有关),并且我期望在执行良好和执行不良(以exit结束)的情况下,try-catch将能够存储python脚本打印的消息(它不做什么)。

我认为这是预期的行为。当脚本以非零退出码退出时,将不会返回StandardOut。如果您想获得输出,而不考虑状态,您可以这样做。下面的代码将结合STDOUT和STDERR,并在退出脚本时返回退出代码为0。这不会将执行移动到catch块。因此,您必须添加一个条件并检查返回的消息。

test_results = sh (
script: "python3 ${WORKSPACE}/test.py notpass 2>&1 || echo "status:$?"; exit 0",
returnStdout: true
)
# Output
Test results in passed test: tests did not pass
Deployement interrupted by python.
status:1

另一种方法是将STDOUT写入文件,然后在catch块中读取。

stage('Test branch') {
steps {
script {
test_results = 'position 1'
try {
test_results = sh (
script: "python3 ${WORKSPACE}/test.py notpass > output",
returnStdout: true
)
echo "Test results in passed test: ${test_results}"
} catch (err) {
output = readFile(file: 'output')
echo "Test results in failed test numb 1: " + output
echo "Test results in failed test numb 2: ${test_results}"
echo err.getMessage()
println err.dump()
}
}
}
}

最新更新