简体   繁体   中英

How to save a Java object in Jython/Python

I'm building a Python UI using Tkinter. For the needs of the program, I've to connect Python with Java to do some stuff, so I'm using a simple Jython script as a linker. I cant use Tkinter with Jython because it's not supported.

Python (ui.py) -> Jython (linker.py) -> Java (compiled in jars)

To call the Jython function in Python I use subprocess as follows:

ui.py:

cmd = 'jython linker.py"'
my_env = os.environ
my_env["JYTHONPATH"] = tons_of_jars
subprocess.Popen(cmd, shell=True, env=my_env)

Then, in the Jython file, linker.py , I import the Java classes already added on the JYTHONPATH, and I create an object with the name m and call to some functions of the Java class.

linker.py:

import handler.handler
m = handler.handler(foo, moo, bar)
m.schedule(moo)
m.getFullCalendar()
m.printgantt()

The thing is that I've created a m object, that will be destroyed after the execution of jython linker.py ends. So the question is: Is possible to save that m object somewhere so I can call it from ui.py whenever I want? If it's not possible, is there any other way to do this?

Thanks in advance.

I finally solved it by using ObjectOutputStream .

from java import io

def saveObject(x, fname="object.bin"):
    outs = io.ObjectOutputStream(io.FileOutputStream(fname))
    outs.writeObject(x)
    outs.close()

def loadObject(fname="object.bin"):
    ins = io.ObjectInputStream(io.FileInputStream(fname))
    x=ins.readObject()
    ins.close()
    return x

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