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.

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

    1. Tomas Lin Post author

      Because we call a Thread.join in the script, the processes are associated with the running script. So when you do Ctrl-C on the script, it will kill the spawned processes.

      Reply
  1. kvervaeke

    Any reason you didn’t use this?
    proc = “npm install”.execute([], new File(“${project.basedir}/../..”))
    proc.consumeProcessOutput(System.out, System.err)

    Reply

Leave a comment