Last active
March 23, 2016 11:14
-
-
Save seansummers/bbfe021e83935b3db01d to your computer and use it in GitHub Desktop.
Jython contextmanager to provide redirect_stdout
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
'''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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment