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)
I should get back 35, but I get null instead. In other hand it works with this other test:
5 * 7
What am I doing wrong?
Here's the Java code:
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: It works fine with JRuby, Groovy and Rhino, i.e. the last line is always returned.
Thanks in advance.
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.
First update the Multiplier.py script as below:
class Multiplier:
def multiply(self, x, y):
return x * y
x = Multiplier().multiply(5, 7)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With