python Jython contextmanager提供redirect_stdout

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Jython contextmanager提供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)

以上是关于python Jython contextmanager提供redirect_stdout的主要内容,如果未能解决你的问题,请参考以下文章

python (jython) 归档库

如何将 python 模块添加到 jython/lib?

使用 jython 运行 python

python JButton Jython示例!!!!

python Jython classPathHacker加载JDBC

Cpython和Jython的对比介绍