In Python I can execute arbitrary code using exec(string). How can I do this in Groovy? I'd like the code to execute in the context of my currently running application, not as if I were using the Groovy shell.
+3
A:
To execute a command-line program dynamically in Groovy:
"cmdstring".execute().text
You can also execute some Groovy code wrapped in a String with:
def myGroovyCode = 'println "hi"'
Eval.me(myGroovyCode) //prints hi
Eric Wendelin
2009-08-18 18:25:40
This doesn't appear to work, I want to execute actual code, not a command line program.
Jared
2009-08-20 22:20:39
Sorry I must have been on crack or something. You now have a real answer :)
Eric Wendelin
2009-08-20 23:17:26
A:
You can also pass in your current context parameters via the binding mechanism to the Groovy Shell.
def myname = 'Inigo Montoya'
def binding = new Binding( [ myname:myname ] )
new GroovyShell( binding ).evaluate( 'println "My Name is " + myname' )
tomas
2009-08-22 11:49:51