本文介绍了在groovy脚本中执行外部程序并捕获输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要编写一个groovy脚本,该脚本正在执行一个外部程序并将该程序的输出打印到控制台.
I need to write a groovy script, that is executing a external program and print the output of that program to the console.
以下是有关代码段:
def pmdCommand = "${scriptDir}/run.sh pmd -d ${filesToAnalyse}"
def sout = new StringBuffer()
def serr = new StringBuffer()
def process = pmdCommand.execute()
process.consumeProcessOutput(sout, serr)
process.waitFor()
if (process.exitValue() !=0 ) {
System.err << serr.toString()
System.exit(-1)
}
else {
System.out << sout.toString()
System.exit(0)
}
我在Java中做了类似的事情,但是我无法将其翻译为groovy.
I did something similar in Java, but I can't translate it to groovy.
StringBuffer output = new StringBuffer();
String s = null;
try {
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
while ((s = stdError.readLine()) != null) {
System.err.println(s);
}
System.exit(0);
}
catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
更新:我似乎waitFor()永远不会返回并阻止执行
Update: I seems the waitFor() never returns and blocks the execution
伊曼纽尔·罗莎(Emmanuel Rosa)提供的解决方案:
def pmdCommand = "/usr/src/app/lib/pmd/bin/run.sh pmd -d ${filesToAnalyse} -f codeclimate -R ${ruleset} -l apex -v 35"
def sout = new StringBuffer()
def serr = new StringBuffer()
def process = pmdCommand.execute()
process.consumeProcessOutput(sout, serr)
process.waitForProcessOutput()
System.out << sout.toString()
System.exit(0)
推荐答案
文档指出consumeProcessOutput()
...
到目前为止,一切都很好.这是重要的部分...
So far so good. Here's the important part...
解决方案...
所以您可以做的是将process.waitFor()
替换为process.waitForProcessOutput()
.
So what you can do is replace process.waitFor()
with process.waitForProcessOutput()
.
这篇关于在groovy脚本中执行外部程序并捕获输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!