Monthly Archives: November 2011

Replacing the Groovy execute() method with one that prints output while the process is running

We are writing a small script to help us run our grails functional tests in parallel.

One of the issues we are running into with Groovy’s execute() method and its online examples is that the output from the process is not available until the process is finished.

When running Grails functional tests, we want to see the results right away in the console to debug things that are going wrong.

The solution we found was to use the Java ProcessBuilder task instead.

So instead of

myCommand.execute()

in Groovy, use the following wall of code:


ProcessBuilder builder = new ProcessBuilder( myCommand.split(' ') )

builder.redirectErrorStream(true)

Process process = builder.start()

InputStream stdout = process.getInputStream ()
BufferedReader reader = new BufferedReader (new InputStreamReader(stdout))

while ((line = reader.readLine ()) != null) {
   System.out.println ("Stdout: " + line)
}

You could probably change this so that it replaces the groovy metaclass methods, but it’s a start.