开发者

Python module for implementing binary file formats?

I frequently find myself needing to write code to interact with binary file formats for which there aren't existing tools. I'm looking for an easy way to implement readers/writers for structured binary formats -- ideally something that will let me create the reader using some sort of simple declar开发者_开发知识库ative format.

I've found the Construct module, which works but seems to have been largely abandoned by the author. I'm wondering if there are any alternatives out there that people have worked with.


Personally I'd use the bitstring module, but I may be biased as I wrote it. There's some simple code for reading/writing a binary format in the manual as an example.

This is one way to create via a binary format:

fmt = 'sequence_header_code,
       uint:12=horizontal_size_value,
       uint:12=vertical_size_value,
       uint:4=aspect_ratio_information,
       ...
       '
d = {'sequence_header_code': '0x000001b3',
     'horizontal_size_value': 352,
     'vertical_size_value': 288,
     'aspect_ratio_information': 1,
     ...
    }

s = bitstring.pack(fmt, **d)

and one method to parse it afterwards:

>>> s.unpack('bytes:4, 2*uint:12, uint:4')
['\x00\x00\x01\xb3', 352, 288, 1]


Have a look at Hachoir.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜