如何在Jenkins slaves的脚本控制台中使用groovy运行python命令?

2024-09-28 22:31:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在一个Jenkins'slaves'脚本控制台上运行一些任意的东西,比如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的输出?


Tags: 脚本cmdhellonewexecutedefprocout
3条回答

这对我来说是完美的:

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}"

使用“Execute Groovy script”(而不是“Execute system Groovy script”)

Groovy执行shell&python命令

要在上述答案中添加一个更重要的信息,请考虑正在执行的python命令或脚本的stdoutstderr

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

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

但是,如果您希望获得与cmd标准输出相关的Stringstdout)和/或标准错误(stderr),则上述代码不会产生结果输出。

因此,为了获得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()

而不是

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

通过这种方式,我们在Groovy中执行命令后捕获输出,因为后者是一个阻塞调用(check ref for reason)。

完整示例w/executeBashCommandfunc

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脚本,您应该通过.shbash shell脚本执行它。

注2:所有示例都在

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

尝试将命令分成数组

def cmdArray = ["python", "-c", "print('hello')"]
def cmd = cmdArray.execute()
cmd.waitForOrKill(1000)
println cmd.text

不知道为什么你的版本不起作用。

相关问题 更多 >