我正在开发一个大型Java项目,其中Jython脚本是从Java代码解释的。由于我还没有想到的原因,除非函数,类,变量全部声明为全局,否则Jython脚本中没有任何作用。 为了追查这个问题,我把问题缩小到了这个范围。以下是:
script.py
java -jar jython.jar script.py
Interpreter.java
Python脚本:
#global aFunction # uncommenting this makes the script work from Java
def main():
aFunction()
def aFunction():
print 'aFunction() called'
main()
Java类:
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();
}
}
}
这是运行Java类时出现的错误。
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
有关如何更正Java类以便解释器可以运行Jython脚本的任何想法?谢谢!
答案 0 :(得分:3)
我无法解释您所获得的错误,但我能够通过PythonInterpreter
使其成功:
org.python.util.PythonInterpreter interp = new org.python.util.PythonInterpreter();
String scriptname = "script.py";
interp.execfile(scriptname);