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

Chr*_* W. 6 python memory tar tarfile

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

Spi*_*nim 5

不,它没有加载到内存中.您可以读取tarfile源代码以查看它正在使用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
Run Code Online (Sandbox Code Playgroud)