Skip to content

Instantly share code, notes, and snippets.

@micolous
Created December 9, 2010 07:11
Show Gist options
  • Save micolous/734437 to your computer and use it in GitHub Desktop.
Save micolous/734437 to your computer and use it in GitHub Desktop.
Transparent compression system for python (bytecode)
#!/bin/env python
# compressor. it's like upx for python.
# decompression stub. this will decompress the data and evaluate the module code stored in the docstring.
DECOMPRESS = """from marshal import loads
__doc__ = loads(__doc__.decode('bz2'))
del loads
eval(__doc__)"""
from bz2 import compress
from sys import argv
import compiler, marshal, imp
print "Creating new compressed bytecode from", argv[1], "into", argv[2], "..."
# read in the bytecode
fin = open(argv[1], 'rb')
comp_data = '\'' + compress(fin.read()[8:]).encode('string_escape') + '\'\n'
fin.close()
# compile the code
data = compiler.compile(comp_data + DECOMPRESS, '', 'exec')
# write it out
fout = open(argv[2], 'wb')
fout.write(imp.get_magic() + "LOLZ" + marshal.dumps(data))
fout.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment