简体   繁体   English

从jenkinsfile调用python脚本会输出标准输出,但不会返回返回值

[英]calling python script from jenkinsfile prints stdout but not returning the return value

I'm using the following py script and triggering it with the following groovy script. 我正在使用以下py脚本,并使用以下groovy脚本触发它。 The triggering itself is done by groovy b.jenkinsfile : 触发本身是由groovy b.jenkinsfile完成的:

a.py - Python 2.7 a.py-Python 2.7

import sys

def main(x):
    print x
    return 2

if __name__ == '__main__':
    main(sys.argv[1:])

b.jenkinsfile - Groovy b.jenkinsfile-Groovy

def cmd = ["python", "a.py", "arg"]
def func = cmd.execute()
func.waitForOrKill(10000)
println func.text
func.dump()
println func

The output I get is ["arg"] which is about what I expected (actually expected it without the [], but that's beside the point). 我得到的输出是[“ arg”],与我的期望值差不多(实际上期望它不带[],但这不重要)。

I can't seem to get the actual return value of the object. 我似乎无法获得该对象的实际返回值。 why is text / dump / func itself won't give the return value? 为什么text / dump / func本身不提供返回值?

tried also return main(sys.argv[1:]) instead of plain calling to main , but that supressed my print x for some reason... 尝试也return main(sys.argv[1:])而不是简单地调用main ,但是由于某种原因,这限制了我的打印x ...

to get exit value use func.exitValue() . 要获取退出值,请使用func.exitValue()

the method execute() returns Process object instance that extended by groovy with additional methods 方法execute()返回通过Groovy使用其他方法扩展的Process对象实例

the [] brackets you have because in python you are accessing the sublist of arguments starting from first one: 您拥有[]括号,因为在python中,您要从第一个开始访问参数的子列表:

sys.argv[1:]

as soon as this accessor returns a list (even with only one element) - it wrapped with [] on output. 一旦此访问器返回一个列表(即使只有一个元素),它也会在输出中用[]包裹起来。

if you want to get just one element use 如果您只想使用一种元素

sys.argv[1]

You are expecting the value returned by the function main() to be passed to the OS as a return code. 您期望函数main()返回的值作为返回码传递到OS。

It doesn't. 没有。 You need to explicitly pass it to the OS. 您需要将其显式传递给操作系统。

rc = main(sys.argv[1:])
sys.exit(rc)

And you got ["arg"] because sys.argv[1:] asks for a slice (that is, a sublist) of sys.argv . 和你有["arg"]因为sys.argv[1:]要求一个切片(即子表)的sys.argv If you just want one element, use sys.argv[1] which selects element 1. 如果只需要一个元素,请使用sys.argv[1]选择元素1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM