Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controlling stdout/stderr from Jython

I am calling a function in a java library from jython which prints to stdout. I would like to suppress this output from the jython script. I attempt the python idiom replacing sys.stdout with a file like object (StringIO), but this does not capture the output of the java library. I'm guessing sys.stdout does not affect the java program. Is there a standard convention for redirecting or suppressing this output programatically in jython? If not what ways can I accomplish this?

like image 984
Mark Roddy Avatar asked Feb 19 '11 01:02

Mark Roddy


1 Answers

You can use System.setOut, like this:

>>> 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

Note that this won't affect Python output, because Jython grabs System.out when it starts up so you can reassign sys.stdout as you'd expect.

like image 113
Nicholas Riley Avatar answered Oct 07 '22 05:10

Nicholas Riley