我正在尝试使用java创建一个简单的python解释器。基本上,您编写了一些Python代码,例如print('hello world'),然后将请求发送到Spring Boot后端应用程序,该应用程序使用 PythonInterpreter 库解释代码,并以JSON对象形式返回结果就像:
{
"result": "hello world"
}
我尝试了下面的代码在控制台上显示打印结果,但还无法将返回值分配给构造JSON响应所需的变量。
PythonInterpreter interp = new PythonInterpreter();
interp.exec("print('hello world')");
在控制台上打印hello world
。
我想要这样的东西:
PythonInterpreter interp = new PythonInterpreter();
interp.exec("x = 2+2");
PyObject x = interp.get("x");
System.out.println("x: "+x);
此打印x: 4
我想对打印进行相同操作,但我仍然没有找到解决方法。
任何人都知道如何执行此操作,将非常感谢您的帮助。
答案 0 :(得分:3)
如果您阅读文档,即PythonInterpreter
的javadoc,则会发现以下方法:
setErr(Writer outStream)
-设置用于标准输出流sys.stderr的Writer。
setOut(Writer outStream)
-设置用于标准输出流sys.stdout的Writer。
所以您可以这样做:
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);