首页 > 解决方案 > 有没有办法使用 PythonInterpreter 将 Python 代码的输出值(如“print('python code')”)返回到字符串或其他对象中

问题描述

我正在尝试使用 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我想对打印做同样的事情,但我仍然没有找到解决方案。

任何人都知道如何做到这一点,非常感谢您的帮助。

标签: javapythonspring-bootpythoninterpreter

解决方案


如果您阅读文档,即 的 javadoc PythonInterpreter,您会发现以下方法:

所以你会这样做:

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);

推荐阅读