我需要使用Python 2.4.3中的struct.pack打包变长数组,并提示?
数组数据值的长度必须为n,我希望将其作为包中列出每个元素的最后一个参数。
datavalues = array("i",[20, 40, 60])
data = conn.recv(1024)
print 'Connect by', addr
print 'nice try'
sys.stdout.write(hexdump(data))
recvStruct = '>hhhBBhh'
recvStructSize = struct.calcsize(recvStruct)
recvFormat = '%s%dx' % (recvStruct, len(data) - recvStructSize)
TransID , ProtoColID, PacketLength, UnitID, FC, StartAddress, RegisterCount = struct.unpack(recvFormat, data)
datatranStruct = '>hhhBBBhhh'
datatranStructSize = struct.calcsize(datatranStruct)
datatranFormat = '%s%dx' % (datatranStruct, 10 + (2*RegisterCount) - datatranStructSize)
print 'datatranFormat ',datatranFormat
print TransID, ProtoColID, PacketLength, UnitID
print FC, StartAddress, RegisterCount
# I want to just say datavalues in the next line, I know I need to fix the format statement when using n values
datatran = struct.pack(datatranFormat, TransID , ProtoColID, PacketLength+(2*RegisterCount), UnitID, FC, 2*RegisterCount, datavalues[0], datavalues[1], datavalues[2])
conn.sendall(datatran)