在Python中实现自定义Str或缓冲区

时间:2018-07-19 23:25:32

标签: python python-2.7

我正在与python-gnupg一起解密文件,解密后的文件内容很大,因此将整个内容加载到内存中是不可行的。

我想短路write方法,以便在解密内容写入时对其进行操作

以下是一些失败的尝试:

import gpg
from StringIO import StringIO

# works but not feasible due to memory limitations
decrypted_data = gpg_client.decrypt_file(decrypted_data)

# works but no access to the buffer write method
gpg_client.decrypt_file(decrypted_data, output=buffer())

# fails with TypeError: coercing to Unicode: need string or buffer, instance found
class TestBuffer:
    def __init__(self):
        self.buffer = StringIO()

    def write(self, data):
        print('writing')
        self.buffer.write(data)

gpg_client.decrypt_file(decrypted_data, output=TestBuffer())

有人能想到让我创建类似文件的strbuffer对象以将数据输出到的任何其他想法吗?

1 个答案:

答案 0 :(得分:1)

您可以在I/O Base Classes中描述的io模块中实现一个类的子类,大概是io.BufferedIOBase。标准库以zipfile.ZipExtFile类的形式包含一个非常相似的示例。至少通过这种方式,您不必自己实现诸如readline之类的复杂功能。