Search code examples
pythonbashbase64gzippython-2.6

gzip string, then base64 value of gzip


I want implement this line of bash in python 2.6.

echo 'some string' | gzip | base64

Right now I have this:

import io
import gzip
import base64

st = 'some string'
in = io.BytesIO(st)
gzz = gzip.GzipFile(fileobj=in)

I'm not sure what to do next because I've been playing around with different methods and I keep getting errors for all the different methods I try. I'm not sure if I am headed in the right direction


Solution

  • First in is a keyword, cannot be used as a variable name.

    Then, create the BytesIO object empty, then use the GZipFile handle to write into it, using binary mode.

    When done, retrieve the contents of the BytesIO stream and encode it with base64.encode

    import io
    import gzip
    import base64
    
    st = b'some string'
    fo = io.BytesIO()
    gzz = gzip.GzipFile(fileobj=fo,mode="wb")
    
    gzz.write(st)
    
    print(base64.encodebytes(fo.getvalue()))
    

    result:

    b'H4sIAF8LSlkC/w==\n'
    

    tested with Python 3.4, should work OK with python 2.x as well.