For Python:
1 2 3 4 5 6 7 8 9 10 11 | def capture(func, * args, * * kwargs): import sys, cStringIO tmpstdout = sys.stdout sys.stdout = cStringIO.StringIO() try : func( * args, * * kwargs) finally : value = sys.stdout.getvalue() sys.stdout = tmpstdout return value |
To use it:
1 2 3 4 | def sayHello(): print "Hello World" value = capture(sayHello) print value.upper() |
The output is:
HELLO WORLD
For Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | package myproject; import java.io.ByteArrayOutputStream; import java.io.PrintStream; public abstract class StdoutCaptor { public String capture() { PrintStream tmp = System.out; ByteArrayOutputStream baos = new ByteArrayOutputStream(); System.setOut( new PrintStream(baos)); try { invoke(); } finally { System.setOut(tmp); } return new String(baos.toByteArray()); } public abstract void invoke(); } |
To use it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | package myproject; public class Main { public static void sayHello() { System.out.println( "Hello World!" ); } public static void main(String[] args) { String value = new StdoutCaptor() { @Override public void invoke() { sayHello(); } }.capture(); System.out.println(value.toUpperCase()); } } |
The output is:
HELLO WORLD
Unlike Python, Java doesn't allow a function/method to be passed around. Hence, the code is more verbose than Python.