Executing External Processes

Groovy provides a simple way to execute command line processes. Simply write the command line as a string and call the execute() method. E.g., on a *nix machine (or a windows machine with appropriate *nix commands installed), you can execute this:

def process = "ls -l".execute()
println "Found text ${process.text}"

The execute() method returns a java.lang.Process instance which will subsequently allow the in/out/err streams to be processed and the exit value from the process to be inspected etc.

e.g. here is the same command as above but we will now process the resulting stream a line at a time

def process = "ls -l".execute()
process.in.eachLine { line -> println line }

in Groovy 1.5.5 the eachLine method is not available on InputStream. Earlier or later version will have that method. As an alternative you can use process.in.newReader().eachLine { line -> println line }

Remember that many commands are shell built-ins and need special handling. So if you want a listing of files in a directory on a windows machine and if you write

Process p = "dir".execute()
println "${p.text}"

you will get IOException saying  "Cannot run program "dir": CreateProcess error=2, The system cannot find the file specified."

This is because "dir" is built-in to the windows shell (cmd.exe) and can't be run as a simple executable. Instead, you will need to write:

Process p = "cmd /c dir".execute()
println "${p.text}"

Also, because this functionality currently make use of java.lang.Process under the covers, the deficiencies of that class must currently be taken into consideration. In particular, the javadoc for this class says:

Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock

Because of this, Groovy provides some additional helper methods which make stream handling for processes easier.

Here is how to gobble all of the output (including the error stream output) from your process:

def p = "rm -rf */*.tmp".execute()

There are also variations of consumeProcessOutput including one which takes output and error StringBuffers, another which takes output and error ditto for InputStreams and variations for StringBuffers, Writers and InputStreams which handle just the output stream or error stream individually. In addition, there is a pipeTo command (mapped to '|' to allow overloading) which lets the output stream of one process be fed into the input stream of another process.

Here are some examples of use:

proc1 = 'ls'.execute()
proc2 = 'tr -d o'.execute()
proc3 = 'tr -d e'.execute()
proc4 = 'tr -d i'.execute()
proc1 | proc2 | proc3 | proc4
if (proc4.exitValue())
    print proc4.err.text
    print proc4.text
def sout = new StringBuffer()
def serr = new StringBuffer()
proc2 = 'tr -d o'.execute()
proc3 = 'tr -d e'.execute()
proc4 = 'tr -d i'.execute()
proc4.consumeProcessOutput(sout, serr)
proc2 | proc3 | proc4
[proc2, proc3].each{ it.consumeProcessErrorStream(serr) }
proc2.withWriter { writer ->
    writer << 'testfile.groovy'
println 'sout: ' + sout
println 'serr: ' + serr
def sout = new StringBuffer()
def serr = new StringBuffer()
proc1 = 'gzip -c'.execute()
proc2 = 'gunzip -c'.execute()
proc2.consumeProcessOutput(sout, serr)
proc1 | proc2
proc1.withWriter { writer ->
    writer << 'test text'
println 'sout: ' + sout // => test text
println 'serr: ' + serr
def initialSize = 4096
def outStream = new ByteArrayOutputStream(initialSize)
def errStream = new ByteArrayOutputStream(initialSize)
def proc = "ls.exe".execute()
proc.consumeProcessOutput(outStream, errStream)
println 'out:\n' + outStream
println 'err:\n' + errStream
def out = new StringBuilder()
def err = new StringBuilder()
def proc = "ls".execute()
proc.waitForProcessOutput(out, err)
if (out) println "out:\n$out"
if (err) println "err:\n$err"

Further Information

See also: