Py学习  »  Python

有没有一种方法可以使用PythonInterpreter将“print('python code')”之类的python代码输出的值返回到字符串或其他对象中

Zakarya Elbazy • 5 年前 • 1540 次点击  

蟒蛇

{
  "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 我想对打印也这样做,但我仍然没有找到解决办法。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53978
 
1540 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Andreas
Reply   •   1 楼
Andreas    5 年前

如果您阅读文档,即 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);