问题
I'm trying to convert the following perl code:
unpack(.., "Z*")
to python, however the lack of a "*" format modifier in struct.unpack() seems to make this impossible. Is there a way I can do this in python?
P.S. The "*" modifier in perl from the perldoc - Supplying a * for the repeat count instead of a number means to use however many items are left, ...
So although python has a numeric repeat count like perl, it seems to lack a * repeat count.
回答1:
python's struct.unpack
doesn't have the Z
format
Z A null-terminated (ASCIZ) string, will be null padded.
i think this
unpack(.., "Z*")
would be:
data.split('\x00')
although that strips the nulls
回答2:
I am assuming that you create the struct datatype and you know the size of the struct. If that is the case, then you can create a buffer allocated for that struct and the pack the value into the buffer. While unpacking, you can use the same buffer to unpack directly by just specifying the starting point.
For e.g.
import ctypes
import struct
s = struct.Struct('I')
b = ctypes.create_string_buffer(s.size)
s.pack_into(b, 0, 42)
s.unpack_from(b, 0)
回答3:
You must calculate the repeat count yourself:
n = len(s) / struct.calcsize(your_fmt_string)
f = '%d%s' % (n, your_fmt_string)
data = struct.unpack(s, f)
I am assuming your_fmt_string
doesn't unpack more than one element, and len(s)
is perfectly divided by that element's packed size.
来源:https://stackoverflow.com/questions/5849167/python-struct-unpack