当前位置: 代码迷 >> python >> Python的`tarfile`模块是否存储了它在内存中构建的档案?
  详细解决方案

Python的`tarfile`模块是否存储了它在内存中构建的档案?

热度:101   发布时间:2023-07-16 10:01:23.0

我正在一个内存受限的环境中工作,我需要在其中创建SQL转储存档。 如果我使用python的内置是'.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()

不,它没有加载到内存中。 您可以读取的看它是否正在使用copyfileobj ,它使用固定大小的缓冲区从文件复制到tarball:

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