![](/img/trans.png)
[英]import module error: calling python script using jython in a java program
[英]Jython import Python methods AND variables in java (Load the whole script basically)
由于stackoverflow,我找到了一种将Python脚本导入Java并使用Jython调用其方法之一的方法:
interface DataRetriever {public Object retrieveData();}
...
PythonInterpreter interpreter;
PyObject fun;
DataRetriever dr;
...
interpreter = new PythonInterpreter();
Py.getSystemState().path.append(new PyString("Scripts/"));
interpreter.exec("from " + pythonFileName + "import *");
fun = interpreter.get("retrieveData");
dr = (DataRetriever) fun.__tojava__(DataRetriever.class);
...
public Object thisIsGettingCalledPrettyOften(){
return dr.retrieveData();
}
现在,如果我在python脚本中的方法仅使用局部变量,例如:
def retrieveData():
a = 2
b = 4
c = a + b
return c
,一切正常。
不幸的是,我绝对需要全局定义一些变量,以便它们的值在多次调用检索数据之间保持不变-但是“ from script import *”显然不会导入这些变量。 示例脚本:
timesCalled = 0
def retrieveData():
timesCalled += 1
return timesCalled
如何导入这些变量?
通过在我的restoreData函数中添加“全局”语句来解决该问题。 简单的python错误显然...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.