[Tutor] How to pass arguments to struct.pack()?

Alan Gauld alan.gauld at btinternet.com
Mon Aug 3 19:53:00 CEST 2009


"prasad rao" <prasadaraon50 at gmail.com> wrote

> I am finding it difficult to pass arguments to struct.pack().

You are not actually passing argments to struct.pack you 
are trying to access a non existent tuple() method of 
struct.pack. Hence the error message.

But your code has several strangenesses... so simplifying

>>>> def structpack(alist):
>             a='%di'%len(alist)
>             return struct.pack( a, *aList )

Should be all you need.

However from a practical point of view you might find it useful 
to write the length of the list in front:

def structpack(aList):
      ln = len (aList)
      fmt = "i%di" % ln
      return struct.pack(fmt, ln, *aList)

That makes it easier to decode if/when you want to read it back.

You will find an example in my tutorial under Handling files.


HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list