how do i pack and unpack messages in python?

Randall Hopper aa8vb at yahoo.com
Fri Apr 21 07:40:28 EDT 2000


Shaun:
 |Randall:
 |> Shaun:
 |>  |id           : 10
 |>  |subid        : 13
 |>  |NV sequence  : {14, "shaun"-string
 |>  |               {20, ["Anytown, Anywhere"]-list
 |>  |               {34, 1234567890-int
 |>  |
 |>  |i want to pack the message to look like this:
 |>  |
 |>  |10 fs 13 fs 14 fs s shaun fs 20 fs l s anytown fs s anywhere fs i
 |>  |1234567890 gs gs
 |>
 |> I was going to mention the struct, array, or xdrlib modules to you, but
 |> from your desired output format (all ASCII it appears), it looks like
 |> a simple string.join would do the job:
 |
 |actually randall, i kinda simplified the output, it was more representative
 |than actual, so if you have time to mention the struct, array, or xdrlib
 |modules, i would be gratefull.

struct gives you packing and unpacking of basic Python types into binary
data structures (like C structures).  array does this for long homogeneous
sequences of integer and floating point types (you can use struct, but
array saves looping in Python).  And xdrlib gives you the capability to
serialize to a binary RFC 1014 stream such as that used by RPC.

So if you want to write a binary stream of the above data, you may want to
check out struct or xdrlib.

>>> import struct
>>> struct.pack( 'iiii5s', 10, 13, 14, len('shaun'), 'shaun' )
'\000\000\000\012\000\000\000\015\000\000\000\016\000\000\000\005shaun'

>>> import xdrlib
>>> packer = xdrlib.Packer()
>>> packer.pack_int( 10 )
>>> packer.pack_int( 13 )
>>> packer.pack_int( 14 )
>>> packer.pack_string( 'shaun' )
>>> packer.get_buffer()
'\000\000\000\012\000\000\000\015\000\000\000\016\000\000\000\005shaun\000\000\000'

-- 
Randall Hopper
aa8vb at yahoo.com




More information about the Python-list mailing list