Last Updated: November 15, 2016
· tessthyer

Calling Other Processes From Groovy

Calling Other Processes from Groovy

There are lots of scenarios where calling another process from Groovy is helpful. For example, you may want to use a common system utility that does what you want more easily than you could in your Groovy code. Or perhaps you need to call an existing, sophisticated program written in another language that will handle some functionality more efficiently. Or you're under deadline pressure and just don't have time to rewrite that old Perl script. The following is an introduction to calling external processes from Groovy.

A simple example frequently given to demonstrate calling another process from Groovy uses the ls utility.

"ls -l".execute()

To see the results, print the text of the process's output stream.

println "ls -l".execute().text

This returns a directory listing on a Unix or Unix-like operating system.

One Step Further: Run a Custom Script

What if you need to run a custom script? Groovy must be told where to find it. This can be achieved in two ways.

Option 1: Use the absolute path to your script

For this example, suppose you placed a perl script in the foo folder of your home directory. Use the complete absolute path to construct a command string.

def scriptPath = "/Users/me/foo/"
def command = "perl -w $scriptPath"
println command.execute().text

Option 2: Further Control of the Context

Another signature of the execute method allows passing an array of environment parameters and the parent directory of the command.

def parentDir = "/Users/me/foo"
def command = "perl -w"
def env = [] // in this case, environment is empty

println command.execute( env, dir ).text

You can build a custom environment, adding one property at a time. Or, pass all the system-wide environment variables, as follows. I had a need to do this when the code calling the perl script was a java executable rather than a groovy script running in my terminal.

def env = System.getenv().collect { k, v -> "$k=$v" }

Consuming Process Output

There are better ways to handle output than the first example given above. What the execute() method actually returns is a Process object. The GDK provides a handy consumeProcessOutput() method. Here's an example:

Process process = command.execute()
def out = new StringBuffer()
def err = new StringBuffer()
process.consumeProcessOutput( out, err )
if( out.size() > 0 ) println out
if( err.size() > 0 ) println err

More About External Processes in Groovy

This article did not attempt to cover all the other ways of calling processes from Groovy. Some of these are:

My groovy processes example scripts are available on Github.

1 Response
Add your response

I am new to groovy. none of the example works in my groovyconsole. do i need to import anything?

over 1 year ago ·