简体   繁体   中英

Jython import Python methods AND variables in java (Load the whole script basically)

I found a way to import a Python Script into java and call one of its methods with Jython thanks to stackoverflow:

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();
}

Now, if my method in the python script only uses local variables, for example:

def retrieveData():
    a = 2
    b = 4
    c = a + b
    return c

, everything works fine.

Unfortunately, I absolutely need to have some variables defined globally so that they their value persists between multiple calls to retrieveData - But the "from script import *" apparently does not import those variables. Example script:

timesCalled = 0
def retrieveData():
    timesCalled += 1
    return timesCalled

How do I also import those variables?

Solved it by adding a "global" statement in my retrieveData function. Simple python error apparently...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM