Executing External Processes
Groovy provides a simple way to execute command line processes. Simply write the command line as a string and call the
exectue() method. E.g., on a *nix machine (or a windows machine with appropriate *nix commands installed), you can execute this:
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
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
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:
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:
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, these 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: