Search code examples
javapythonjython

Jython printing all terminal output / assign output as string


Iv been looking into embedding jython into my java program to allow users to script in python. However i want to print the output of their python scripts into a java text box in my program. But i cannot find a way to embed the output of the jython engine:

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

    public class Main {
      public static void main(String[] args) throws ScriptException {
        ScriptEngine pyEngine = new ScriptEngineManager().getEngineByName("python");
        Object Pyoutput = pyEngine.eval("2*3");
        System.out.println(Pyoutput.toString());
      }
    }

I tried this to get the output of eval.

This outputs 6

Which is correct however when i try the same from a print statement:

Object Pyoutput = pyEngine.eval("print('Hello World')");
System.out.println(Pyoutput.toString());

the output is null when it should be Hello World. Is there a way to print the entire output/terminal content of a script that has been eval/exec by jython?


Solution

  • You can set a Writer for the scripts to use through the engines ScriptContext. For example:

    ScriptEngine pyEngine = new ScriptEngineManager().getEngineByName("python");
    StringWriter sw = new StringWriter();
    pyEngine.getContext().setWriter(sw);
    pyEngine.eval("print('Hello World')");
    System.out.println(sw.toString());
    

    Prints

    Hello World