Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to stream the output of a long Groovy execute() command to the console rather than wait for it to finish?

I'm running a shell command via a system Groovy script. It's a long running process, about 30 minutes, and it is quite verbose. But as written, this waits for the command to complete before printing stdout or stderr. Is there a way to have the output go to the console as the script executes (like it would in a terminal session).

def sout = new StringBuffer(), serr = new StringBuffer()
def proc = "/some/long/running/command".execute()

proc.consumeProcessOutput(sout, serr)
println "STDOUT\n $sout"
println "STDERR\n $serr"

Update: This is the code I'm trying based on the answer. It doesn't print anything until after the process completes, or is killed.

def cmd = "/home/adam/test.sh"
StringBuffer sout = new StringBuffer()
StringBuffer serr = new StringBuffer()
def process = cmd.execute()
process.waitForProcessOutput sout, serr
sout.each 
   println "Line ${it}"
}
like image 452
Adam vonNieda Avatar asked Sep 19 '25 04:09

Adam vonNieda


1 Answers

While the solution you found will probably work fine, I think it is better to use waitForProcessOutput which also allows to stream the error output of the process.

The full solution would be something like this:

#!/usr/bin/env groovy
Process proc = "ping -c 10 google.com".execute()
proc.waitForProcessOutput(System.out, System.err)
System.exit(proc.exitValue())

There are several alternatives to this method to capture only normal output or only error output for example. You can find them here.

There is also a (rather short) chapter on executing external processes on the Groovy docs.

like image 175
Michael Avatar answered Sep 21 '25 01:09

Michael