Executing External Processes From Groovy – Improved

I’ve started using an exec method as shown below to run sub processes from groovy. If you run the standard exec like:

def torun = "ls -l "
proc = torun.execute()

This will hang on UNIX systems if these programs generate more STDOUT data than the buffer can handle. Better to handle this yourself with the following:

#!/usr/bin/env groovy

void execute(def command ) {

println "Running command : " + command
ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", command)
def process = pb.start()
def output = process.inputStream
output.each() { // Throw away stdout in this example, could return it at the end.
println "Done executing command , return value : " + process.exitValue()
process = null
pb = null


execute("ls -l /usr/bin ")

NOTE From: http://jira.codehaus.org/browse/GROOVY-2620

A Better solution is :

StringWriter stringWriterOutput = new StringWriter()
StringWriter stringWriterError = new StringWriter()
Process proc = command.execute()
stringWriterOutput << proc.in
stringWriterError << proc.err


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s