[Tutor] Returning repr() data by function

Joel Ricker joel@prettyhipprogramming.com
Sun, 28 Jul 2002 18:17:26 -0400


Horrible subject line :)

I'm been working with the wxPython gui framework and it uses a class called
wxBitmap to store an image for use within the program.  I've got a bunch of
little icons that I'm planning to use and instead of having a directory of a
bunch of little images, I'm trying to write a python program that creates
the class, pickles it, compresses the text by zlib, and takes the resulting
text and writes a python function to a module file to be used in my
application.

I found a script that comes with PIL called image2py that works similar to
what I want but when I adapted the code into my script, I keep getting a
invalid \x escape when it tries to parse the resulting module. The
difference between my code and theirs is that they use StringIO to load the
file and does a repr() on that.

Here is a sample of the output file I'm getting:

import cPickle
import zlib

def getFlagAA():

     return
cPickle.loads(zlib.decompress('x\xda\xd3\xc8,\xaf\x08\xa8,\xc9\xc8\x\
cf\xd3KO\xc9\xe4*\xafp\xca,\xc9M,\xe0*0\xe4\xd2H)0\xe2\nV/\xc9\xc8,V\xe7*0\x
\
062\xe3S\x8c-L\x13-\xe2a\xaa\xe2\x0b\xd4\xb9\x8a!*\xf2\xcb\xf3\x80\x8aL\xb8<
\
\r\xb9\x8a\x93\xf4\x00\xcb\xa7\x1b8'))

And my code:

import glob
from wxPython.wx import *
import cPickle
import zlib
import os

octdigits = "01234567"
wxInitAllImageHandlers()

files = glob.glob("images/*.*")

f = open("images.py", "wb")
f.write("import cPickle\n")
f.write("import zlib\n\n")

for x in files:
    name, ext = os.path.splitext(os.path.basename(x))
    print name.upper()

    ## wxBitmap takes in a filename to an image file, type =
wxBITMAP_TYPE_ANY
    ## tells wxBitMap to guess what image type it is (GIF, PNG, etc)
    image = wxBitmap(name = x, type = wxBITMAP_TYPE_ANY)

    data = zlib.compress(cPickle.dumps(image), 9)
    data = repr(data)
    f.write("def getFlag%s():\n\n" % name.upper())

    word = "\treturn cPickle.loads(zlib.decompress('"

    f.write(word)
    c = len(word)

    i = 1
    while i < len(data)-1:
        if data[i] != "\\":
            word = data[i]
            i = i + 1
        else:
            if data[i+1] in octdigits:
                for n in range(2, 5):
                    if data[i+n] not in octdigits:
                        break
                word = data[i:i+n]
                i = i + n
            else:
                word = data[i:i+2]
                i = i + 2
        l = len(word)
        if c + l >= 78-1:
            # fp.write("'\n'")
            f.write("\\\n")
            c = 0
        f.write(word)
        c = c + l

    f.write("'))\n\n\n")

Thanks for any help
Joel