Groovy 执行 shell 命令 [英] Groovy executing shell commands

查看:66
本文介绍了Groovy 执行 shell 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Groovy 在 String 中添加了 execute 方法,使 shell 的执行变得相当容易;

Groovy adds the execute method to String to make executing shells fairly easy;

println "ls".execute().text

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

but if an error happens, then there is no resulting output. Is there an easy way to get both the standard error and standard out? (other than creating a bunch of code to; create two threads to read both inputstreams, then using a parent stream to wait for them to complete then convert the strings back to text?)

如果有这样的东西就好了;

It would be nice to have something like;

 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"

显示:

<代码>输出>错误>ls: 无法访问/badDir: 没有那个文件或目录

这篇关于Groovy 执行 shell 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆