Hi Anadi,

The output for any script can be set through the 'out' property in the
binding:

var script = File.createTempFile('myScript', '.groovy').tap {
    write '''
        out.println 'hi'
        println 6 * 7
        printf '%x%n', 6 * 7
        out << 'bye'
    '''
    deleteOnExit()
}
var sw = new StringWriter()
var binding = new Binding(out: sw)
String[] roots = [script.parentFile.absolutePath]
var engine = new GroovyScriptEngine(roots)
engine.run(script.name, binding)
assert sw.toString().readLines() == ['hi', '42', '2a', 'bye']

Cheers, Paul.


On Tue, Feb 13, 2024 at 5:38 PM Anadi Kashyap <anadi.kash...@314ecorp.com>
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.
>
> Best regards,
>
> --
> * Anadi Kashyap *
> * Software Engineer *
> ------------------------------
> [image: 314e Corporation] <https://www.314e.com/>
> * E: * anadi.kash...@314ecorp.com
> * T: * +1.510.371.6736
> * M: * +91.891.016.1263
> Connect with me on LinkedIn <https://www.linkedin.com/in/anadi-kashyap/>
> [image: Book a meeting with 314e in ViVE and HIMSS 2024]
>

Reply via email to