gpt4 book ai didi

java - 有没有办法使用 PythonInterpreter 将 python 代码的输出值(例如 "print(' python code')"返回到字符串或其他对象中

转载 作者:行者123 更新时间:2023-12-01 19:30:05 24 4
gpt4 key购买 nike

我正在尝试使用 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 我想对 print 执行相同的操作,但我仍然没有找到解决方案。

任何知道如何执行此操作的人都会非常感谢您的帮助。

最佳答案

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

所以你会这样做:

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

关于java - 有没有办法使用 PythonInterpreter 将 python 代码的输出值(例如 "print(' python code')"返回到字符串或其他对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60022203/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com