[Tutor] reading output from a c executable.
Alan Gauld
alan.gauld at btinternet.com
Sun Dec 21 02:05:21 CET 2008
"Bill Campbell" <bill at celestial.net> wrote
>>struct nameid {
>> u32bits len /* total length */
>>u32bits id;
>>char name; /* name variable length */
>>}
>>
> I haven't done this in python yet, but when handling things like
> this in C and perl, I have done it with two reads, the first to
> get the length, the second to read the data with that length.
Ah yes, I didn't notice that len was the total length of the record,
in that case its much easier. As Bill says you can construct the
struct format string using the calculated length value. Something
like:
fmt = "%dc" % len - (2 * LEN32)
name = struct.unpack(fmt)
You can see a working example of something similar in my
tutor in the handling files topic in the binary files section:
In our case we know it must be like the one we created in
formatAddress(), namely 'iNs' where N is a variable number. How do we
determine the value of N?
The struct module provides some helper functions that return the size
of each data type, so by firing up the Python prompt and experimenting
we can find out how many bytes of data we will get back for each data
type:
>>> import struct
>>> print struct.calcsize('i')
4
>>> print struct.calcsize('s')
1
Ok, we know that our data will comprise 4 bytes for the number and one
byte for each character. So N will be the length of the data minus 4.
Let's try using that to read our file:
import struct
f = file('address.bin','rb')
data = f.read()
f.close()
fmtString = "i%ds" % (len(data) - 4)
number, rest = struct.unpack(fmtString, data)
address = ' '.join((str(number),rest))
print "Address after restoring data:", addressHTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list