Improve read_from_socket, a lot...

This commit is contained in:
Anders Ingemann 2015-01-16 01:52:42 +01:00
parent 7ef88d284d
commit 767b32d20e

View file

@ -14,7 +14,7 @@ def waituntil(predicate, timeout=5, interval=0.05):
return False return False
def read_from_socket(socket_path, termination_string, timeout): def read_from_socket(socket_path, termination_string, timeout, read_timeout=0.5):
import socket import socket
import select import select
import errno import errno
@ -22,15 +22,15 @@ def read_from_socket(socket_path, termination_string, timeout):
console.connect(socket_path) console.connect(socket_path)
console.setblocking(0) console.setblocking(0)
from timeit import default_timer
start = default_timer()
output = '' output = ''
ptr = 0 ptr = 0
continue_select = True continue_select = True
nooutput_for = 0
select_timeout = .5
while continue_select: while continue_select:
read_ready, _, _ = select.select([console], [], [], select_timeout) read_ready, _, _ = select.select([console], [], [], read_timeout)
if console in read_ready: if console in read_ready:
nooutput_for = 0
while True: while True:
try: try:
output += console.recv(1024) output += console.recv(1024)
@ -43,12 +43,11 @@ def read_from_socket(socket_path, termination_string, timeout):
if e.errno != errno.EWOULDBLOCK: if e.errno != errno.EWOULDBLOCK:
raise Exception(e) raise Exception(e)
continue_select = False continue_select = False
else: if default_timer() - start > timeout:
nooutput_for += select_timeout
if nooutput_for > timeout:
from exceptions import SocketReadTimeout from exceptions import SocketReadTimeout
msg = ('Reading from socket `{path}\' timed out after {seconds} seconds.' msg = ('Reading from socket `{path}\' timed out after {seconds} seconds.\n'
.format(path=socket_path, timeout=nooutput_for)) 'Here is the output so far:\n{output}'
.format(path=socket_path, seconds=timeout, output=output))
raise SocketReadTimeout(msg) raise SocketReadTimeout(msg)
console.close() console.close()
return output return output