serialize object in jython, read into python
Kent Johnson
kent at kentsjohnson.com
Thu Dec 22 19:16:59 EST 2005
py wrote:
> I want to serialize an object in jython and then be able to read it in
> using python, and vice versa.
>
> Any suggestions on how to do this? pickle doesnt work, nor does using
> ObjectOutputStream (from jython).
>
> I prefer to do it file based ...something like
>
> pickle.dump(someObj, open("output.txt", "w"))
>
> as opposed to shelve
>
> f = shelve.open("output.txt")
> f['somedata'] = someObj
It works for me. I think the problem is that your pickle file is not closed properly, when
I tried it with the form you have above the file was never written. Here is an example
that works with Jython 2.1 and Python 2.4.2:
D:\WUTemp>jython
Jython 2.1 on java1.4.2_06 (JIT: null)
Type "copyright", "credits" or "license" for more information.
>>> a='hello world'
>>> b=tuple(range(10))
>>> c={ 'a':1, 'b':2, 'c':3}
>>> class Foo:
... pass
...
>>> d=Foo()
>>> lst=[a,b,c,d]
>>> lst
['hello world', (0, 1, 2, 3, 4, 5, 6, 7, 8, 9), {'b': 2, 'a': 1, 'c': 3}, <__main__.Foo
instance at 17930334>]
>>> f=open('pickle.txt', 'wb')
>>> import pickle
>>> pickle.dump(lst, f)
>>> f.close()
>>> ^Z
D:\WUTemp>python
Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> class Foo:
... pass
...
>>> f=open('pickle.txt')
>>> lst = pickle.load(f)
>>> f.close()
>>> lst
['hello world', (0, 1, 2, 3, 4, 5, 6, 7, 8, 9), {'a': 1, 'c': 3, 'b': 2}, <__main__.Foo
instance at 0x00A51350>]
>>>
Kent
More information about the Python-list
mailing list