【问题标题】:Trouble with compressing big data in python在 python 中压缩大数据的问题
【发布时间】:2014-05-27 05:30:20
【问题描述】:

我有一个 Python 脚本来压缩大字符串:

import zlib

def processFiles():
  ...
  s = """Large string more than 2Gb"""
  data = zlib.compress(s)
  ...

当我运行这个脚本时,我得到了一个错误:

ERROR: Traceback (most recent call last):#012  File "./../commands/sce.py", line 438, in processFiles#012    data = zlib.compress(s)#012OverflowError: size does not fit in an int

一些信息:

zlib.版本 = '1.0'

zlib.ZLIB_VERSION = '1.2.7'

# python -V
Python 2.7.3

# uname -a
Linux app2 3.2.0-4-amd64 #1 SMP Debian 3.2.54-2 x86_64 GNU/Linux

# free
             total       used       free     shared    buffers     cached
Mem:      65997404    8096588   57900816          0     184260    7212252
-/+ buffers/cache:     700076   65297328
Swap:     35562236          0   35562236

# ldconfig -p | grep python
libpython2.7.so.1.0 (libc6,x86-64) => /usr/lib/libpython2.7.so.1.0
libpython2.7.so (libc6,x86-64) => /usr/lib/libpython2.7.so

如何在 Python 中压缩大数据(超过 2Gb)?

【问题讨论】:

  • 您使用的是 64 位版本的 Python 吗?你有多少内存? Python 需要将整个字符串以及正在构造的压缩对象保存在 RAM 中。
  • 我有 64Gb RAM,现在 56Gb 是免费的。系统是 Debian 64 位。如何发现 Python 是 64 位的?
  • 你的 Python 版本也是 64 位的?
  • 我在主题中更新有关系统和 RAM 的信息。

标签: python zlib


【解决方案1】:

我的大数据压缩功能:

def compressData(self, s):
    compressed = ''
    begin = 0
    blockSize = 1073741824 # 1Gb
    compressor = zlib.compressobj()
    while begin < len(s):
      compressed = compressed + compressor.compress(s[begin:begin + blockSize])
      begin = begin + blockSize
    compressed = compressed + compressor.flush()
    return compressed

【讨论】:

    【解决方案2】:

    这不是 RAM 问题。只是 zlib 或 python 绑定无法处理大于 4GB 的数据。

    将您的数据分成 4GB(或更小的块)并分别处理每一个。

    【讨论】:

    • 谢谢!我写了一个函数,用compressobj分块压缩数据,现在可以了。
    • @DmitrySkryabin:请张贴。
    【解决方案3】:

    尝试流式传输...

    import zlib
    
    compressor = zlib.compressobj()
    with open('/var/log/syslog') as inputfile:
         data = compressor.compress(inputfile.read())
    
    print data
    

    【讨论】:

    • 该解决方案触发与上述相同的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    • 1970-01-01
    相关资源
    最近更新 更多