Last active
August 29, 2015 14:05
-
-
Save jimwhite/181225815c1c343b7987 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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