社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

Zakarya Elbazy • 4 年前 • 779 次点击  

蟒蛇

{
  "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
 
779 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Andreas
Reply   •   1 楼
Andreas    4 年前

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