Greetings,
I'm building a wrapper class for the struct module to help me handle
network data. The tin can on the other end of the string is probably a
C program that does pointer casts into C structures. I'd like to build
a helper class to pack and unpack these datagrams. It will rely on the
struct module for packing and unpacking the data.
I've done the unpacking method quite easily. Another one of those
tasks that makes you feel like programming is a fun and rewarding
pastime, thanks to Python. Problems show up when I try to pack the
data back into a binary string, because struct.pack's arugments are
(format, *args). The problem is, I don't know what *args will be when
I declare the class, only when an object is instantiated.
Is there a general method for calling a function that expects *args
with an iterable instead (tuple or, even better, a list)? I can see
how I could do something funky with exec, but I'd like to avoid that
if possible.
I considered hacking structmodule.c, but that would involve climbing a
certain learning curve, and I would much rather not depend on
non-standard behavior in the standard library.
Thanks for any pointers people might have...
Nick
p.s. Here's the module as it stands (minus some front matter):
import struct
class dstruct(object):
def __init__(self, structure, hasblob = False):
self.format = ''.join([ y for x, y in structure ])
self.fields = [ x for x, y in structure ]
self.hasblob = hasblob
for v in self.fields:
self.__dict__[v] = None
if hasblob:
self.blob = None
self.structsize = struct.calcsize(self.format)
def unpack(self, dat):
elements = struct.unpack(self.format, dat[:self.structsize])
for k, v in zip(self.fields, elements):
self.__dict__[k] = v
if self.hasblob:
self.blob = dat[self.structsize:]
def pack(self):
# need some way to call struct.pack with a list/tuple of values
# built with [ self.__dict__[v] for v in self.fields ]
pass
--
# sigmask || 0.2 || 20030107 || public domain || feed this to a python
print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') 8 2703
On 21 Nov 2003 11:49:45 -0500, Nick Vargish <na*******@bandersnatch.org.invalid> wrote: Greetings,
Is there a general method for calling a function that expects *args with an iterable instead (tuple or, even better, a list)? I can see how I could do something funky with exec, but I'd like to avoid that if possible. def foo(*args): print args
... foo(*[x for x in 'You mean like this ?'.split()])
('You', 'mean', 'like', 'this', '?')
(just prefix '*' to unpack a sequence into the arg list)
You can even unpack a generator-supplied sequence:
def g():
... for x in 'You mean like this ?'.split(): yield x
... foo(*g())
('You', 'mean', 'like', 'this', '?')
It's not limited to passing args to *args on the receiving end either, though
the count has to match if it's fixed:
def bar(x,y,z): print x,y,z
... bar(*'this works too'.split())
this works too
bar(*'but this does not, since the count is wrong.'.split())
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: bar() takes exactly 3 arguments (9 given)
Regards,
Bengt Richter
Nick Vargish wrote: def pack(self): # need some way to call struct.pack with a list/tuple of values # built with [ self.__dict__[v] for v in self.fields ] pass
Shouldn't this work?
struct.pack(*tuple([ self.__dict__[v] for v in self.fields ]))
Cheers,
Evan
Nick Vargish <na*******@bandersnatch.org.invalid> writes: Is there a general method for calling a function that expects *args with an iterable instead (tuple or, even better, a list)? I can see how I could do something funky with exec, but I'd like to avoid that if possible.
Are you just asking for *arg? struct.pack('c'*4, *(['e']*4))
'eeee'
Cheers,
mwh
--
Get out your salt shakers folks, this one's going to take more
than one grain. -- Ator in an Ars Technica news item
Can you give an example of what you're trying to do? Your description
and code are way too confusing. But it sounds to me like your best bet
may be to use the array module and build up your string a field at a time.
Nick Vargish wrote:
.... Is there a general method for calling a function that expects *args with an iterable instead (tuple or, even better, a list)? I can see how I could do something funky with exec, but I'd like to avoid that if possible.
I'm unsure of what you mean; if you explain why this doesn't solve
your problem, we'll go from there?:
I suspect you want something that can be used in the following way:
obj = dstruct(...)
...
obj.pack(5,4,3,2)
To put a little meat in, I'll have pack simply print its args:
class dstruct(object):
...
def pack(self, *args):
for element in args:
print element
This works, now what is unlike what you want?
-Scott David Daniels Sc***********@Acm.Org
Thanks for all the replies -- I think what I want is the *arg
idiom. Amazing that I hadn't encountered it until now!
Over my lunch break I realized that I could do what I wanted with
apply(struct.pack, tuple), but the *arg thing is much tidier.
Thanks again,
Nick
--
# sigmask || 0.2 || 20030107 || public domain || feed this to a python
print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?')
Nick Vargish <na*******@bandersnatch.org.invalid> wrote... def __init__(self, structure, hasblob = False): self.format = ''.join([ y for x, y in structure ]) self.fields = [ x for x, y in structure ] self.hasblob = hasblob for v in self.fields: self.__dict__[v] = None
Just random passing code commentary:
def __init__(self, structure, hasblob = False):
self.format = ''
self.fields = []
for format, field in structure:
self.format += format
self.fields.append(field)
vars(self)[field] = None
That avoids the triple iteration. The vars(self) call is unnecessary,
I just think it looks cleaner. :)
David. dw***********@botanicus.net (David M. Wilson) writes: Just random passing code commentary:
[...] for format, field in structure:
[...] That avoids the triple iteration. The vars(self) call is unnecessary, I just think it looks cleaner. :)
Interestingly enough, I'd already swapped out the list comprehensions
for a single for loop. :^)
Some respondants seemed confused about what I was trying to do... I'm
communicating with a C program that generates datagrams from a C
structure. Many of the datagrams have, for the last two fields,
"unisigned int datasize; char data[]". I wanted a convenient way of
extracting the fields of known size, and the data blob at the end.
If others are interested in the class I've built, I can make it
available (maybe through the Cookbook web site) when it's a little
more mature.
Again, thanks for all the pointers. Although the language itself is
the first reason, the community is a close second for why I love
programming in Python.
Nick
--
# sigmask || 0.2 || 20030107 || public domain || feed this to a python
print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Dick Moores |
last post by:
I need to figure out how to compute pi to base 12, to as many digits as
possible. I found this reference,
<http://mathworld.wolfram.com/Base.html>, but I really don't understand
it well enough....
|
by: Alex Shirley |
last post by:
Hi there
I’m simply trying to check for a blank or empty value in a textbox on my
webform. In this instance I do not want to use a requiredfieldvalidator,
I want to use a customvalidator (as I...
|
by: Christoph Zwerschke |
last post by:
On the page http://wiki.python.org/moin/Python3%2e0Suggestions
I noticed an interesting suggestion:
"These operators ≤ ≥ ≠should be added to the language having the
following meaning:
...
|
by: josh |
last post by:
Hi,
I am trying to validate cXML documents against cXML.dtd using the
XmlValidatingReader. If I set the XMLValidatingReader's ValidatingType
to ValidationType.DTD, I get the following...
|
by: ajay.padala |
last post by:
Hi
I would like to be able to get the inputs that are needed into a
template file programmatically.
For example if we had a template:
=====================
$name has $num marbles in his...
|
by: Michael Sperlle |
last post by:
Is it possible? Bestcrypt can supposedly be set up on linux, but it seems
to need changes to the kernel before it can be installed, and I have no
intention of going through whatever hell that would...
|
by: cty0000 |
last post by:
I need to set several variable (can be different type) by sub
function..
I don't know the count of variable and type, so i used object type and
parameter list like below source..
After setData...
|
by: iu2 |
last post by:
Hi
I'm trying to make a method call automatically to its super using this
syntax:
class A:
chained =
def pr(self):
print 'Hello from A'
|
by: swetha123 |
last post by:
hello,
I don't know how to use cookies
please help me in this
I am using the dream weaver cs4
I designed the navigation bar to my page using dream weaver cs4
navigation bar contains...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: Vimpel783 |
last post by:
Hello!
Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
|
by: jfyes |
last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
|
by: ArrayDB |
last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: Shællîpôpï 09 |
last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
|
by: Faith0G |
last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
| |