[BangPypers] pack data

Noufal Ibrahim noufal at gmail.com
Fri May 28 09:26:59 CEST 2010

On Fri, May 28, 2010 at 12:49 PM, murugadoss <murugadoss2884 at gmail.com> wrote:
> Hello all,
> I am trying a sample program for send set of data [ kept in array]. I have
> attached the code below,
> import struct
> sendvalues = [181, 98, 11, 01]
> for i in range(4):
> snddata = struct.pack('int',int(sendvalue[i]))
> sendto(sndData,("localhost"))

'int' is not a valid struct.pack format specifier. You'll have to say
'i'. Since you have 4 arguments (all signed integers), you'll have to
say 'i'*4.

Something like

  struct.pack('i'*4, *sendvalues)

will pack all four integers into a string. The * before sendvalues it
to unpack the list into arguments. You can send it then. If you want
to send it int by int, you can put

  snddata = struct.pack('i', sendvalue[i])

in your loop (the int constructor is redundant since all the elements
are integers anyway).

Also, you wouldn't use "for i in range(4)" to loop through a list in
Python. You'd say

  for i in sendvalues:
     snddata = struct.pack('i', i)

> i am getting error as,
> Traceback (most recent call last):
>  File "./clientudp.py", line 10, in <module>
>    snddata = struct.pack('hhl',sendvalue[i])
>  File "/usr/local/lib/python2.5/struct.py", line 63, in pack
>    return o.pack(*args)
> struct.error: pack requires exactly 3 arguments

This is somewhat fundamental. Are you sure you read
http://docs.python.org/library/struct.html before trying this? If not,
you know what to do. :)


More information about the BangPypers mailing list