importing pyc from memory?

Jeff Epler jepler at unpythonic.net
Mon Jul 4 14:01:06 EDT 2005


This stupid code works for modules, but not for packages.  It probably has bugs.


import marshal, types

class StringImporter:
    def __init__(self, old_import, modules):
        self._import = old_import
        self._modules = modules

    def __call__(self, name, *args):
        module = self._modules.get(name, None)
        if module is None:
            return self._import(name, *args)
        code = marshal.loads(module)
        mod = types.ModuleType(name)
        exec code in mod.__dict__
        return mod

def test():
    import __builtin__
    __builtin__.__import__ = StringImporter(__builtin__.__import__,
        { 'test_importer': open("/usr/lib/python2.3/os.pyc").read()[8:] })

    import test_importer
    print test_importer.path.join("a", "b")
    print test_importer.__doc__

if __name__ == '__main__': test()
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20050704/b45b0ea7/attachment.sig>


More information about the Python-list mailing list