add file streaming support

This commit is contained in:
Roman Zeyde
2014-07-21 11:18:17 +03:00
parent cb7162f50e
commit 88838fc72e
2 changed files with 55 additions and 0 deletions

33
stream.py Normal file
View File

@@ -0,0 +1,33 @@
import time
import common
import wave
class FileBuffer(object):
SAMPLES = 4096
BUFSIZE = int(SAMPLES * wave.bytes_per_sample)
WAIT = 0.1
TIMEOUT = 2.0
def __init__(self, fd):
self.fd = fd
def __iter__(self):
return self
def next(self):
block = bytearray()
finish_time = time.time() + self.TIMEOUT
while time.time() <= finish_time:
left = self.BUFSIZE - len(block)
data = self.fd.read(left)
if data:
block.extend(data)
if len(block) == self.BUFSIZE:
_, values = common.loads(str(block))
return values
time.sleep(self.WAIT)
raise IOError('timeout')

22
test_stream.py Normal file
View File

@@ -0,0 +1,22 @@
import stream
import wave
def test():
p = wave.record('-', stdout=wave.sp.PIPE)
f = stream.FileBuffer(p.stdout)
result = zip(range(10), f)
p.stop()
j = 0
for i, buf in result:
assert i == j
assert len(buf) == f.SAMPLES
j += 1
try:
for buf in f:
pass
except IOError as e:
assert str(e) == 'timeout'