【问题标题】:Does Python's `tarfile` module store the archives it's building in memory?Python 的 `tarfile` 模块是否将它正在构建的档案存储在内存中?
【发布时间】:2011-07-12 23:50:58
【问题描述】:

我在内存受限的环境中工作,我需要对 SQL 转储进行归档。如果我使用 python 内置的tarfile module 是保存在内存中的“.tar”文件还是在创建时写入磁盘?

例如,在下面的代码中,如果huge_file.sql 是 2GB,tar 变量会占用 2GB 内存吗?

import tarfile

tar = tarfile.open("my_archive.tar.gz")), "w|gz")
tar.add('huge_file.sql')
tar.close()

【问题讨论】:

    标签: python memory tar tarfile


    【解决方案1】:

    不,它没有将其加载到内存中。您可以阅读source for tarfile 以了解它正在使用copyfileobj,它使用固定大小的缓冲区从文件复制到压缩包:

    def copyfileobj(src, dst, length=None):
        """Copy length bytes from fileobj src to fileobj dst.
           If length is None, copy the entire content.
        """
        if length == 0:
            return
        if length is None:
            shutil.copyfileobj(src, dst)
            return
    
        BUFSIZE = 16 * 1024
        blocks, remainder = divmod(length, BUFSIZE)
        for b in xrange(blocks):
            buf = src.read(BUFSIZE)
            if len(buf) < BUFSIZE:
                raise IOError("end of file reached")
            dst.write(buf)
    
        if remainder != 0:
            buf = src.read(remainder)
            if len(buf) < remainder:
                raise IOError("end of file reached")
            dst.write(buf)
        return
    

    【讨论】:

    猜你喜欢
    • 2010-12-31
    • 1970-01-01
    • 2019-05-10
    • 2018-12-12
    • 2021-04-15
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多