首页 > 解决方案 > 管道/流 gnupg 输出到 tarfile 中

问题描述

我有以下代码,但显然这不是真正的流媒体。这是我能找到的最好的,但它首先将整个输入文件读入内存。我想在解密大型(> 100Gb文件)时将其流式传输到tarfile模块而不使用我的所有内存

import tarfile, gnupg                                                                                                                                                                                                                                
gpg = gnupg.GPG(gnupghome='C:/Users/niels/.gnupg')                                                                         

with open('103330-013.tar.gpg', 'r') as input_file:                                                                                                                                                                                                   
    decrypted_data = gpg.decrypt(input_file.read(), passphrase='aaa')                                                       
    # decrypted_data.data contains the data                                                                                 
    decrypted_stream = io.BytesIO(decrypted_data.data)                                                                      

    tar = tarfile.open(decrypted_stream, mode='r|')                                                                                                                                                                                                 
    tar.extractall()                                                                                                                                                                                                                                
    tar.close()

标签: pythonstreampipetar

解决方案


显然,您不能使用 gpnupg 模块使用真正的流式传输,gnupg 模块总是将 gnupg 的整个输出读入内存。所以要使用真正的流媒体,你必须直接运行 gpg 程序。这是一个示例代码(没有适当的错误处理):

import subprocess
import tarfile

with open('103330-013.tar.gpg', 'r') as input_file:
   gpg = subprocess.Popen(("gpg", "--decrypt", "--homedir", 'C:/Users/niels/.gnupg', '--passphrase', 'aaa'), stdin=input_file, stdout=subprocess.PIPE)
   tar = tarfile.open(fileobj=gpg.stdout, mode="r|")
   tar.extractall()
   tar.close()

推荐阅读