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:Then call it like this from the Java code:
I get the following output when running the code above:
I had the same problem. I have written a scripting library that supports JSR223 and have submited http://bugs.jython.org/issue1798:
At least if you
eval("x=5\nx")
it seems like you would get the value back.This is a Python language issue more than a Jython or JSR 223 issue. Python differentiates between expressions (which have values) and statements (which don't). The script you're passing is a statement. If you passed an expression, it'd have a value.
The reason you're seeing something different with Ruby and JavaScript is that compound statements have the value of the last statement evaluated. For example, compare Ruby:
with Python:
JavaScript seems to be somewhere in between. Like Ruby, assignments evaluate to the value assigned. However, the last evaluated statement in a block is returned but not usable as part of an expression: