Groovy执行Shell命令
时间:2020-03-06 14:59:32 来源:igfitidea点击:
Groovy在String中添加了execute方法,使执行shell变得相当容易。
println "ls".execute().text
但是如果发生错误,则没有结果输出。有一种简单的方法可以同时消除标准误差和标准误差吗? (除了创建一堆代码;创建两个线程来读取两个输入流,然后使用父流等待它们完成,然后将字符串转换回文本?)
有这样的事情会很好;
def x = shellDo("ls /tmp/NoFile") println "out: ${x.out} err:${x.err}"
解决方案
" ls" .execute()
返回一个Process
对象,这就是为什么"" ls" .execute()。text`有效的原因。我们应该能够只读取错误流,以确定是否存在任何错误。
在Process上还有一个额外的方法,它允许我们传递一个StringBuffer来检索文本:consumeProcessErrorStream(StringBuffer error)。
例子:
def proc = "ls".execute() def b = new StringBuffer() proc.consumeProcessErrorStream(b) println proc.text println b.toString()
好吧,我自己解决了;
def sout = new StringBuilder(), serr = new StringBuilder() def proc = 'ls /badDir'.execute() proc.consumeProcessOutput(sout, serr) proc.waitForOrKill(1000) println "out> $sout err> $serr"
显示:
out> err> ls:无法访问/ badDir:没有这样的文件或者目录