【发布时间】:2011-11-08 11:44:21
【问题描述】:
我正在使用 Groovy 在我的 Linux 机器上执行命令并取回输出,但我无法以某种方式使用 | 管道(我认为)或者它可能没有等待命令完成。
我的代码有什么问题或遗漏了什么?
我的调用函数:
def test()
{
String result="N"
HashMap<String,String> params = IntermediateResults.get("userparams")
Map env=AppContext.get(AppCtxProperties.environmentVariables)
def fClass = new GroovyClassLoader().parseClass( new File( 'plugins/infa9/Infa9CommandExecUtil.groovy' ) )
List<String> frows=["uname -a",
"uname -a | awk '{print\$2}'",
"uname -a | cut -d ' ' -f 2"]
List<String> resultRows = fClass.newInstance().fetchCommandOutput( params, env, frows )
return result
}
Infa9CommandExecUtil.groovy文件内容(更新:添加exitVal println):
package infa9
import java.io.BufferedReader;
public class Infa9CommandExecUtil {
StringBuffer result
public Infa9CommandExecUtil() {
result = new StringBuffer()
}
public List<String> fetchCommandOutput( Map<String,String> params, Map env, List<String> rows )
{
List<String> outputRows = new ArrayList<String>()
try
{
for(item in rows)
{
String temp=item.toString()
println "CMD:$temp"
Process proc = Runtime.getRuntime().exec(temp);
InputStream stdin = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String line = null;
result = new StringBuffer()
line=null
int exitVal = proc.waitFor() //do I need to wait for the thread/process to finish here?
while ((line = br.readLine()) != null)
{
result.append(line+System.getProperty("line.separator")) //to maintain the format (newlines)
}
String tRes=result
tRes=tRes.trim()
println "OUTPUT:$tRes\nEXITVAL:$exitVal"
outputRows.add(tRes)
}
}
catch (IOException io) { io.printStackTrace();}
catch (InterruptedException ie) {ie.printStackTrace();}
return outputRows
}
}
我的输出(更新:添加了 exitVal 值):
CMD:uname -a
OUTPUT:Linux estilo 2.6.18-128.el5 #1 SMP Wed Dec 17 11:41:38 EST 2008 x86_64 x86_64 x86_64 GNU/Linux
EXITVAL:0
CMD:uname -a | awk '{print$2}'
OUTPUT:
EXITVAL:1
CMD:uname -a | cut -d ' ' -f 2
OUTPUT:
EXITVAL:1
注意:我在内部使用sh -c <command>。
【问题讨论】:
-
那么,您仍然没有以 Groovy 的方式进行操作(我已经向您展示了好几次)?
-
@tim:我落后了,我以为我会先满足要求,然后重构代码。对不起:)
-
我也会读取错误流或使用 ProcessBuilder 将错误定向到输出。我会将输出复制到 ByteArrayOutputStream 并将其转换为字符串。
-
@Peter Lawrey:你能举个例子吗,这将是一个很大的帮助。谢谢
-
我认为您不应该从 Java 调用非 Java 程序。否则,何必一开始就用 Java 编写代码呢?