【问题标题】:gzip string, then base64 value of gzipgzip 字符串,然后是 gzip 的 base64 值
【发布时间】:2017-06-21 05:57:06
【问题描述】:

我想在python 2.6 中实现这行bash

echo 'some string' | gzip | base64

现在我有这个:

import io
import gzip
import base64

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

我不确定下一步该做什么,因为我一直在尝试不同的方法,而且我尝试的所有不同方法都不断出错。我不确定我是否朝着正确的方向前进

【问题讨论】:

    标签: python bash base64 gzip python-2.6


    【解决方案1】:

    第一个in是关键字,不能作为变量名。

    然后,创建空的BytesIO对象,然后使用GZipFile句柄写入它,使用二进制模式。

    完成后,检索BytesIO 流的内容并使用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()))
    

    结果:

    b'H4sIAF8LSlkC/w==\n'
    

    用 Python 3.4 测试过,在 python 2.x 上也应该可以正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 2019-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多