+ protected static final String PYTHON_SCL_WRITER = "python.scl.writer";
+ //TODO Replace with a count of open contexts and call Py_Finalize when the last one closes.
+ private static Boolean isPyInitialized = false;
+
+ // A writer that is called by the sys.stdout and sys.stderr streams in Python
+ private static final Writer pythonWriter = new Writer() {
+ Writer defaultWriter = new OutputStreamWriter(System.out);
+
+ @Override
+ public void close() throws IOException {
+ throw new IllegalStateException("This writer should never be closed!");
+ }
+
+ @Override
+ public void flush() throws IOException {
+ Writer writer = getPythonWriter();
+ synchronized (writer) {
+ writer.flush();
+ }
+ }
+
+ @Override
+ public void write(char[] cbuf, int off, int len) throws IOException {
+ Writer writer = getPythonWriter();
+ synchronized (writer) {
+ writer.write(cbuf, off, len);
+ }
+ }
+
+ // Get a thread-specific Writer instance
+ private Writer getPythonWriter() {
+ SCLContext sclContext = SCLContext.getCurrent();
+ Writer writer = (Writer) sclContext.get(PYTHON_SCL_WRITER);
+ return writer != null ? writer : defaultWriter;
+ }
+ };