2011-02-19 94 views
7

我打電話給標準輸出從jython調用java庫中的函數。我想從jython腳本中取消這個輸出。我嘗試用像對象(StringIO)這樣的文件替換sys.stdout的python習語,但是這並不捕獲java庫的輸出。我猜sys.stdout不會影響Java程序。有沒有一個標準的慣例重定向或壓制這種輸出在jython編程方式?如果我不能通過什麼方式來實現這一點?從Jython控制標準輸出/標準錯誤

回答

9

您可以使用System.setOut,像這樣:

>>> from java.lang import System 
>>> from java.io import PrintStream, OutputStream 
>>> oldOut = System.out 
>>> class NoOutputStream(OutputStream):   
...  def write(self, b, off, len): pass  
... 
>>> System.setOut(PrintStream(NoOutputStream())) 
>>> System.out.println('foo')     
>>> System.setOut(oldOut) 
>>> System.out.println('foo')     
foo 

請注意,這不會影響Python的輸出,因爲Jython中抓住System.out啓動時這樣你就可以重新分配sys.stdout如你所期望。

1

我創建了一個上下文管理器模仿(Python3的)contextlib的redirect_stdout (gist here)

'''Wouldn't it be nice if sys.stdout knew how to redirect the JVM's stdout? Shooting star. 
     Author: Sean Summers <[email protected]> 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) 
相關問題