Im having an issue using Jython, I wish to capture the output of the eval function:
Object Pyoutput = pyEngine.eval("print('Hello World')");
System.out.println(Pyoutput.toString());
This was how i thought it could be done, but instead turns into a reference to the object. After some googling i found ways only to access specific variables etc that have been previously evaluated.
I have also tried exec:
interp.exec("print("hello world")");
But this cannot be assigned to a variable as its type is void. So my question is, is it possible to recover the entire output of eval or exec into a Java string so it can be displayed in another text field?
Pyoutput
in the question is null
(print
does not return anything), so Pyoutput.toString()
results in a NullPointerException
.
It works with an expression that yields a value. The following program prints 6
.
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());
}
}