Advertisement
p2k

line_buffer.py

p2k
Feb 11th, 2012
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.08 KB | None | 0 0
  1. from cStringIO import StringIO
  2.  
  3. class LineBuffer(object):
  4.     """
  5.    Simple line buffer implementation for line-based data streams.
  6.    
  7.    Use like this (in this example with a socket `s`):
  8.    
  9.    ------
  10.    from line_buffer import LineBuffer
  11.    ...
  12.    lb = LineBuffer()
  13.    while True:
  14.        lb.feed(s.recv(2048))
  15.        for line in lb:
  16.            print(line)
  17.        ...
  18.    ------
  19.    
  20.    If you set `strip` to False in the constructor, CR and LF are retained,
  21.    otherwise they are stripped.
  22.    """
  23.    
  24.     def __init__(self, strip=True):
  25.         self.strip = strip
  26.         self.buffer = StringIO()
  27.    
  28.     def feed(self, data):
  29.         self.buffer.write(data)
  30.    
  31.     def __iter__(self):
  32.         self.buffer.seek(0)
  33.         return self
  34.    
  35.     def next(self):
  36.         line = self.buffer.readline()
  37.         if line.endswith('\n'):
  38.             return line.strip('\r\n') if self.strip else line
  39.         else:
  40.             self.buffer.seek(0)
  41.             self.buffer.write(line)
  42.             self.buffer.truncate()
  43.             raise StopIteration
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement