Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jimwhite
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimwhite/181225815c1c343b7987 to your computer and use it in GitHub Desktop.
Save jimwhite/181225815c1c343b7987 to your computer and use it in GitHub Desktop.
// Bind 'out' variable to redirect script printing methods.
out = new StringWriter()
// Child script inherits our bindings, including 'out'.
// def result = evaluate(new File('TargetScript.groovy'))
def result = evaluate '''
def a = 42
println "The answer is $a."
a ** 2
'''
def output = out.toString()
// Re-redirect 'out'.
// 'out = null' would also work in this case since System.out is the default.
out = System.out
println "Result: $result"
println "---"
print output
println "---"
// If you have many print calls and you're a speed freak then
// setting 'out' to a PrintWriter is a little faster:
// out = new PrintWriter(new StringWriter())
// Then because Groovy lets us be cavalier about member access
// we can get to the StringWriter without an extra variable:
// def output = out.out.toString()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment