使迭代器适应Python中类似文件对象的行为

使迭代器适应Python中类似文件对象的行为,第1张

使迭代器适应Python中类似文件对象的行为

这是应该从迭代器中分批读取的解决方案。

class some_magic_adaptor:  def __init__( self, it ):    self.it = it    self.next_chunk = ""  def growChunk( self ):    self.next_chunk = self.next_chunk + self.it.next()  def read( self, n ):    if self.next_chunk == None:      return None    try:      while len(self.next_chunk)<n:        self.growChunk()      rv = self.next_chunk[:n]      self.next_chunk = self.next_chunk[n:]      return rv    except StopIteration:      rv = self.next_chunk      self.next_chunk = None      return rvdef str_fn():  for c in 'a', 'b', 'c':    yield c * 3ff = some_magic_adaptor( str_fn() )while True:  data = ff.read(4)  if not data:    break  print data


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5647883.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存