Simple Jython script doesn't run from Java
I am working on a big Java project, where Jython scripts are interpreted from Java code. For a reason I have not yet figured out, nothing works in the Jython script unless functions, class, variables, are declared all as global. In an attempt to track down this problem, I have narrowed the issue down to this. Below are :
- A Jython script
script.py
which runs well when launched withjava -jar jython.jar script.py
- A Java main class
Interpreter.java
which uses Jython 2.2 methods to try and interpret the Jython script given above
Python script :
#global aFunction # uncommenting this makes the script work from Java
def main():
aFunction()
def aFunction():
print 'aFunction() called'
main()
Java class :
import java.io.File;
import org.python.core.PyException;
import org.python.core.PyStringMap;
import org.python.core.PySystemState;
public class Interpreter {
public static void main(final String[] args) {
final PyStringMap localNameSpace = new PyStringMap();
final PyStringMap globalNameSpace = new PyStringMap();
final File scriptFile = new File("../../jython/script.py");
PySystemState.initialize();
try {
org.python.core.__builtin__.execfile(scriptFile.getAbsolutePath(), globalNameSpace, localNameSpace);
} catch (final PyException pyException) {
pyException.printStackTrace();
}
}
}
Here is the error I get when running the Java class.
Traceback (innermost last):
File "/opt/coflight/axel/workspace/essais/../../jython/script.py", line 12, in ?
File "/opt/coflight/axel/workspace/essais/../../jython/script.py", line 5, in main
NameError: aFunction
Any ideas on ho开发者_开发问答w to correct the Java class so that the interpreter can run the Jython script ? Thanks !
I can't explain the error that you get, but I was able to make it work by using PythonInterpreter
:
org.python.util.PythonInterpreter interp = new org.python.util.PythonInterpreter();
String scriptname = "script.py";
interp.execfile(scriptname);
精彩评论