问题描述:

So I can send strings just fine. What I want to do though is to more or less send a string representation of a list. I know quite a few to convert a list into something that should be able to sent as a string and then converted back.

#on sending

l = [1,2,3,4]

l_str = str(l)

#on receiving

l = ast.literal_eval(received_data)

## or pickle

l = pickle.dumps([1,2,3,4])

##then

l = pick.loads(received_data)

My issues however seems to be that something odd is happening between the receiving and sending.

Right now I have this

msg = pickle.dumps([sys.stdin.readline(), person])

s.send(msg)

where sys.stdin.readline() is the line typed into the console and person is a variable containing someone's name.

I then receive it like so.

d1 = sock.recv(4096)

pickles = False

try:

d1 = pickle.loads(d1)

pickles = True

It doesn't matter if I just make the list string by my first method and then use ast.literal_eval or use pickle, it never actually converts back to the list I want.

I currently have a try statement in place because I know there will be times where I will actually not be getting back something that was dumped using pickle or what not, so the idea is that it should fail on those and in the except just continue as if the data received was formatted correctly.

The error that is produced when I try to unpickle them for instance is

 Traceback (most recent call last):

File "telnet.py", line 75, in <module>

d1 = pickle.loads(d1)

File "/usr/local/lib/python2.7/pickle.py", line 1382, in loads

return Unpickler(file).load()

File "/usr/local/lib/python2.7/pickle.py", line 858, in load

dispatch[key](self)

KeyError: '\r'

The pickle.loads never succeeds because pickles is never True...... Any ideas?

EDIT: I have the overall solution. The issue for me was actually not in the file you see in the error, that being telnet.py, but in another file. I didn't realize that the intermediate server was receiving input and changing it. However, after some suggestions, I realized that was what exactly was happening.

网友答案:

My issue actually came from another file. At the time I did not realize that this being a chat server / client was important. However, the chat server was actually sending data back to the client that it formatted.. honestly I don't know how that didn't hit me but thats what happened.

相关阅读:
Top