hello python interpreter什么意思_有没有一种方法可以使用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我想对打印执行相同操作,但我仍然没有找到解决方案。

任何人都有关于如何执行此操作的想法,将非常感谢您的帮助。

参考方案

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

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

输入URL字段时,出现错误“远程URL测试失败:不支持协议'git clone HTTPS'” - java

当我单击“定义远程”时,输入在Android Studio的Bitbucket站点中提供的HTTPS URL时,出现错误远程URL测试失败:不支持协议'git clone https'我使用了SSH URL,这给了我错误远程URL测试失败:警告:将IP地址“ 18.205.93.0”的RSA主机密钥永久添加到已知主机列表中。无法从远程存储库读取。我什至尝试从…Java-如何将此字符串转换为日期? - java

我从服务器收到此消息,我不明白T和Z的含义,2012-08-24T09:59:59Z将此字符串转换为Date对象的正确SimpleDateFormat模式是什么? java大神给出的解决方案 这是ISO 8601标准。您可以使用SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM…R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。如何用'-'解析字符串到节点js本地脚本? - python

我正在使用本地节点js脚本来处理字符串。我陷入了将'-'字符串解析为本地节点js脚本的问题。render.js:#! /usr/bin/env -S node -r esm let argv = require('yargs') .usage('$0 [string]') .argv; console.log(argv…将字符串分配给numpy.zeros数组[重复] - python

This question already has answers here: Weird behaviour initializing a numpy array of string data                                                                    (4个答案)         …

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值