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:
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()
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
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()
}
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.11 JVM: 1.8.0_191 Vendor: Oracle Corporation OS: Linux