Sending a Dictionary using Sockets in Python?

前端 未结 6 619
悲哀的现实
悲哀的现实 2021-01-12 06:27

My problem: Ok, I made a little chat program thing where I am basically using sockets in order to send messages over a network.

It works great, but when I decided t

6条回答
  •  遥遥无期
    2021-01-12 06:54

    You have to serialize your data. there would be many ways to do it, but json and pickle will be the likely way to go for they being in standard library.

    for json :

    import json
    
    data_string = json.dumps(data) #data serialized
    data_loaded = json.loads(data) #data loaded
    

    for pickle(or its faster sibling cPickle):

    import cPickle as pickle
    
    data_string = pickle.dumps(data, -1) 
    #data serialized. -1, which is an optional argument, is there to pick best the pickling protocol
    data_loaded = pickle.loads(data) #data loaded.
    

    also, please don't write

    i= True
    while i is True:
     #do_something
    

    because simple while True: would suffice.

提交回复
热议问题