python - 在 Python 中实现自定义 Str 或 Buffer

标签 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 对象来输出数据吗?

最佳答案

您可以实现I/O Base Classes中描述的io模块中的类之一的子类。 ,大概是 io.BufferedIOBase 。标准库包含 zipfile.ZipExtFile 类形式的非常相似的示例。至少这样,您就不必自己实现像 readline 这样的复杂函数。

关于python - 在 Python 中实现自定义 Str 或 Buffer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51433031/

相关文章:

python - Django 日期时间

python - 将 Python 列表转换为 JSON 文档

python-2.7 - 使用 BeautifulSoup 从 xml 中删除 img 标签

python - 从 CSV 中提取信息

python-2.7 - conda 更新 scikit-learn(还有 scipy 和 numpy)

python - 使用列表列表进行 Numpy 索引

python - 请问这个功能如何修复?

Python 同时循环、枚举和添加到字典

python - Linux 在 azure 中打印安全组时出错

python - 使用 Tkinter 时出现致命的 python 错误(pygame 降落伞)段错误