使用JSR-223从Jython脚本获取数据 [英] Get data back from Jython scripts using JSR-223

查看:124
本文介绍了使用JSR-223从Jython脚本获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Jython 2.5.1与JSR-223(即javax.script包)一起使用,并且我希望返回Python脚本的最后一行.例如,在评估此脚本后:

I am using Jython 2.5.1 with JSR-223 (i.e. javax.script package) and I expect the last line of the Python script to be returned. For example, after evaluating this script:

class Multiplier:

  def multiply(self, x, y):
    return x * y

Multiplier().multiply(5, 7)

我应该回到35,但是我得到的却是null.另一方面,它可以与其他测试一起使用:

I should get back 35, but I get null instead. In other hand it works with this other test:

5 * 7

我在做什么错了?

这是Java代码:

public static void main(String[] args) throws Exception {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");

    FileReader f = new FileReader("Multiplier.py");
    Object result = engine.eval(f);
    //assert(result == 35);
}

PS:它在JRuby,Groovy和Rhino上都可以正常工作,即总是返回最后一行.

PS: It works fine with JRuby, Groovy and Rhino, i.e. the last line is always returned.

谢谢.

推荐答案

更新:实际上,我在最初的答案中已经错过了OP的目标(和问题),该答案已在评论中得到澄清. .我正在相应地更新我的答案.

UPDATE: I was actually missing the goal (and problem) of the OP in my initial answer that has been clarified in a comment. I'm updating my answer accordingly.

首先按如下所示更新Multiplier.py脚本:

First update the Multiplier.py script as below:

class Multiplier:

  def multiply(self, x, y):
    return x * y

x = Multiplier().multiply(5, 7)

然后从Java代码中这样调用它:

Then call it like this from the Java code:

public static void main(String[] args) throws Exception {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");

    FileReader f = new FileReader("Multiplier.py");
    engine.eval(f);
    Object x = engine.get("x");
    System.out.println("x: " + x);
}

运行上面的代码时,我得到以下输出:

I get the following output when running the code above:

x: 35

这篇关于使用JSR-223从Jython脚本获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆