java - 有没有办法使用 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
我想对打印做同样的事情,但我仍然没有找到解决方案。
任何人都知道如何做到这一点,非常感谢您的帮助。
解决方案
如果您阅读文档,即 的 javadoc PythonInterpreter
,您会发现以下方法:
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);
推荐阅读
- android-studio - Android Studio 没有为 Dart 扩展方法识别“on”关键字
- c# - 使用 C# 过滤 Json 输出
- java - spring mvc - HTML表单传递请求参数
- python - 随时间改变变量
- c - 在 C 中将 scanf 用于无符号八进制/十六进制 int
- node.js - 如何在猫鼬中正确构建嵌套对象模型
- javascript - JS如何在条件中使用相对单位
- css - 如何将 css 过滤器应用于固定的背景图像
- .htaccess - 为什么这个 .htaccess 配置会导致重定向循环?
- php - 如何检查 API 是否能够使用 PHP 处理请求