How To Run Python Commands Using Groovy In Jenkins Slaves' Script Console?
Solution 1:
Try to divide command into array
defcmdArray= ["python", "-c", "print('hello')"]
defcmd= cmdArray.execute()
cmd.waitForOrKill(1000)
println cmd.text
Not sure why your version does not work.
Solution 2:
this works perfect for me:
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}"
use "Execute Groovy script" (not "Execute system groovy script")
Solution 3:
Groovy executing shell & python commands
To add one more important information to above provided answers is to consider the stdout
and stderr
for the python cmd or script that its being executed.
Groovy adds the execute
method to make executing shells fairly easy, eg:python -c
cmd:
groovy:000> "python -c print('hello_world')".execute()
===> java.lang.UNIXProcess@2f62ea70
But if you like to get the String
associated to the cmd standard output (stdout
) and/or an standard error (stderr
), then there is no resulting output with the above cited code.
So in order to get the cmd output for a Groovy exec process always try to use:
StringbashCmd="python -c print('hello_world')"defproc= bashCmd.execute()
defcmdOtputStream=newStringBuffer()
proc.waitForProcessOutput(cmdOtputStream, System.err)
print cmdOtputStream.toString()
rather than
defcmdOtputStream = proc.in.text
print cmdOtputStream.toString()
In this way we capture the outputs after executing commands in Groovy as the latter is a blocking call (check ref for reason).
Complete Example w/ executeBashCommand
func
StringbashCmd1="python -c print('hello_world')"
println "bashCmd1: ${bashCmd1}"StringbashCmdStdOut= executeBashCommand(bashCmd1)
print "[DEBUG] cmd output: ${bashCmdStdOut}\n"StringbashCmd2="sh aws_route53_tests_int.sh"
println "bashCmd2: ${bashCmd2}"
bashCmdStdOut = executeBashCommand(bashCmd2)
print "[DEBUG] cmd output: ${bashCmdStdOut}\n"
def staticexecuteBashCommand(shCmd){
defproc= shCmd.execute()
defoutputStream=newStringBuffer()
proc.waitForProcessOutput(outputStream, System.err)
return outputStream.toString().trim()
}
Output
bashCmd1: python -c print('hello_world')
[DEBUG] cmd output: hello_world
bashCmd2: sh aws_route53_tests_int.sh
[DEBUG] cmd output: hello world script
NOTE1: As shown in the above code (bashCmd2
) example for a more complex python scripts you should execute it through a .sh
bash shell script.
NOTE2: All examples have been tested under
$ groovy -v
Groovy Version:2.4.11JVM:1.8.0_191 Vendor: Oracle Corporation OS: Linux
Post a Comment for "How To Run Python Commands Using Groovy In Jenkins Slaves' Script Console?"