Run script in Groovy Console

The usual method of running a non-gui Groovy script is with the groovy JVM runner. This is done using a script file such as groovy.bat in Windows. Another option is to use the Groovy interactive Console which is a Gui for editing and running Groovy scripts.

Sample groovy script

println 'Hello world!'

Run via the command line invocation or double click on file explorer:

C:\temp>groovy Hello.groovy
Hello world!

Run using the Groovy console:

C:\temp>groovyconsole Hello.groovy

This results in the Console as shown below after the script is then executed withing the console.

It is also possible to programmatically execute the script in the Groovy Console directly by using the Console class.

import groovy.transform.TypeChecked
import groovy.ui.Console

class ConsoleRunner {	
	 * Do the 'Hello world!' as an example.
	static void main(args) {		
		Console console = new Console();;
		def script = "println 'Hello world!'"		
		File file = File.createTempFile("hello",null)

How this works
Here I sneak in the script text using a temporary file; did not find a direct way of doing it. Then I invoke the loaded script. This results in the same Groovy Console image as shown above.

Of course, if you already have a Groovy script stored in a file, it is even easier, skip the temp file creation.

I’m sure there is some way to bootstrap a Groovy script to use the Console for its runtime or a way of subclassing or extending the Console itself to serve as a generic runner.

Does this have any practical use? Maybe.

Further Reading

  1. Groovy Console
  2. Running
  3. Console.groovy
  4. Embedding a Groovy Console in a Java Server Application

Leave a Reply

Your email address will not be published. Required fields are marked *