我正在与 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())
任何人都可以想到任何其他想法,可以让我创建一个类似文件的 str
或 buffer
对象来输出数据吗?
最佳答案
您可以实现I/O Base Classes中描述的io
模块中的类之一的子类。 ,大概是 io.BufferedIOBase 。标准库包含 zipfile.ZipExtFile 类形式的非常相似的示例。至少这样,您就不必自己实现像 readline
这样的复杂函数。
关于python - 在 Python 中实现自定义 Str 或 Buffer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51433031/