如何在Jenkins从机的脚本控制台中使用Groovy运行Python命令?

4

我需要在Jenkins的一个从节点的脚本控制台上运行像python -c "print('hello')"这样简单的任意命令。以下是我的尝试:

def cmd = 'python -c "print(\'hello\')"'
def sout = new StringBuffer(), serr = new StringBuffer()
def proc = cmd.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout\nerr> $serr"

然而,得到了空输出:
out> 
err> 

有没有办法在Groovy中获取Python的输出?
3个回答

7
尝试将命令分成数组。
def cmdArray = ["python", "-c", "print('hello')"]
def cmd = cmdArray.execute()
cmd.waitForOrKill(1000)
println cmd.text

不确定为什么你的版本无法工作。


我怀疑Python会创建子进程来运行代码,而这个子进程无法被Groovy跟踪...但这只是我的猜测。虽然不确定如何检查它。 - peetonn

4
这对我来说非常完美:
def cmd = 'python -c "print(\'hello\')"'
def proc = cmd.execute()
proc.waitFor()
println "return code: ${ proc.exitValue()}"
println "stderr: ${proc.err.text}"
println "stdout: ${proc.in.text}"

请使用“执行 Groovy 脚本”(而不是“执行系统 Groovy 脚本”)功能。

这给我:out> err> 返回代码:0 标准错误输出: 标准输出: - peetonn
你是在使用Execute SYSTEM Groovy脚本而不是Execute Groovy脚本吗?(我编辑了我的回答) - jussuper

1

使用Groovy执行shell和python命令

除了上面提供的答案外,还需要考虑正在执行的python命令或脚本的stdoutstderr这一重要信息。

Groovy添加了execute方法,使得执行shell变得相当容易,例如:python -c cmd:

groovy:000> "python -c print('hello_world')".execute()
===> java.lang.UNIXProcess@2f62ea70

但是,如果您想获取与命令 标准输出 (stdout) 和/或 标准错误 (stderr) 相关联的 String,则上述引用代码没有任何结果输出

因此,为了始终获得 Groovy exec 进程的 cmd 输出,请尝试使用以下方式:

String bashCmd = "python -c print('hello_world')"
def proc = bashCmd.execute()
def cmdOtputStream = new StringBuffer()
proc.waitForProcessOutput(cmdOtputStream, System.err)
print cmdOtputStream.toString()

rather than

def cmdOtputStream = proc.in.text
print cmdOtputStream.toString()

由于Groovy是一个阻塞调用(点击查看原因),我们在执行命令后捕获其输出。

executeBashCommand函数完整示例

String bashCmd1 = "python -c print('hello_world')"
println "bashCmd1: ${bashCmd1}"
String bashCmdStdOut = executeBashCommand(bashCmd1)
print "[DEBUG] cmd output: ${bashCmdStdOut}\n"


String bashCmd2 = "sh aws_route53_tests_int.sh"
println "bashCmd2: ${bashCmd2}"
bashCmdStdOut = executeBashCommand(bashCmd2)
print "[DEBUG] cmd output: ${bashCmdStdOut}\n"

def static executeBashCommand(shCmd){
    def proc = shCmd.execute()
    def outputStream = new StringBuffer()
    proc.waitForProcessOutput(outputStream, System.err)
    return outputStream.toString().trim()
}

输出

bashCmd1: python -c print('hello_world')
[DEBUG] cmd output: hello_world
bashCmd2: sh aws_route53_tests_int.sh
[DEBUG] cmd output: hello world script

注意1:如上代码所示(bashCmd2),对于更复杂的Python脚本,您应该通过一个.sh bash shell脚本来执行它。

注意2:所有示例均在下列环境中测试通过:

$ groovy -v
Groovy Version: 2.4.11 JVM: 1.8.0_191 Vendor: Oracle Corporation OS: Linux

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接