Sockets

Dave Brueck dave at pythonapocrypha.com
Fri Apr 8 08:34:59 EDT 2005


Dan wrote:

 >On Thu, 7 Apr 2005 21:52:11 -0500, jepler at unpythonic.net wrote:
 >>Python strings always carry their length, and can have embedded NULs.
 >>   s.write("\0\1\2\3")
 >>should write 4 bytes to the socket 's'.
 >
 >I'm taking binary data from a database, so it's not really a Python
 >string.  Is there an easy way to convert it?

Unless I'm misunderstanding you, you don't need to. It's not that Python 
normal strings are "encoded" in some special format, it's just that a 
string object does not make a distrinction between what is traditionally 
called "text" and "binary data".

Play around with this at a Python prompt to see for yourself. For example:

 >>> img = file('foo.jpg', 'rb').read() # use a real image filename though
 >>> img[:50]
'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00H\x00H\x00\x00\xff\xdb\x00C\x00
\x05\x03\x04\x04\x04\x03\x05\x04\x04\x04\x05\x05\x05\x06\x07\x0c\x08\x07\x07\x07
\x07\x0f\x0b\x0b\t'
 >>>

So, the fact that you're getting the data from a database is probably 
immaterial.

HTH,
Dave





More information about the Python-list mailing list