On 13.02.24 08:38, Anadi Kashyap wrote:
Hello Groovy Developers and Community,

Perhaps my last question was missed so I'm asking it again, would
appreciate some direction here -

I am currently working with groovy.util.GroovyScriptEngine and I have
encountered a specific requirement where I need to redirect the output
of the script engine to a custom Writer, separate from the default
stdout/stderr, without affecting the rest of the JVM. This functionality
is somewhat similar to what javax.script.ScriptContext offers with
methods to set a custom writer.I am aware of
org.codehaus.groovy.jsr223.GroovyScriptEngineImpl, but it seems limited
for my use case. I am looking for a way to achieve this with
groovy.util.GroovyScriptEngine.Could you please guide me on how to
redirect the output effectively? Is there an existing feature in Groovy
that I might have missed, or would this be a case for a feature
request?Any guidance or suggestions would be greatly appreciated.Thank
you for your time and assistance.

ok... first there is GroovyScriptEngine (GSE) and the code it does
generate and execute. GSE itself is more a class management engine that
(re)compiles on demand). I think you want the output of those scripts
GSE is executing. GSE does not directly offer this. In Groovy a script
has a print, println and printf methods, that can depend on an optional
out property, which can hold any redirection you may want. But that does
not include error, direct usages of System.out or code called by the
script, nor explicit classes in the script. So this is very limited.

example:

Binding binding = new Binding(out: System.err)
groovyScriptEngine.run("""
println "Hello World from script"
class X {
  void foo() {
   println "Hello World from class"
  }
}
new X().foo()
out = System.out
println "Hello World from script Number 2"
""", binding)


Executing that kind of code would create a script and a class X. The
first println will write "Hello World from script" to System.err because
we set the out property for the class (in the binding) accordingly. Next
the code cause "Hello World from class" to System.out, since the println
in the class does not know about the out-property of the script. The
script and the class are only loosely related. Next we redefine out in
the binding (can be prevented with a custom Binding) and "Hello World
from script Number 2" will be written to System.out again.

bye Jochen

Reply via email to