python - 在 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())
谁能想到任何其他想法可以让我创建一个类似文件str
或buffer
对象来输出数据?
解决方案
您可以实现I/O 基类io
中描述的模块中的一个类的子类,大概。标准库包含一个与类形式非常相似的示例。至少这样,你就不必像你自己那样实现复杂的功能了。io.BufferedIOBase
zipfile.ZipExtFile
readline
推荐阅读
- python-3.x - VueJS 让页面接受 UID 和令牌
- python - 执行回归后如何取消展平和图像?
- java - 在应用程序类之外使用 javafx 生成图形?
- python - 我收集模拟结果的最佳方式是什么?
- android - 尝试在 Webview PDF 中获取 Firebase URL 但出现问题
- html - 什么是请求有效载荷?
- c - 将整数读取到 C 中的文本文件中(整数存在于结构中)
- python - 我可以把这个数据框变成折线图吗
- .net - 有没有办法直接调用.NET 的控制台应用程序本机命令行解析器?
- node.js - 无法在 Node 中使用 GeoDataManager 查询 dynamoDb 数据