Groovy 执行 shell & python 命令
要在上面提供的答案中添加一个更重要的信息,请考虑 stdout 和 stderr 用于执行它的 python cmd 或脚本。
Groovy 添加了execute 方法,使执行shell 变得相当容易,eg: python -c cmd:
groovy:000> "python -c print('hello_world')".execute()
===> java.lang.UNIXProcess@2f62ea70
但是,如果您希望将String 关联到 cmd 标准输出 (stdout) 和/或标准错误 (stderr),那么上面引用的代码没有结果输出。
因此,为了获得 Groovy 执行进程的 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)。
带有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()
}
输出
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