[英]How to save a Java object in Jython/Python
I'm building a Python UI using Tkinter. 我正在使用Tkinter构建Python UI。 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.
为了满足程序的需要,我必须将Python与Java连接起来以做一些事情,因此我使用了一个简单的Jython脚本作为链接器。 I cant use Tkinter with Jython because it's not supported.
我不能将Tkinter与Jython一起使用,因为它不受支持。
Python (ui.py) -> Jython (linker.py) -> Java (compiled in jars)
To call the Jython function in Python I use subprocess
as follows: 要在Python中调用Jython函数,我使用如下
subprocess
:
ui.py: 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. 然后,在Jython文件
linker.py
,导入已经添加到JYTHONPATH上的Java类,并创建一个名称为m
的对象,并调用Java类的某些函数。
linker.py: 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. 事实是,我创建了一个
m
对象,它将在jython linker.py
执行结束后销毁。 So the question is: Is possible to save that m
object somewhere so I can call it from ui.py
whenever I want? 所以问题是:可以将那个
m
对象保存在某个地方,以便我可以随时从ui.py
调用它吗? If it's not possible, is there any other way to do this? 如果不可能,还有其他方法可以做到吗?
Thanks in advance. 提前致谢。
I finally solved it by using ObjectOutputStream
. 我终于通过使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.