首页 > 解决方案 > 在 Python 中实现自定义 Str 或 Buffer

问题描述

我正在使用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对象来输出数据?

标签: pythonpython-2.7

解决方案


您可以实现I/O 基类io中描述的模块中的一个类的子类,大概。标准库包含一个与类形式非常相似的示例。至少这样,你就不必像你自己那样实现复杂的功能了。io.BufferedIOBasezipfile.ZipExtFilereadline


推荐阅读