I am trying to make a simple python interpreter using java. basically, you write some python code like print('hello world') and the request is sent to a spring boot back end app that interprets the code using PythonInterpreter library and returns the result in a JSON object form like :
{
"result": "hello world"
}
I tried the following code that displays the result of print on the console but I wasn't able yet to assign the return into a variable that I need to construct the JSON response.
PythonInterpreter interp = new PythonInterpreter();
interp.exec("print('hello world')");
prints hello world
on the console.
I want something like this :
PythonInterpreter interp = new PythonInterpreter();
interp.exec("x = 2+2");
PyObject x = interp.get("x");
System.out.println("x: "+x);
this prints x: 4
i want to do the same with print but I still haven't found a solution.
anyone has an idea on how to do this would really appreciate your help.
If you read the documentation, i.e. the javadoc of PythonInterpreter
, you will find the following methods:
setErr(Writer outStream)
- Sets a Writer to use for the standard output stream, sys.stderr.
setOut(Writer outStream)
- Sets a Writer to use for the standard output stream, sys.stdout.
So you would do it like this:
StringWriter out = new StringWriter();
PythonInterpreter interp = new PythonInterpreter();
interp.setOut(out);
interp.setErr(out);
interp.exec("print('hello world')");
String result = out.toString();
System.out.println("result: " + result);