Counting bytes
Fredrik Lundh
fredrik at pythonware.com
Mon Feb 25 10:40:36 EST 2002
Hugo Martires wrote:
> I need to send a list in a socket
>
> server side
> ------------
> list = [0.5 0.5 0.5 0.5]
> client.socket.send(list)
(did you try running this code?)
> client side
> -------------
> client.socket.recv(1024)
>
> the problem is the buffer size (1024 bytes)
> if i need to send a "big" list (with more than 1024 bytes), i have to count
> the number of bytes to send in parts. So i must know how many bytes my list
> oucupies.
a list contain objects, not bytes. how things are stored in
memory is implementation dependent; unlike in C, there's no
way to get a pointer to the internal data structures.
to convert python objects to byte streams (and back), use
the pickle module (or cPickle or marshal).
import pickle
list = [0.5, 0.5, 0.5, 0.5]
data = pickle.dumps(list)
# data is now a string of bytes; use len(data) to
# get the number of bytes
list = pickle.loads(data)
more info here:
http://www.python.org/doc/current/lib/module-pickle.html
also see cPickle and marshal. to produce an array of floating
point values (same as C's float data[] or double data[]), use
the array (or struct) module.
</F>
<!-- (the eff-bot guide to) the python standard library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->
More information about the Python-list
mailing list