Search code examples
pythonpyglet

Pyglet's ZIPLocation


I found out that Pyglet has class with which I can load zip files: http://www.pyglet.org/doc/api/pyglet.resource.ZIPLocation-class.html

There is how I use it:

myzip = zipfile.ZipFile('testzip.zip')
myzip = pyglet.resource.ZIPLocation(myzip, '')
myzip = myzip.open('test.png', mode='rb')

But what it returns is <StringIO.StringIO instance at 0x41ec670> so I can't use in the way I use pyglet.resource.image. I get actually that file as plain text. Is there any method to convert it?


Solution

  • Ok, I guess it's still unimplemented. The only thing that class does is to return file's data in StringIO. And doing that with pure zipfile is even easier. This is how I did that:

    # That class is necessary, it's explained why in Loader's class comments
    class Cleaner(dict):
       pass
    
    class Loader:
        def __init__(self):
            self.sprite = pyglet.resource.image(self.unzip('test.png'))
            self.sprite = pyglet.resource.image(self.unzip('test2.png'))
        def unzip(self, file):
            zip = zipfile.ZipFile('test.zip')
            file = open('.buffer', 'wb')
            # without 'b' it wont work on windows
            file.write(zip.read(file))
            file.close()
            '''now the tricky part: pyglet save every file with weakref to
               dont load save thing more than once, it wouldnt let to load
               files from buffer so we need to block it somehow after each
               file reading i do that with empty dict class (dont need to import weakref)'''
            pyglet.resource._default_loader._cached_images = Cleaner()
            return 'data/.buffer'