【问题标题】:Preserve return code from python script in Jenkins when used in a bash pipe在 bash 管道中使用时保留来自 Jenkins 中 python 脚本的返回代码
【发布时间】:2017-02-16 01:09:46
【问题描述】:

考虑一下:

$ cat test.py 
import sys
print "Doing something ..."
sys.exit(1)

$ python test.py
Doing something ...
$ echo $?
1

$ python test.py | tee log # used in Jenkins, but I need to capture rc of 1 as well
Doing something ...
$ echo $?
0

如您所见,如果我将输出通过管道传输到 tee,则无法从 python 脚本中捕获 1 的返回码。有没有办法我可以做到这一点?此代码位于 Jenkins 的 Build->execute shell 部分中。

由于我无法捕获 1 的 rc,因此该行后面的命令继续执行,这是我不希望发生的。

【问题讨论】:

    标签: python bash python-2.7 jenkins


    【解决方案1】:

    bash 中,您可以使用PIPESTATUS 数组来获取管道中每个命令的退出状态:

    python test.py | tee log
    echo ${PIPESTATUS[0]}
    

    【讨论】:

      【解决方案2】:

      关于“由于我无法捕获 1 的 rc,该行后面的命令将继续执行”,您可以在脚本的开头添加 set -o errexitset -o pipefail,如果您这样做,它将直接终止得到一个错误(即使在管道命令中)。 Here a good resource with a more in-depth explanation.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-07
        • 2020-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多