seansummers
9/28/2015 - 8:31 PM

Jython contextmanager to provide redirect_stdout

Jython contextmanager to provide redirect_stdout

'''Wouldn't it be nice if sys.stdout knew how to redirect the JVM's stdout? Shooting star.
        Author: Sean Summers <seansummers@gmail.com> 2015-09-28 v0.1
        Permalink: https://gist.githubusercontent.com/seansummers/bbfe021e83935b3db01d/raw/redirect_java_stdout.py
'''

from java import io, lang

from contextlib import contextmanager

@contextmanager
def redirect_stdout(new_target):
        ''' Context manager for temporarily redirecting sys.stdout to another file or file-like object
                see contextlib.redirect_stdout documentation for usage
        '''

        # file objects aren't java.io.File objects...
        if isinstance(new_target, file):
                new_target.close()
                new_target = io.PrintStream(new_target.name)
        old_target, target = lang.System.out, new_target
        try:
                lang.System.setOut(target)
                yield None
        finally:
                lang.System.setOut(old_target)