python包来扩展标准库的struct包的功能。
EStruct的Python项目详细描述
EStruct提供了标准库的Struct模块提供的扩展打包/解包库。 它提供条件元素和数组的打包。这个图书馆最初是作者为了简化 在mpeg4文件中打包和解包二进制数据。
典型用法:
#!/usr/bin/env python from estruct.estruct import EStruct import sys from datetime import date packager = EStruct("Student", "Student.Name Student.Address Student.DOB", "![50s50sQ]") records=[] with open(sys.argv[1],"rb") as f: records=packager.unpack(f.read()) for r in records: print r.Student.Name, r.Student.Address, date.fromordinal(r.Student.DOB)
estruct也托管在github上的https://github.com/simblack/EStruct
安装
pip install EStruct
结构对象
estruct object\uuu init\uu方法接受三个参数,解包的类名、类中的字段和打包格式。
estruct.\uu init(self,name,fields\u string,format\u string)
姓名
这只是解包值时创建的对象的名称。
字段字符串
字段字符串是包含字段和子字段的描述。 字符串必须是一个用空格分隔的字段列表。嵌套结构可以使用点符号“.”创建,即。 object.field或object.sub_object.field。
示例:
'f1 f2 f3.a1 f3.a2 f4 f5.a1.b1 f5.a1.b2 f5.a2.b1 f5.a2.b2' This would create the object with fields: f1,f2,f3,f4,f5 f3 is of a type of an object with fields: a1, a2 f5 is of a type of an object with fields: a1, a2 with both fields of an object of type with fields b1 and b2
格式化字符串
format= byteorder + format_string byte_order= '@'|'='|'<'|'>'|'!' @ native byte-order native size native alignment = native byte-order standard size no alignment < little endian standard size no alignment > big endian standard size no alignment ! network standard size no alignment format_string= conditonal_format | array_format | normal_format | empty_format emptry_format= conditionl_format= '(' + condition + '?' + true_format + ':' + false_format + ')' condition= [python evaluation] true_format= format_string false_format= format_string An empty format_string implies that no field is required for packinging. array_format= count[format_string] count= empty_count | constant_count | field_count empty_count= constant_count= (0..9)* field_count= '{' + [field_name] + '}'
[字段名]是在此包装元素之前定义的任何字段。 [python evaluation]是一个有效的python语句,等于true或false结果。 可以使用此包装元素之前的任何字段名。也可以使用索引值index来评估数组 指定当前索引。
示例
网络尾数,32位整数后跟64,但如果f1==1则为另一个32位整数:
!II(f1==1?Q|I)
网络尾数,32位整数,后跟一个数组,数组的元素数在字段中指定 f1。数组元素是一个32位整数,后跟多个字符,该数字设置在 字段f2[index].a1,该索引是外部数组的当前迭代。:
!I{f1}[I{f2[INDEX].a1}[c]]
拆包
解包方法用于将二进制数据解包到对象中
estruct.unpack(self,data,**kargs)
如果计算需要关键字参数,也可以传递它们。 方法返回由构造函数的字段字符串描述的对象
struct=EStruct('Test','f1 f2','!I{f1}[I]') data=[0,0,0,3,0,0,0,2,0,0,0,1,0,0,0,0] data_str="".join([chr(x) for x in data]) obj=struct.unpack(data_str) print obj.f1, obj.f2
包装
pack方法用于将值打包为二进制字符串
EStruct.pack(self,*args,**kargs)
必须根据打包格式为打包传递正确数量的参数。 如果计算需要关键字参数,也可以传递它们。 方法返回压缩的二进制字符串。
struct=EStruct('Test','f1 f2','!I{f1}[I]') packed_result=self.struct.pack(3,[2,1,0]) print packed_result.encode("hex")