<h3>Groovy执行shell&python命令</h3>
<p>要在上述答案中添加一个更重要的信息,请考虑正在执行的<strong>python</strong>命令或脚本的<code>stdout</code>和<code>stderr</code>。</p>
<p><strong>Groovy</strong>添加了<code>execute</code>方法,使执行shell相当容易,<strong>例如:</strong><code>python -c</code>命令:</p>
<pre><code>groovy:000> "python -c print('hello_world')".execute()
===> java.lang.UNIXProcess@2f62ea70
</code></pre>
<p>但是,如果您希望获得与cmd标准输出相关的<code>String</code>(<code>stdout</code>)和/或标准错误</strong>(<code>stderr</code>),则上述代码不会产生结果输出</strong>。</p>
<p>因此,为了获得Groovy exec进程的<strong>cmd输出,请始终尝试使用:</p>
<pre><code>String bashCmd = "python -c print('hello_world')"
def proc = bashCmd.execute()
def cmdOtputStream = new StringBuffer()
proc.waitForProcessOutput(cmdOtputStream, System.err)
print cmdOtputStream.toString()
</code></pre>
<p>而不是</p>
<pre><code>def cmdOtputStream = proc.in.text
print cmdOtputStream.toString()
</code></pre>
<p>通过这种方式,我们在Groovy中执行命令后捕获输出,因为后者是一个阻塞调用(<a href="https://stackoverflow.com/questions/25300550/difference-in-collecting-output-of-executing-external-command-in-groovy">check ref for reason</a>)。</p>
<h3>完整示例w/<code>executeBashCommand</code>func</h3>
<pre><code>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()
}
</code></pre>
<p><strong>输出</strong></p>
<pre><code>bashCmd1: python -c print('hello_world')
[DEBUG] cmd output: hello_world
bashCmd2: sh aws_route53_tests_int.sh
[DEBUG] cmd output: hello world script
</code></pre>
<p><strong>注意1:</strong>如上面的代码(<code>bashCmd2</code>)示例所示,对于更复杂的python脚本,您应该通过<code>.sh</code>bash shell脚本执行它。</p>
<p><strong>注2:</strong>所有示例都在</p>
<pre><code>$ groovy -v
Groovy Version: 2.4.11 JVM: 1.8.0_191 Vendor: Oracle Corporation OS: Linux
</code></pre>