How To Send Objects Through Python?
Solution 1:
Python includes an object serialization module called pickle
: https://docs.python.org/2/library/pickle.html
You can use pickle.dumps(CommandDict[client_data])
to produce a string which you can then send on a socket. Then use pickle.loads
to restore the object on the other side. Of course this requires that the object is "pickleable", but many simple data structures are, or can be made so without much trouble. In your case you may need to add some code to pickle the ImageGrab
object type, but try it first and see if it works by default.
Solution 2:
The following should allow you to pickle an image. I don't have PIL on my current machine, so I haven't been able to test it properly. The machine
import cPickle as pickle # cPickle is considerably more efficient than pickle
import copy_reg
from StringIO import StringIO
from PIL import Image, ImageGrab
def pickle_image(img):
"""Turns an image into a data stream. Only required on machine sending the
image."""
data = StringIO()
img.save(data, 'png')
data.seek(0)
return unpickle_image, (data,)
def unpickle_image(data):
"""Turns a data stream into an image. Required on both machines"""
img = Image.open(data)
data.close() # releases internal buffer immediately
return img
# tells pickle it should use the function pickle_image to pickle objects of
# type Image. Required on the machine sending the image
copy_reg.pickle(Image, pickle_image)
some_image = ImageGrab.grab()
# HIGHEST_PROTOCOL uses a more effcient representation of the object
pickled_image = pickle.dumps(some_image, pickle.HIGHEST_PROTOCOL)
unpickled_image = pickle.loads(pickled_image)
In my code I have used dumps
and loads
to create and use a string representation of the data. Ideally you should be using dump
and load
, passing my_socket.makefile()
as the file argument.
Post a Comment for "How To Send Objects Through Python?"