Skip to content

Instantly share code, notes, and snippets.

@fser
Created June 26, 2020 18:14
Show Gist options
  • Save fser/997a16281467957df78416503ea903e1 to your computer and use it in GitHub Desktop.
Save fser/997a16281467957df78416503ea903e1 to your computer and use it in GitHub Desktop.
Uses libbz2 c-library using ctypes to decompress files.
#!/usr/bin/env python3
#
# "THE BEER-WARE LICENSE" (Revision 42):
# <[email protected]> wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return.
from ctypes import *
from ctypes.util import find_library
from sys import argv, stderr, exit
if len(argv) < 2:
print("Usage: {} <filename>".format(argv[0]), file=stderr)
exit(1)
z2 = find_library("bz2")
if not z2:
print("Lib bz2 not found :(")
exit(1)
libz2 = CDLL(z2)
for infile in argv[1:]:
outfile = infile[:-4] if infile[-4:] == '.bz2' else infile + '.out'
f = libz2.BZ2_bzopen(infile.encode(), "r".encode())
buffer = create_string_buffer(1024)
ptr = cast(f, c_void_p)
with open(outfile, 'w') as out:
while True:
res = libz2.BZ2_bzread(ptr, buffer, sizeof(buffer))
if res <= 0:
break
out.write(buffer.value[:res].decode())
libz2.BZ2_bzclose(f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment