Groovy执行Shell命令

鲍勃·赫尔曼

Groovy添加了该execute方法,String以使执行Shell变得相当容易。

println "ls".execute().text

但是如果发生错误,则没有结果输出。是否有一种简单的方法可以同时消除标准错误和标准?(除了创建一堆代码;创建两个线程来读取两个输入流,然后使用父流等待它们完成,然后将字符串转换回文本?)

有这样的事情会很好;

 def x = shellDo("ls /tmp/NoFile")
 println "out: ${x.out} err:${x.err}"
鲍勃·赫尔曼

好吧,我自己解决了;

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: cannot access /badDir: No such file or directory

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章