2

I want to modify quicktime files, so I'm working with quicktime.py but it only parses information. It doesn't know how to write/modify things.

In C, struct records are actually very powerful - you get 4 things for the cost of 1 readable definition:

  1. Define names for each variable.
  2. Define serializable types and order for each variable (let's ignore machine specific shenanigans for this discussion).
  3. Pack (write)
  4. Unpack ('parse')

In python, the struct module can do numbers 2-4 but you need to do extra work to make python define names for both packing and unpacking based on 1 definition (DRY).

OTOH ctypes is able to do 1-4 (3-4 aren't exactly in the stdlib but they're easier to patch in using this) and ctypes supports nesting.

I understand that if more complex parsing/serializing is needed, specific code will be written. But still it seems to me that I should be able to explain to python what a file looks like and it could do the rest (pack/unpack). Problem is that ctypes is advertised as a "foreign function library" so it's not "supposed" to do this. Another issue is ctypes probably won't work well with a HUGE file where you just want to seek to wherever and change a few bits, though I haven't tested this.

Here's the question: what's the DRY way to read and modify binary formats in python?

Community
  • 1
  • 1
ubershmekel
  • 11,864
  • 10
  • 72
  • 89
  • Now that I have these 2 fine answers I'm comparing how they work using their png parser: https://bitbucket.org/haypo/hachoir/src/2a6cad1599c6/hachoir-parser/hachoir_parser/image/png.py vs https://github.com/MostAwesomeDude/construct/blob/master/construct/formats/graphics/png.py so I'll come back in a jiffy and tell which one I chose. – ubershmekel Apr 11 '11 at 22:16

2 Answers2

2

Maybe try Hachoir ?

Rom1
  • 3,167
  • 2
  • 22
  • 39
2

Try Construct, it does exactly what you want.

Björn Lindqvist
  • 19,221
  • 20
  • 87
  • 122