如何通过python发送对象? [英] how to send objects through python?

查看:68
本文介绍了如何通过python发送对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一台服务器:

import socket
import time
import random
from PIL import ImageGrab

server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_socket.bind(('127.0.0.1',8820))
server_socket.listen(1)

while True:
    print "Waiting for commands"
    a = ImageGrab.grab()
    CommandDict = {"TIME" : time.strftime("%a %b %d %H:%M:%S %Y"),"NAME": "Ori","RANDOM":   str(random.randint(0,10)),"EXIT":"BYE","PRINT SCREEN":a}
    (client_socket, client_address) = server_socket.accept()
    client_data = client_socket.recv(1024)
    print "GOT COMMAND FROM " + client_address[0] + " : " + client_data
    client_socket.send(CommandDict[client_data])
    client_socket.close()

server_socket.close()

和客户:

import socket
from PIL import ImageGrab
while True:
    client_input = raw_input("Enter You Command: ")
    CommandList=["EXIT","TIME","NAME","RANDOM","PRINT SCREEN"]
    if client_input in CommandList:
        my_socket=socket.socket()
        my_socket.connect(('127.0.0.1',8820))
        my_socket.send(client_input)
        data = my_socket.recv(1024) + "\n"
        if client_input=="PRINT SCREEN":
        data.save()
        else:
            print "SERVER: " + data
    else: 
        print "Invalid command. try one of those: " + " , ".join(CommandList) + "\n" + "."


my_socket.close()

当我尝试这个时,它给了我一个错误,因为它试图将它作为字符串对象发送.我想通过套接字发送一个对象,我希望客户端读取它.有什么想法吗?

When i try this it gives me an error because it trys to send it as a string object. I want to send an object through socket and i want the client to read it. Any ideas?

推荐答案

Python 包含一个名为 pickle 的对象序列化模块:https://docs.python.org/2/library/pickle.html

Python includes an object serialization module called pickle: https://docs.python.org/2/library/pickle.html

您可以使用 pickle.dumps(CommandDict[client_data]) 生成一个字符串,然后您可以在套接字上发送该字符串.然后使用 pickle.loads 恢复另一侧的对象.当然,这要求对象是可腌制的",但许多简单的数据结构是,或者可以毫不费力地做到这一点.在您的情况下,您可能需要添加一些代码来腌制 ImageGrab 对象类型,但请先尝试一下,看看它是否在默认情况下有效.

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.

这篇关于如何通过python发送对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆