-1

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.

  • Python [`print` *does not return a value.*](https://stackoverflow.com/a/58887963/2970947). – Elliott Frisch Feb 02 '20 at 00:08
  • @ElliottFrisch Returning a value isn't the only meaning of the word "output"; in this context the output is what's printed to `sys.stdout`. I'm guessing the solution involves redirecting `sys.stdout` to something else. – kaya3 Feb 02 '20 at 00:16
  • Perhaps, or OP could overload `print`. – Elliott Frisch Feb 02 '20 at 00:19

1 Answers1

3

If you read the documentation, i.e. the javadoc of PythonInterpreter, you will find the following methods:

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);
Andreas
  • 154,647
  • 11
  • 152
  • 247