python - Python 的 `tarfile` 模块是否将它正在构建的文件存储在内存中?

标签 python memory tar tarfile

我在一个内存受限的环境中工作,我需要对 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()

最佳答案

不,它没有将它加载到内存中。您可以阅读 source for 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

关于python - Python 的 `tarfile` 模块是否将它正在构建的文件存储在内存中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5264755/

相关文章:

python - 为属性提供自定义 __str__ 表示

python - 重写所有 svn :externals in repository trunk 的脚本/实用程序

python - 预接收 Hook 中的 git push 选项

c++ - 正确删除EGL Opengles 2.0

linux - 解压缩具有有限目录层次结构的文件

python - 如何成为一名优秀的 Python 程序员?

c# - 在 32 位 .NET 进程中分配超过 1,000 MB 的内存

java - 如何判断其中一代堆是否已满?

node.js - npm install 不适用于 gzipped tarball

python - 无法使用 python 提取 .xz 文件 "tarfile.ReadError: file could not be opened successfully"