Processes from Groovy

A string is a command, and execute() starts it. The result is a java.lang.Process with the streams and the exit status of the child, which is all a script needs to call a tool.

Run and read

echo.groovy

def process = 'echo hello'.execute() process.waitFor() println process.text.trim() println process.exitValue()

groovy echo.groovy

hello
0

waitFor() blocks until the command ends, and text reads the whole standard output. Read the stream before the process fills the pipe buffer: a command that writes more than a few kilobytes blocks until somebody reads it.

A command that fails

fail.groovy

def process = ['sh', '-c', 'echo bad input >&2; exit 3'].execute() println process.err.text.trim() println process.waitFor()

groovy fail.groovy

bad input
3

A list as the receiver runs the first word with the rest as arguments, with no shell parsing, which is what a file name with a space needs. err.text is the standard error, and the exit status is 3: a script decides from that number whether the command worked, not from the text it printed.

Both streams and a real tool

sort.groovy

def process = ['sh', '-c', 'printf "pear\\nfig\\napple\\n" | sort'].execute() def output = process.text def status = process.waitFor() println output.readLines() println status

groovy sort.groovy

[apple, fig, pear]
0

The shell builds the input and sorts it, and Groovy reads the result. This is the shape of every "call a tool and use its answer" script: run, read, check the status. A command with a lot of output on both streams needs two threads, one per stream, or the child blocks on the stream nobody reads.

Related

Автор статьи: Arthur Isaev