你怎么做一个时髦的T恤?

时间:2012-05-14 08:13:19

标签: groovy

我喜欢执行命令并将其stdout和stderr复制到日志文件中。

我喜欢跑:

p = myexecute("ls -l /tmp/")

并且基本上将相同的Process对象返回为:

p = "ls -l /tmp/".execute()

区别在于stdout / stderr被复制到所述日志文件中。我确信在groovy中有一种简单的方法可以做到这一点,但我还没有足够的时间去看它。

3 个答案:

答案 0 :(得分:2)

这个答案早就应该了,但一个解决方案可能是:

import groovy.ui.SystemOutputInterceptor

File logFile = new File('stdout.log')                                                                                
new SystemOutputInterceptor({logFile << it; true}).start() 
...

答案 1 :(得分:1)

更好的解决方案可能是:

def logFile = new File( '/tmp/log.txt' )
logFile.withWriter('UTF-8') { sout ->
    p = "ls -l /tmp/".execute()
    p.waitForProcessOutput(sout, sout)
}

因为这将等待过程完成

答案 2 :(得分:0)

你是对的,很简单:

logFile.withWriter('UTF-8') { sout ->
    p = "ls -l /tmp/".execute()
    p.consumeProcessOutput(sout, sout)
}

这会将两个流写入同一个文件。

有关更多示例,请参阅http://groovy.codehaus.org/Process+Management